2010-06-02 111 views
12

我有一些來自Tuaw的示例代碼,可能是3版本;)編譯器發出一個警告,說該方法已被棄用,但我沒有看到在SDK文檔中提到的。如果它被棄用,則必須有其他方法或替代方法。有人知道這種方法的替代是什麼?如果NSString stringWithContentsOfFile已被棄用,它的替代是什麼?

特定代碼是:

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];    

回答

18

更能夠方法替換舊的。使用方法:

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

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

+0

如果BOOL成功返回NO,請務必處理該錯誤。很多示例代碼沒有顯示。 – uchuugaka 2014-04-19 08:39:01

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

一點忠告......總是要試圖瞭解你的文件的字符編碼。猜測是有風險的事情。

相關問題