假设您在缓存目录中保存了一个名为“imageTexture.jpg”的临时图像。最喜欢的“FavoritePhoto.jpg”保存在文档目录中。
要覆盖文档目录中最喜欢的一个,您可以这样做。
NSError *errorDesc;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *statesDescriptionPath = [documentsDirectory stringByAppendingPathComponent:@"FavoritePhoto.jpg"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *cacheDirectory = [NSFileManager getCacheDirectory];
NSString *temporaryPath = [cacheDirectory stringByAppendingPathComponent:@"imageTexture.jpg"];
NSURL *originalURL = [NSURL fileURLWithPath:statesDescriptionPath];
[fileManager replaceItemAtURL:originalURL withItemAtURL:[NSURL fileURLWithPath:temporaryPath] backupItemName:nil options:NSFileManagerItemReplacementUsingNewMetadataOnly resultingItemURL:&originalURL error:&errorDesc];
if (errorDesc)
{
NSLog(@"there was an error overwriting the favorite photo: %@", errorDesc.description);
}
我正在使用 NSFileManager 类别来获取缓存目录
这里是 NSFileManager+Powertools.h 的代码
#import <Foundation/Foundation.h>
@interface NSFileManager (Powertools)
+ (NSString *)getCacheDirectory;
@end
这里可以看到NSFileManager+Powertools.m的代码
#import "NSFileManager+Powertools.h"
@implementation NSFileManager (Powertools)
+ (NSString *)getCacheDirectory
{
NSString *path = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
if ([paths count])
{
NSString *bundleName =
[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];
path = [[paths objectAtIndex:0] stringByAppendingPathComponent:bundleName];
}
return path;
}
@end