If NSString stringWithContentsOfFile is deprecated, what is its replacement?

前端 未结 2 1413
没有蜡笔的小新
没有蜡笔的小新 2021-02-13 23:36

I have some sample code from Tuaw which is probably 3 releases old ;) The compiler is issuing a warning that the method is deprecated, but I do not see that mentioned in the SD

相关标签:
2条回答
  • 2021-02-14 00:31

    Here's an example, adding to Carl Norum's correct answer.

    Note the ampersand & prepended to the passed error variable.

    // 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);
        // …
    }
    
    • If you know the encoding, you specify that encoding by calling the + stringWithContentsOfFile:encoding:error: method.
    • If you do not know the character encoding and want iOS to guess, call the + stringWithContentsOfFile:usedEncoding:error: method which communicates back to you the detected encoding by setting the value of the usedEncoding argument. For discussion, see this other question.

    Bit of advice… Always make an attempt to know the character encoding of your file. Guessing is risky business.

    0 讨论(0)
  • 2021-02-14 00:35

    A more capable method replaced the old one. Use:

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

    Enjoy! Check out the documentation for more information.

    0 讨论(0)
提交回复
热议问题