开发者

When i click reverse button contiously it is giving me the data repeatedly instead of once? why?

开发者 https://www.devze.com 2023-04-13 05:51 出处:网络
- (IBAction)reverseMethod { //NSUInteger count = [array1 count]; for( int i=[array1 count]-1;i<[array1 count];i--)
- (IBAction)reverseMethod
{   
    //NSUInteger count = [array1 count];

    for( int i=[array1 count]-1;i<[array1 count];i--)
    {
        [开发者_StackOverflow中文版array2 addObject:[array1 objectAtIndex:i]];
        NSLog (@"Object at index %d is: %@", 
               i, [array1 objectAtIndex: i]);


    }
    array1=array2;
    [tblMyTable reloadData];

}


If you are trying to reverse the objects of an array, you do it like this,

- (IBAction)reverseMethod { 

    array1 = [[array1 reverseObjectEnumerator] allObjects];
    [tblMyTable reloadData];
}


You are not clearing the array2 instance variable upon entering the reverseMethod. Every time you enter the reverseMethod the array1 objects are added again.

Either clear the array2 when entering the reverseMethod or define array2 locally within reverseMethod.

The elements are not reversing because the for-loop runs only while i<[array1 count] it should run until i > 0. You want to iterate from the last index of array1 to the first index, that being zero.

Also see this answer for a great example of reversing an NSArray.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号