When i click reverse button contiously it is giving me the data repeatedly instead of once? why?
- (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.
精彩评论