不断收到此崩溃错误并用头撞墙试图让此代码正常工作。该字符串设置为 NSMutableString
。有什么需要更正的建议吗?
@implementation JSONLoaderIngreds
- (NSArray *)ingredientsFromJSONFile:(NSURL *)url {
// Create a NSURLRequest with the given URL
NSURLRequest *request = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:30.0];
// Get the data
NSURLResponse *response;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
// NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&error];
// Now create a NSDictionary from the JSON data
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
// Create a new array to hold the locations
NSMutableArray *locations = [[NSMutableArray alloc] init];
for(NSMutableString *removewords in [[jsonDictionary objectForKey:@"locations"] valueForKey:@"ingredients"]){
[removewords replaceOccurrencesOfString:@"[0-9]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, [removewords length])];
[removewords replaceOccurrencesOfString:@"tablespoons " withString:@"" options:1 range:NSMakeRange(0, [removewords length])];
[removewords replaceOccurrencesOfString:@"cups " withString:@"" options:1 range:NSMakeRange(0, [removewords length])];
[removewords replaceOccurrencesOfString:@"cup " withString:@"" options:1 range:NSMakeRange(0, [removewords length])];
//[removewords replaceOccurrencesOfString:@" Cup " withString:@"" options:1 range:NSMakeRange(0, [removewords length])];
[locations addObjectsFromArray:[removewords componentsSeparatedByString:@"\n"]];
NSLog(@"%@", locations);
}
// Return the array of Location objects
return locations;
}
@end
最佳答案
NSMutableString *removewords in [[jsonDictionary objectForKey:@"locations"] valueForKey:@"ingredients"]
只是将字符串从 jsonDictionary 转换为 NSMutableString,这不能使任何字符串可变。
替换为NSString *removewords in [[jsonDictionary objectForKey:@"locations"] valueForKey:@"ingredients"]
并使用 NSMutableString * mutableRemovewords = [removewords mutableCopy]
.
关于ios - 尝试用 replaceOccurrencesOfString :withString:options:range: 改变不可变对象(immutable对象),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39029326/