【问题标题】:If NSString stringWithContentsOfFile is deprecated, what is its replacement?如果不推荐使用 NSString stringWithContentsOfFile,它的替代品是什么?
【发布时间】:2010-06-02 03:54:19
【问题描述】:

我有一些来自 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];               

【问题讨论】:

    标签: iphone cocoa nsstring


    【解决方案1】:

    一种更强大的方法取代了旧方法。使用:

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

    享受吧!查看documentation了解更多信息。

    【讨论】:

    • 如果 BOOL 返回 NO 表示成功,请务必处理错误。很多示例代码都没有显示出来。
    【解决方案2】:

    这是一个例子,添加到Carl Norum's correct answer

    注意在传递的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);
        // …
    }
    

    忠告... 始终尝试了解文件的字符编码。猜测是有风险的事情。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-07
      • 1970-01-01
      • 2012-03-03
      • 2021-07-29
      • 2019-09-15
      相关资源
      最近更新 更多