考慮以下兩個代碼示例:爲什麼在創建新文件時使用NSFileManager而不是僅僅使用NSData的writeToFile:atomically:方法?
NSData *imgData = UIImagePNGRepresentation(imgFull);
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"itemImg_%i.png", timestamp]]; //add our image to the path
[imgData writeToFile:fullPath atomically:YES];
和
NSData *imgData = UIImagePNGRepresentation(imgFull);
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"itemImg_%i.png", timestamp]]; //add our image to the path
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager createFileAtPath:fullPath contents:imgData attributes:nil];
第二個例子需要的代碼和一個的NSFileManager對象的初始化一個額外的行,而第一實施例簡單地具有NSData對象imgData
將自己寫入文件。第一個示例的另一個優點是可以覆蓋同名的預先存在的文件。
我的問題是:創建新的文件,在什麼情況下,你會真的想使用的NSFileManager和方法createFileAtPath:contents:attributes:
什麼時候?
的NSData的將writeToFile不會改寫爲默認值,從我的經驗。 NSFileManager的createFileAtPath也沒有屬性:nil。有關屬性NSDictionary方法的信息即將出現,這表明它並不常用。 – 2013-06-27 21:09:15