为什么向 NSMutableArray 添加字符串不起作用?
why adding string to NSMutableArray not work?
为什么向 nsmuarray 添加字符串不起作用?
首先,我通过键路径将 NSDictionary 添加到 NSMutableArray,
是工作。
之后我想再添加一个字符串,但它不起作用。
NSMutableArray *_joinornot;
_joinornot = [[NSMutableArray alloc] init];
NSDictionary *tempobject = [[NSDictionary alloc] init];
_joinornot = [tempobject valueForKeyPath:@"groupid"];
到目前为止一切正常。
[_joinornot addObject:@"111"];<----unrecongnized selector sent to instance
如果_joinornot = [tempobject valueForKeyPath:@"groupid"];
returns nil,那么你的数组就是nil,那么你就不能调用addObject了。所以也许添加一个零检查
试试下面的代码:
在添加对象之前,只需检查 nil
。
NSMutableArray *_joinornot;
_joinornot = [[NSMutableArray alloc] init];
NSDictionary *tempobject = [[NSDictionary alloc] init];
_joinornot = [tempobject valueForKeyPath:@"groupid"];
if (_joinornot==nil) {
_joinornot = [[NSMutableArray alloc] init];
[_joinornot addObject:@"111"];
}
else{
[_joinornot addObject:@"111"];
}
编辑:
可能是它被转换为 NSArray 所以它不再可变,试试
_joinornot = [[tempobject valueForKeyPath:@"groupid"] mutableCopy];
看起来像“_joinornot”它不是NSMutableArray或NSMutable数据类型,试试看它是什么类型的对象:
NSLog(@"%@", [_joinornot class]);
如果不是Mutable类型的子类就不能给他添加对象
为什么向 nsmuarray 添加字符串不起作用? 首先,我通过键路径将 NSDictionary 添加到 NSMutableArray, 是工作。 之后我想再添加一个字符串,但它不起作用。
NSMutableArray *_joinornot;
_joinornot = [[NSMutableArray alloc] init];
NSDictionary *tempobject = [[NSDictionary alloc] init];
_joinornot = [tempobject valueForKeyPath:@"groupid"];
到目前为止一切正常。
[_joinornot addObject:@"111"];<----unrecongnized selector sent to instance
如果_joinornot = [tempobject valueForKeyPath:@"groupid"];
returns nil,那么你的数组就是nil,那么你就不能调用addObject了。所以也许添加一个零检查
试试下面的代码:
在添加对象之前,只需检查 nil
。
NSMutableArray *_joinornot;
_joinornot = [[NSMutableArray alloc] init];
NSDictionary *tempobject = [[NSDictionary alloc] init];
_joinornot = [tempobject valueForKeyPath:@"groupid"];
if (_joinornot==nil) {
_joinornot = [[NSMutableArray alloc] init];
[_joinornot addObject:@"111"];
}
else{
[_joinornot addObject:@"111"];
}
编辑:
可能是它被转换为 NSArray 所以它不再可变,试试
_joinornot = [[tempobject valueForKeyPath:@"groupid"] mutableCopy];
看起来像“_joinornot”它不是NSMutableArray或NSMutable数据类型,试试看它是什么类型的对象:
NSLog(@"%@", [_joinornot class]);
如果不是Mutable类型的子类就不能给他添加对象