如果不推荐使用NSString stringWithContentsOfFile,它的替换是什么?

时间:2010-06-02 03:54:20

标签: iphone cocoa nsstring

我有一些来自Tuaw的示例代码,可能是3个旧版本;)编译器发出警告说该方法已被弃用,但我没有看到SDK文档中提到的那些。如果不推荐使用,则必须采用替代方法或替代方法。有谁知道这种方法的替代品是什么?

具体代码是:

NSArray *crayons = [[NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"crayons" ofType:@"txt"]] componentsSeparatedByString:@"\n"];

修改后的代码(在离散的白痴步骤中 - 并且没有错误处理)是:

NSError *error;
NSString *qs = [[NSBundle mainBundle] pathForResource: @"crayons" ofType: @"txt"];
NSString *ps = [[NSString alloc] stringWithContentsOfFile:qs encoding:NSUTF8StringEncoding error: &error];
NSArray *crayons = [[NSArray alloc] arrayWithContentsOfFile: ps];               

2 个答案:

答案 0 :(得分:18)

更有能力的方法取代旧方法。使用:

+ (id)stringWithContentsOfFile:(NSString *)path
                  usedEncoding:(NSStringEncoding *)enc
                         error:(NSError **)error

享受!有关详细信息,请查看documentation

答案 1 :(得分:18)

以下是一个示例,添加到Carl Norum's correct answer

请注意传入错误变量前后的&符号&

// The source text file is named "Example.txt". Written with UTF-8 encoding.
NSString* path = [[NSBundle mainBundle] pathForResource:@"Example"
                                                 ofType:@"txt"];
NSError* error = nil;
NSString* content = [NSString stringWithContentsOfFile:path
                                              encoding:NSUTF8StringEncoding
                                                 error:&error];
if(error) { // If error object was instantiated, handle it.
    NSLog(@"ERROR while loading from file: %@", error);
    // …
}

一点建议......总是试图了解文件的字符编码。猜测是有风险的业务。