【问题标题】:Sorted NSMutableArray and Remove Object排序的 NSMutableArray 和删除对象
【发布时间】:2013-11-06 07:51:57
【问题描述】:

我有一个 NSMutableArray 填充了自定义对象,我必须进行排序。 我读过可以使用以下代码对 NSMutableArray 进行排序。

NSSortDescriptor * sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey: @ "name" ascending: YES];
NSArray * sortDescriptors = [NSArray arrayWithObject: sortDescriptor];
[array sortUsingDescriptors: sortDescriptors];

但是,在这样做时,我遇到了一个问题,因为我必须删除 dell'NSMutableArray 中的元素,如果我尝试使用方法 [removeObject] 会出现错误,因为我无法从 NSArray 中删除对象 有没有办法解决这个问题? 谢谢, 文森佐

【问题讨论】:

    标签: ios objective-c nsmutablearray


    【解决方案1】:

    您可以在NSArray 对象上调用mutableCopy 以向您返回NSMutableArray,如下所示:

    NSMutableArray *mutableArray = [array mutableCopy];
    

    【讨论】:

      【解决方案2】:

      你这里有问题... NSMutableArray 的 sortUsingDescriptors: 对数组本身进行排序。它不返回 NSArray - 它“就地”对实例进行排序:https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html#//apple_ref/occ/instm/NSMutableArray/sortUsingDescriptors:

      所以你的代码是:

      NSMutableArray * myArray = ...
      [myArray sortUsingDescriptors:@[[[NSSortDescriptor alloc] initWithKey: @ "name" ascending: YES]]];
      [myArray removeObjectAtIndex:...]; // or any other method you like
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多