不断收到此崩溃错误,然后撞墙撞墙,以使此代码正常工作。该字符串设置为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]

10-06 16:11