如果NSString的stringWithContentsOfFile方法被弃用了,那么它的替代方法是什么?

12

我从Tuaw的一些示例代码中获取了一些代码,它可能已经过时了三个版本 ;) 编译器发出一个警告,说这种方法已被弃用,但我在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个回答

18

一种更为高效的方法已经取代了旧方法。请使用:

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

祝您使用愉快! 请查看文档以获取更多信息。


请确保处理错误,如果BOOL返回NO表示成功。许多示例代码没有显示这一点。 - uchuugaka

18

这里是一个例子,补充了Carl Norum的正确答案

请注意在传递的error变量前面添加的和号&

// 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);
    // …
}

一点建议... 务必尝试了解文件的字符编码方式,猜测是危险的行为。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接