【问题标题】:How to determine the index number of the last object in a NSMutable Array如何确定 NSMutableArray 中最后一个对象的索引号
【发布时间】:2011-05-06 10:18:02
【问题描述】:

我有一个 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: ...

谢谢!

【问题讨论】:

    标签: iphone objective-c cocoa-touch nsmutablearray


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      试试这个:

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

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          【解决方案4】:
          int index=[*yourarrayname* indexOfObject:[*yourarrayname* lastObject]];
          NSLog(@"index=%d",index);
          

          【讨论】:

            【解决方案5】:

            使用这个sn-p:

            int lastIndex = [YOUR_ARRAY count] - 1;
            

            这将为您提供array 中的最后一个index

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2011-03-05
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2012-12-08
              相关资源
              最近更新 更多