2014-03-05 56 views
1

我有两个类 - BNRItem和BNRContainer。 BNRContainer是BNRItem的一个子类。为了减少代码我贴的数量,假设以下是我已经测试并知道作品:为什么我在尝试将对象添加到NSMutableArray时遇到SIGABRT

+(BNRItem *) randomItem; // allocate and init a random item. 

@property(nonatomic, readwrite, copy) NSMutableArray * subitems; // This is a property of BNRContainer class 

main.m: 

NSMutableArray * rand_items = [NSMutableArray alloc] init]; 
for (int i = 0; i < 10; i++) { 
    [rand_items addObject: [BNRItem randomItem]]; 
} 

[rand_items addObject: @"HELLO"]; 

BNRContainer * rand_container_of_items = [BNRContainer randomItem]; 
rand_container_of_items.subitems = rand_items; 

[rand_container_of_items.subitems addObject: @"THERE"]; // ERROR SIGABRT 

NSLog(@"------------------------------------------------------"); 
NSLog(@"%@", rand_container_of_items); 

rand_container_of_items = nil; 

如果我NSLog无需添加@“有”,我看到“Hello”在我的描述,所以我知道我可以在那个时候致电addObject:。当我试图访问rand_container_of_items的ivar“子项目”时,为什么我会得到SIGABRT?我无法弄清楚这一点。

+0

PLZ,没有更多的snake_case! – Dam

回答

2

问题似乎是您的声明中的拷贝修饰符。

@property (nonatomic, readwrite, copy) NSMutableArray *subitems; 

documentation中,NSCopying协议一致性是继承形式的NSArray,所以我的怀疑的是,在这一行

rand_container_of_items.subitems = rand_items; 

subitems包含原始阵列的不可改变的副本。尝试从您的声明中删除副本。如果您需要复印,请使用mutableCopy方法。

+0

我建议添加[rand_items mutableCopy] – Milo

+0

@MiloGosnell已经做了!不管怎么说,还是要谢谢你! – Merlevede

+0

谢谢。我现在知道了.. – noobuntu

1

问题就在这里

property(nonatomic, readwrite, copy) NSMutableArray * subitems; 

你不应该使用copy在这里,因为它会返回对象的immutable副本。所以你不能添加对象。它可能是

property(nonatomic, strong) NSMutableArray * subitems; 
0

这行给sigbart,因为当您将数组分配给可变数组时,它变为可变。

因此,当您将rand_items复制到rand_container_of_items.subitem时,它变得可变。

所以,使其一成不变,尝试以下操作:

BNRContainer * rand_container_of_items = [BNRContainer randomItem]; 
rand_container_of_items.subitems = [rand_items mutablecopy]; 

[rand_container_of_items.subitems addObject:@"THERE"]; // ERROR SIGABRT 
相关问题