使用NSMutableString和stringByReplacingOccurrencesOfString时,指针类型错误不兼容

时间:2012-07-28 23:46:51

标签: ios

下面显示的代码的目的是从文本字段中取一个字符串并删除逗号和左括号,以准备转换为float的内容。例如,它取数字1,234,567并将其更改为1234567。

代码段有效,但返回信息错误“从String *分配给NSMutableString *的指针类型不兼容”

当我使用NSString而不是NSMutableString时,我没有错误,但返回的值是一个空字符串。

使用NSMutableString方法,问题是什么以及如何更改它以消除“不兼容的指针类型”错误。

NSMutableString *cleanedDataCellTest = [[NSMutableString alloc] initWithString:datacellR2C2.text];
cleanedDataCellTest =  [cleanedDataCellTest stringByReplacingOccurrencesOfString:@"," withString:@""];
cleanedDataCellTest =  [cleanedDataCellTest stringByReplacingOccurrencesOfString:@")" withString:@""];
cleanedDataCellTest =  [cleanedDataCellTest stringByReplacingOccurrencesOfString:@"(" withString:@"-"];
cleanedDataCellTest =  [cleanedDataCellTest stringByReplacingOccurrencesOfString:@" " withString:@""];

3 个答案:

答案 0 :(得分:3)

stringByReplacingOccurrencesOfString是NSString的方法,返回值也是NSString。因此,您无法将返回值分配给NSMutableString变量。

相反,您可以使用replaceOccurrencesOfString:withString:options:range:中的方法NSMutableString

NSMutableString *cleanedDataCellTest = [[NSMutableString alloc] initWithString:@"1,234,567"];
[cleanedDataCellTest replaceOccurrencesOfString:@"," withString:@"" options:0 range:NSMakeRange(0, cleanedDataCellTest.length)];
[cleanedDataCellTest replaceOccurrencesOfString:@")" withString:@"" options:0 range:NSMakeRange(0, cleanedDataCellTest.length)];
[cleanedDataCellTest replaceOccurrencesOfString:@"(" withString:@"-" options:0 range:NSMakeRange(0, cleanedDataCellTest.length)];
[cleanedDataCellTest replaceOccurrencesOfString:@" " withString:@"" options:0 range:NSMakeRange(0, cleanedDataCellTest.length)];

但是,考虑到性能,我认为使用NSString及其方法stringByReplacingOccurrencesOfString更有效。

更新:抱歉,昨天我没有测试"性能"。我刚刚做了一个测试,通过替换字符串中的一些东西(大约26KB),使用NSMutableString和replaceOccurrencesOfString:withString:options:range:稍微更有效

答案 1 :(得分:2)

NSMutableString *cleanedDataCellTest = [[NSMutableString alloc] initWithString:datacellR2C2.text];
[cleanedDataCellTest replaceOccurrencesOfString:@"," withString:@"" options:0 range:NSMakeRange(0, cleanedDataCellTest.length)];

参考:https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/nsmutablestring_Class/Reference/Reference.html#//apple_ref/occ/instm/NSMutableString/replaceOccurrencesOfString:withString:options:range

答案 2 :(得分:1)

切换到NSString对我有用......:

NSString *cleanedDataCellTest = [[NSString alloc] initWithString:@"1,234,098"];
cleanedDataCellTest =  [cleanedDataCellTest stringByReplacingOccurrencesOfString:@"," withString:@""];
cleanedDataCellTest =  [cleanedDataCellTest stringByReplacingOccurrencesOfString:@")" withString:@""];
cleanedDataCellTest =  [cleanedDataCellTest stringByReplacingOccurrencesOfString:@"(" withString:@"-"];
cleanedDataCellTest =  [cleanedDataCellTest stringByReplacingOccurrencesOfString:@" " withString:@""];
NSLog(@"cleanedDataCellTest = %@", cleanedDataCellTest);

节目:

cleanedDataCellTest = 1234098