Reputation: 893
NSMutableArray * Cars = [NSMutableArray arrayWithObjects:
@"Audi", @"BMW",
@"Audi Quattro", @"Audi", nil];
How to get the last previous object from a NSMutableArray? Also each time when i add a new object, i want to fetch the last previous object in the NSMutableArray. Can any one please help.
Upvotes: 1
Views: 2221
Reputation: 1
In this case, I think using category makes sense.
In NSArray category, you can declare a method like:
@implementation NSArray (Utils)
- (id)getNextToLastObject {
if (self.count < 2) {
return nil;
} else {
return [self objectAtIndex: self.count - 2];
}
}
@end
Then it can be called for any array in the project like:
Model *model = [modelArray getNextToLastObject];
ps: You should import your category class's header file to your controller.
Upvotes: 0
Reputation: 333
NSMutableArray *car=[[NSMutableArray alloc]init];
car = [NSMutableArray arrayWithObjects:@"Audi", @"BMW",@"Audi Quattro", @"Audi", nil];
int count=(int)[car count];
NSLog(@"Object at second last index %@",[car objectAtIndex:count-2]);
Upvotes: 0
Reputation: 7552
For the last object:
id lastObject = array.lastObject;
For the second to last object:
id previousLastObject = array.lastObject;
[array addObject:newObject];
Or
[array addObject:newObject];
id previousLastObject = array[array.count - 2];
Upvotes: 4