2011-05-06 43 views
0

我有一个NSMutable数组,并试图找到此数组中最后一个对象的索引号。我尝试过,但感觉很累赘:如何确定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: ... 

谢谢!

回答

12

如果您需要索引,那么就是这样做的方法(int lastIndex = [array count] - 1;)。如果你只是想以取代但是不同对象的最后一个对象,你可以这样做:

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

干净简单的+1 – 2011-05-06 10:22:11

1

试试这个:

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

使用此片段:

int lastIndex = [YOUR_ARRAY count] - 1; 

这将赋予你最后index你的array

0

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

0
int index=[*yourarrayname* indexOfObject:[*yourarrayname* lastObject]]; 
NSLog(@"index=%d",index); 
相关问题