我正在尝试使用以下代码保存图像:
- (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,它们工作正常。我不确定问题是什么。有什么想法吗?
答案 0 :(得分:28)
我看到您在缓存目录中使用了一些中间目录,是/它们是否已创建?如果没有尝试删除它们或使用
-[NSFileManager createDirectoryAtPath:withIntermediateDirectories:attributes:error:]
在
之前创建它们