NSFileManager在初始化文件的时候一不留神就进入陷阱
今天调试一个程序,内容是在手机一个本地路径生成一个缓存文件,在生成本地路径的时候犯了一个错误,本着求原因的精神调试了2个小时,终于找到原因了
刚开始断点调试的时候,执行到第13行,这里死活不给写入数据,一直返回NO,看着我都蛋碎了,后来看到打印出来的路径在Library下,想着是不是这里不
允许用户在这里创建数据缓存,果然把2行的 NSDocumentationDirectory 改成 NSDocumentDirectory,之后路径就变成了:
file:///var/mobile/Applications/79D7DD73-74C5-4ECE-BEF7-5988560A8AC2/Documents/436783070;在这个Documents/路径下用户是可以创建自己的文件,而在 Library/Documentation/路径下是不允许用户写入文件..这里作为本地临时文件储存是要使用 NSDocumentDirectory而不是 NSDocumentationDirectory...
修改前:
1 -(NSURL *)uniqueDocumentURL{ 2 NSArray *documentDictiories = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentationDirectory inDomains:NSUserDomainMask];//注意这里的NSDocumentationDirectory 3 NSString * unique = [NSString stringWithFormat:@"%.0f",floor([NSDate timeIntervalSinceReferenceDate])]; 4 id URLObject = [documentDictiories firstObject] ; 5 return [URLObject URLByAppendingPathComponent:unique]; 6 } 7 8 -(NSURL *)imageURL{ 9 if (!_imageURL && self.image) { 10 NSURL * url = [self uniqueDocumentURL]; 11 if (url) { 12 NSData * imageData = UIImageJPEGRepresentation(self.image, 1.0); 13 if ([imageData writeToURL:url atomically:YES]) {//问题 14 _imageURL = url; 15 } 16 } 17 } 18 return _imageURL; 19 } 20 21 //控制台打印 22 Printing description of url: 23 file:///var/mobile/Applications/16614FF0-B641-4938-8BF8-91658759D4D8/Library/Documentation/436783128
修改后:
1 - (NSURL *)uniqueDocumentURL 2 { 3 NSArray *documentDirectories = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask]; 4 NSString *unique = [NSString stringWithFormat:@"%.0f", floor([NSDate timeIntervalSinceReferenceDate])]; 5 return [[documentDirectories firstObject] URLByAppendingPathComponent:unique]; 6 } 7 8 - (void)setImage:(UIImage *)image 9 { 10 self.imageView.image = image; 11 12 // when image is changed, we must delete files we've created (if any) 13 [[NSFileManager defaultManager] removeItemAtURL:_imageURL error:NULL]; 14 [[NSFileManager defaultManager] removeItemAtURL:_thumbnailURL error:NULL]; 15 self.imageURL = nil; 16 self.thumbnailURL = nil; 17 } 18 19 20 Printing description of url: 21 file:///var/mobile/Applications/79D7DD73-74C5-4ECE-BEF7-5988560A8AC2/Documents/436783070