开发者

How to determine the index number of the last object in a NSMutable Array

I have a NSMutable Array and was trying to find the index number of the last object in this array. I tried this, but it feels cumbersome:

 int currentCount = [[[self.myLibrary objectAtIndex:currentNoteBookNumber] tabColours] count];
    NSLog(@"Number of tab colours total: %i", currentCount);
NSLog(@"Index number of last object: %i", currentCount-1);

Is there another way of doing this? The context of my problem is that I need to determine the last object in order to change it:

replaceObjectAtIndex:[last object] withObject: ...
开发者_开发知识库

Thanks!


If you need the index, then that is the way to do it (int lastIndex = [array count] - 1;). If you just want to replace the last object with a different object however, you can do:

[array removeLastObject];
[array addObject: newLastObject];


Try this:

[myArray replaceObjectAtIndex:[myArray count]-1 withObject:someNewObject];


If you add objects to your NSMutableArray with addObjects: method it always put elements at the end. When you removeObjectAtIndex:index it automatically shift down on 1 position all elements with indexes > index. That is why the last object in array is always have index [array count] - 1. I do not tell you about replacing objects, I just tell about adding objects.


int index=[*yourarrayname* indexOfObject:[*yourarrayname* lastObject]];
NSLog(@"index=%d",index);


Use this snippet:

int lastIndex = [YOUR_ARRAY count] - 1;

this will gives you last index of your array.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜