Jason Jason - 1 year ago 81
iOS Question

Attempt to mutate immutable object with replaceOccurrencesOfString:withString:options:range:

Keep getting this crash error and banging my head against the wall trying to get this code to work. The string is set to a

. Any suggestions on what needs to be corrected?

@implementation JSONLoaderIngreds

- (NSArray *)ingredientsFromJSONFile:(NSURL *)url {
// Create a NSURLRequest with the given URL
NSURLRequest *request = [NSURLRequest requestWithURL:url

// 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;


Answer Source

NSMutableString *removewords in [[jsonDictionary objectForKey:@"locations"] valueForKey:@"ingredients"] just casts strings from jsonDictionary to NSMutableString, this can't make any string mutable.

Replace it to NSString *removewords in [[jsonDictionary objectForKey:@"locations"] valueForKey:@"ingredients"] and use NSMutableString * mutableRemovewords = [removewords mutableCopy].