尝试使用replaceOccurrencesOfString:withString:options:

时间:2016-08-19 00:13:22

标签: ios objective-c arrays string

继续发生此崩溃错误,并试图让这段代码正常工作。该字符串设置为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

1 个答案:

答案 0 :(得分:1)

NSMutableString *removewords in [[jsonDictionary objectForKey:@"locations"] valueForKey:@"ingredients"]只是将jsonDictionary中的字符串转换为NSMutableString,这不会使任何字符串变为可变。

将其替换为NSString *removewords in [[jsonDictionary objectForKey:@"locations"] valueForKey:@"ingredients"]并使用NSMutableString * mutableRemovewords = [removewords mutableCopy]