replaceObjectAtIndex:withObject:Error

时间:2012-07-30 23:50:58

标签: objective-c

有人可以看到错误在哪里......

NSArray *arr = [str componentsSeparatedByString:@","];
NSString *inputStr = [arr objectAtIndex:0];
NSString *trimmedStr = [inputStr stringByTrimmingCharactersInSet:
                               [NSCharacterSet whitespaceAndNewlineCharacterSet]]; 
[[arr objectAtIndex:0] replaceObjectAtIndex:0 withObject:trimmedStr];   

输出:

-[__NSCFString replaceObjectAtIndex:withObject:]: 
unrecognized selector sent to instance 0x68a8eb0
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', 
reason: '-[__NSCFString replaceObjectAtIndex:withObject:]: 
unrecognized selector sent to instance 0x68a8eb0'

编辑:添加额外的行以显示已声明并填充数组 正如下面评论中所述,当我更换这一行时:

[[arr objectAtIndex:0] replaceObjectAtIndex:0 withObject:trimmedStr];  

使用:

[arr replaceObjectAtIndex:0 withObject:trimmedStr];  

Xcode错误(运行前):

 No visible @interface for 'NSArray' declares the selector 'replaceObjectAtIndex:withObject'

3 个答案:

答案 0 :(得分:3)

这是错误的:

[[arr objectAtIndex:0] replaceObjectAtIndex:0 withObject:trimmedStr];

你真正想做的是:

[arr replaceObjectAtIndex:0 withObject:trimmedStr];

你发送了replaceObjectAtIndex到数组中的字符串([arr objectAtIndex:0]),这显然无法解决。将该消息发送到(可变)数组,它将用新的字符串替换该字符串。

关于你的下一个问题:告诉我们更多关于你要做的事情等等,并且不要将自己限制在不到10个单词。您提供的详细信息越多,您获得的帮助就越多。

答案 1 :(得分:1)

虽然我不肯定你正在尝试做什么(因为我不知道arr是什么),但似乎你从你的数组中得到一个NSString对象,试图对其执行replaceObjectAtIndex:withObject:。也许你的意思是:

[arr replaceObjectAtIndex:0 withObject:trimmedStr];

答案 2 :(得分:1)

只是为了它,这是正确的解决方法:

NSMutableArray *arr = [[[str componentsSeparatedByString:@","] mutableCopy] autorelease];
NSString *inputStr = [arr objectAtIndex:0];
NSString *trimmedStr = [inputStr stringByTrimmingCharactersInSet:
                           [NSCharacterSet whitespaceAndNewlineCharacterSet]]; 
[arr replaceObjectAtIndex:0 withObject:trimmedStr];   

或者,如果您使用ARC:

NSMutableArray *arr = [[str componentsSeparatedByString:@","] mutableCopy];
NSString *inputStr = [arr objectAtIndex:0];
NSString *trimmedStr = [inputStr stringByTrimmingCharactersInSet:
                           [NSCharacterSet whitespaceAndNewlineCharacterSet]]; 
[arr replaceObjectAtIndex:0 withObject:trimmedStr];