NSError的正確用法


You Don’t Own Objects Returned by Reference

Some methods in Cocoa specify that an object is returned by reference (that is, they take an argument of type ClassName ** or id *). A common pattern is to use an NSError object that contains information about an error if one occurs, as illustrated by initWithContentsOfURL:options:error: (NSData) and initWithContentsOfFile:encoding:error: (NSString).

In these cases, the same rules apply as have already been described. When you invoke any of these methods, you do not create the NSError object, so you do not own it. There is therefore no need to release it, as illustrated in this example:

 

 1 NSString *fileName = <#Get a file name#>;
2 NSError *error = nil;
3 NSString *string = [[NSString alloc] initWithContentsOfFile:fileName
4 encoding:NSUTF8StringEncoding error:&error];
5 if (string == nil)
6 {
7 // Deal with error...
8 }
9 // ...
10 [string release];

之所以要用二重指針作為參數,是因為需要為NSError分配內存,有也就是說error本身存取的內容會改變,而參數傳遞屬於拷貝傳值,必須將指針的地址傳過去,通過指針的地址訪問指針,才改變的是指針的直.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM