0

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

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

当我使用 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:@""];
4

3 回答 3

3

是NSString的stringByReplacingOccurrencesOfString一个方法,返回值也是一个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:一点。

于 2012-07-29T00:43:55.813 回答
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 :范围

于 2012-07-29T00:06:15.690 回答
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
于 2012-07-29T00:09:44.713 回答