ios - 尝试用 replaceOccurrencesOfString :withString:options:range: 改变不可变对象(immutable对象)

标签 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

最佳答案

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/

相关文章:

iOS 谷歌地图 SDK : Setting maxZoom level issue when using Tiles

iOS - 表格 View - 静态单元格(分组) - 更改节标题文本颜色

ios - 如何使用 GCD 说明后台任务?

ruby - 导轨 : CSV Array to string (convert)

ios - 清除 drawRect shape-layer 绘图中的绘图

iphone - iOS UISlider 自定义。从中心显示突出显示

objective-c - 有没有办法获取另一个 NSString 中出现的 NSString 的 NSRanges 的 NSArray?

ios - 无法从 NSString 中提取子字符串

javascript - 根据提示存储坐标并计算距离

javascript - 将 JS 数组按键构建为一个 - 寻找最佳解决方案