我知道有两件事:
1) 由您的应用程序生成的文件(而不是用户使用您的应用程序的结果),例如用于存储变量值的临时文本文件,那么这些文件必须放在 Library/Cache 而不是 Document 目录中。
2) 您还必须使用“skip-backup”属性标记文件,以告诉 iCloud 不要备份该文件。
我想你可能错过了第 2 步。
我编写了一个简单的 MediaDirectory 类,它可以快速为我提供 Library/Cache 文件夹中文件的路径,还添加了跳过备份属性。
将文件保存到 Libary/Cache 文件夹后,您只需执行以下操作:
[MediaDirectory addSkipBackupAttributeForFile:@"myTextFile.txt"];
这是完整的课程:
// Header File
// ----------------------------------------------------------------------
// This class takes a file name (including extension) and returns
// the path to that file in the Library/Cache folder
// ----------------------------------------------------------------------
#import <Foundation/Foundation.h>
@interface MediaDirectory : NSObject
+(NSString *) mediaPathForFileName:(NSString *) fileName;
+(NSString *) mediaPathForFileName:(NSString *) fileName inSubDirectory:(NSString *) subDirectory;
+ (BOOL)addSkipBackupAttributeToFile:(NSString *) fileName;
+ (BOOL)addSkipBackupAttributeToFile:(NSString *) fileName inSubDirectory:(NSString *) subDirectory;
@end
// Implementation File
#import "MediaDirectory.h"
#include <sys/xattr.h>
@implementation MediaDirectory
+(NSString *) mediaPathForFileName:(NSString *) fileName
{
NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachesDirectory = [directoryPaths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:@"%@/%@", cachesDirectory, fileName];
return filePath;
}
// if an image needs to be stored in a sub folder called "images"
+(NSString *) mediaPathForFileName:(NSString *) fileName inSubDirectory:(NSString *) subDirectory
{
NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachesDirectory = [directoryPaths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:@"%@/%@/%@", cachesDirectory, subDirectory, fileName];
return filePath;
}
//+ (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL
+ (BOOL)addSkipBackupAttributeToFile:(NSString *) fileName
{
const char* filePath = [[self mediaPathForFileName:fileName] fileSystemRepresentation];
const char* attrName = "com.apple.MobileBackup";
u_int8_t attrValue = 1;
int result = setxattr(filePath, attrName, &attrValue, sizeof(attrValue), 0, 0);
return result == 0;
}
+ (BOOL)addSkipBackupAttributeToFile:(NSString *) fileName inSubDirectory:(NSString *) subDirectory
{
const char* filePath = [[self mediaPathForFileName:fileName inSubDirectory:subDirectory] fileSystemRepresentation];
const char* attrName = "com.apple.MobileBackup";
u_int8_t attrValue = 1;
int result = setxattr(filePath, attrName, &attrValue, sizeof(attrValue), 0, 0);
return result == 0;
}
@end