【问题标题】:Adding an object at a specific index of an NSMutableArray在 NSMutableArray 的特定索引处添加对象
【发布时间】:2011-07-05 11:22:19
【问题描述】:

如何在NSMutableArray 的特定索引处添加对象?

如何将对象添加到数组的前面?

【问题讨论】:

    标签: objective-c nsmutablearray foundation


    【解决方案1】:

    为 Swift 3 更新:

    如果要在 NSMutableArray 的特定索引处添加对象,请使用下面的简单代码行:

    self.yourMutableArrayName.insert(<#T##newElement: String##String#>, at: <#T##Int#>)
    

    示例:如果要添加字符串:"Nature" at index: 3

    var str = "Nature"
    self.yourMutableArrayName.insert(str, at: 3) 
    

    // 享受..! 

    【讨论】:

      【解决方案2】:
      [myMutableArray insertObject:myObject atIndex:42];
      

      要将对象添加到数组的前面,请使用 0 作为索引:

      [myMutableArray insertObject:myObject atIndex:0];
      

      【讨论】:

      • 如果我尝试在一个新分配的可变数组上运行第一条语句,而其中目前没有数据?
      • 很棒的答案!谢谢
      【解决方案3】:

      看看NSMutableArray类的insertObject:atIndex:方法。添加到数组的“前面”意味着索引 0。

      例如:

      NSMutableArray * array = [[NSMutableArray alloc] initWithCapacity:3];
      [array addObject:@"b"]; // Contains "b"
      [array insertObject:@"a" atIndex:0]; // Contains "a", "b"
      [array insertObject:@"c" atIndex:2]; // Contains "a", "b", "c"

      【讨论】:

        猜你喜欢
        • 2012-12-08
        • 1970-01-01
        • 2011-09-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-29
        • 2015-04-17
        • 1970-01-01
        相关资源
        最近更新 更多