【发布时间】:2013-02-13 15:14:17
【问题描述】:
我在创建 TableView class 时犯了一个错误,并且在我定义它时不小心将我的 @property 保留为 copy:
@property (copy, nonatomic) NSMutableArray *words;
我“正确”初始化了数组:(注意这是第三次尝试,所以请忽略我没有使用 mutableCopy 和其他更好的方法)
NSArray *fixedWords = @[@"Eeny", @"Meeny", @"Miny", @"Moe", @"Catch", @"A", @"Tiger", @"By", @"His", @"Toe"];
NSMutableArray *mutWords = [[NSMutableArray alloc] initWithArray:fixedWords];
self.words = mutWords;
但是当我后来重新排序数组时,它在 removeObjectAtIndex 行上崩溃了:
id object = [self.words objectAtIndex:fromIndexPath.row];
NSUInteger from = fromIndexPath.row;
NSUInteger to = toIndexPath.row;
[self.words removeObjectAtIndex:from];
带有错误信息
unrecognized selector sent to instance
花了很多时间才发现这是因为副本意味着分配 NSMutableArray 会导致创建标准(非可变)NSArray。谁能解释为什么这是正确的行为?
【问题讨论】:
-
@property (copy, nonatomic) NSMutableArray *words;不使用复制,你应该使用保留。 -
或强而不是保留
-
哈,我来到这里是因为我希望今天有一种方法可以做到
@property (nonatomic, mutableCopy)。哦,好吧,随着 swift 即将逐步淘汰 Objective-C,我猜它永远不会发生了。
标签: ios objective-c nsmutablearray nsarray