如何确定NSMutableArray中最后一个对象的索引号

时间:2011-05-06 10:18:03

标签: iphone objective-c cocoa-touch nsmutablearray

我有一个NSMutable数组,并试图找到此数组中最后一个对象的索引号。我尝试过这个,但感觉很麻烦:

 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);

还有另一种方法吗?我的问题的背景是我需要确定最后一个对象才能改变它:

replaceObjectAtIndex:[last object] withObject: ...

谢谢!

5 个答案:

答案 0 :(得分:12)

如果您需要索引,那么就可以这样做(int lastIndex = [array count] - 1;)。如果您只想用不同的对象替换最后一个对象,则可以执行以下操作:

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

答案 1 :(得分:1)

试试这个:

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

答案 2 :(得分:0)

使用此代码段:

int lastIndex = [YOUR_ARRAY count] - 1;

这将为您提供index的最后array

答案 3 :(得分:0)

如果您使用NSMutableArray方法向addObjects:添加对象,则总是将元素放在最后。当您removeObjectAtIndex:index时,它会自动向下移动1个位置,所有元素的索引都是> index。这就是数组中最后一个对象始终具有索引[array count] - 1的原因。我没有告诉你有关替换对象的事情,我只是告诉你添加对象。

答案 4 :(得分:0)

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