0

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

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'
4

3 回答 3

3

这是错的:

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

你真正想做的是:

[arr replaceObjectAtIndex:0 withObject:trimmedStr];

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

对于你的下一个问题:告诉我们更多关于你想要做什么等,不要限制自己少于 10 个字。你提供的细节越多,你得到的帮助就越多。

于 2012-07-30T23:56:56.980 回答
1

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

[arr replaceObjectAtIndex:0 withObject:trimmedStr];
于 2012-07-30T23:57:44.070 回答
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];   
于 2012-07-31T06:22:52.350 回答