我想使用以下代码保存图像:
- (void)writeData{ if(cacheFileName==nil) return; if(cacheDirectoryPath==nil) return; if (![[NSFileManager defaultManager] fileExistsAtPath:[self filePath]]) { NSData *imageData = UIImageJPEGRepresentation(self.image, 0.9); NSError *writeError= nil; BOOL didWrite = [imageData writeToFile:[self filePath] options:NSAtomicWrite error:&writeError]; if(writeError) NSLog([writeError localizedDescription]); if(didWrite) NSLog(@"image saved"); else NSLog(@"image not saved"); } } - (NSString *)filePath{ NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); NSString *cacheDirectory = [paths objectAtIndex:0]; NSString *filename = [cacheDirectory stringByAppendingPathComponent:cacheDirectoryPath]; filename = [filename stringByAppendingPathComponent:cacheFileName]; NSLog(filename); return filename; }
我收到一个错误:
2009-06-23 16:39:19.740 XXX[33454:20b] Operation could not be completed. (Cocoa error 4.)
我查了一下,发现错误有以下含义:
NSFileNoSuchFileError = 4, // Attempt to do a file system operation on a non-existent file
这是没有意义的,因为该文件不应该存在.
我尝试编写png表示并使用方便方法:
- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag
我使用类似的代码来保存plists,它们工作正常.我不确定问题是什么.有任何想法吗?
我看到你在缓存目录中使用了一些中间目录,它们/它们是否已创建?如果没有尝试删除或使用
-[NSFileManager createDirectoryAtPath:withIntermediateDirectories:attributes:error:]
以前创建它们