【问题标题】:Replace object Index in NSMutableArray替换 NSMutableArray 中的对象索引
【发布时间】:2011-11-21 13:16:48
【问题描述】:

我有NSMutableArray。例如有这样的对象:0、1、2。 如何将对象0 替换为对象2 所在的索引。结果我想要带有对象的数组:1、2、0。谢谢。

【问题讨论】:

    标签: objective-c object replace nsmutablearray


    【解决方案1】:

    @trojanfoe,你的回答有一个简单的错误。

    代码的第一行没有按照文档返回任何内容。应该是这样的,

    id object = [[array objectAtIndex:0] retain];
    [array removeObjectAtIndex:0];
    [array insertObject:object atIndex:2];
    [object release];
    

    【讨论】:

    • 这是评论而非答案。
    • 没有必要保留和稍后释放object,因为objectAtIndex返回一个保留和自动释放的对象。
    【解决方案2】:
    [array addObject:[array objectAtIndex:0]];
    [array removeObjectAtIndex:0];
    

    【讨论】:

      【解决方案3】:

      首先获取对象的副本,然后将其从索引 0 中删除,然后将其添加到索引 2。

      id object = [array objectAtIndex:0];
      [array removeObjectAtIndex:0];
      [[array insertObject:object atIndex:2];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-05
        • 1970-01-01
        • 2011-09-19
        相关资源
        最近更新 更多