从NSMutableArray中删除对象时崩溃

时间:2013-08-06 13:19:29

标签: objective-c nsmutablearray

我在NSMutableArray初始化了viewDidLoad

 self.titlesTagArreys = [@[@"Dollar", @"Euro", @"Pound",@"Dollar longString", @"Euro longStringlongString", @"Pound",@"Dollar", @"Euro", @"PoundlongStringlongString"]mutableCopy];

在.h:

 @property(nonatomic, copy) NSMutableArray* titlesTagArreys;

当我尝试删除一个项目时,应用程序崩溃:

-(void)removeButtonWasPressed:(NSString*)tagTitle{
    NSLog(@"tagTitle - %@",tagTitle);
    NSLog(@"self.titlesTagArreys - %@",self.titlesTagArreys);    
    [self.titlesTagArreys removeObject:tagTitle];
}

这是日志:

2013-08-06 16:15:03.989 EpicTv[6378:907] tagTitle - Dollar
2013-08-06 16:15:03.991 EpicTv[6378:907] self.titlesTagArreys - (
    Dollar,
    Euro,
    Pound,
    "Dollar longString",
    "Euro longStringlongString",
    Pound,
    Dollar,
    Euro,
    PoundlongStringlongString
)
[__NSArrayI removeObject:]: unrecognized selector sent to instance 0x1c53bbd0
 *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI removeObject:]: unrecognized selector sent to instance 0x1c53bbd0'
*** First throw call stack:
(0x327162a3 0x3a5c197f 0x32719e07 0x32718531 0x3266ff68 0x20ad55 0x20c9a5 0x20bf5d 0x346090c5 0x34609077 0x34609055 0x3460890b 0x34608e01 0x345315f1 0x3451e801 0x3451e11b 0x362295a3 0x362291d3 0x326eb173 0x326eb117 0x326e9f99 0x3265cebd 0x3265cd49 0x362282eb 0x34572301 0xafb89 0xa4d68)
libc++abi.dylib: terminate called throwing an exception

4 个答案:

答案 0 :(得分:6)

似乎titlesTagArray列出的不是NSMutableArray,因为无法调用removeObject。 也许您之前已将代码NSArray传递给titlesTagArreys

尝试使用

init数组
self.titlesTagArreys = [NSMutableArray arrayWithArray:@[@"...",@"...",...]];

@property(非原子,复制)制作一个不可变的NSMutableArray副本。尝试@property(非原子,保留)而不是复制

答案 1 :(得分:5)

我还认为由于某些代码更改,您titlesTagArreys不是可变数组

尝试添加:NSLog(@"%@", NSStringFromClass(self.titlesTagArreys.class));以检查您使用的是哪个班级

-(void)removeButtonWasPressed:(NSString*)tagTitle{

  NSLog(@"%@", NSStringFromClass(self.titlesTagArreys.class));

  [self.titlesTagArreys removeObject:tagTitle];
}

答案 2 :(得分:0)

我遇到了同样的问题,并了解到必须覆盖可变数组属性的 setter 并调用mutableCopy。您将在Stack Overflow here中找到答案。

答案 3 :(得分:0)

titlesTagArray不是NSMutableArray。这是因为,在日志中我们可以看到发送到实例0x1c53bbd0的[__NSArrayI removeObject:]无法识别的选择器。 NSArrayI也用于NSArray,NSArrayM用于NSMutableArray。 您必须使用NSArray初始化mutablearray,因此例外。