是否可以节省大量的UIBezierPaths?如果是这样,怎么办呢?我已经尝试将它们全部放入NSMutableArray(和NSMutableDictionary),然后将该数组/字典保存到NSUserDefaults但是我得到了这个警告:
*** -[NSUserDefaults setObject:forKey:]: Attempt to insert non-property value '(
"<UIBezierPath: 0x20b9ca10>",
"<UIBezierPath: 0x20a1dbf0>",
"<UIBezierPath: 0x20b9e550>",
)' of class '__NSArrayM'. Note that dictionaries and arrays in property lists must also contain only property values.
答案 0 :(得分:4)
尝试使用此代码
-(void)saveData :(NSMutableArray *)dataArray;
{
NSFileManager *filemgr;
NSString *docsDir;
NSArray *dirPaths;
filemgr = [NSFileManager defaultManager];
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
// Build the path to the data file
NSString *dataFilePath = [[NSString alloc] initWithString: [docsDir
stringByAppendingPathComponent: @"data.archive"]];
[NSKeyedArchiver archiveRootObject:
dataArray toFile:dataFilePath];
}
-(NSMutableArray *)loadData;
{
NSFileManager *filemgr;
NSString *docsDir;
NSArray *dirPaths;
filemgr = [NSFileManager defaultManager];
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
// Build the path to the data file
NSString *dataFilePath = [[NSString alloc] initWithString: [docsDir
stringByAppendingPathComponent: @"data.archive"]];
// Check if the file already exists
if ([filemgr fileExistsAtPath: dataFilePath])
{
NSMutableArray *dataArray;
dataArray = [NSKeyedUnarchiver
unarchiveObjectWithFile: dataFilePath];
return dataArray;
}
return NULL;
}
应该工作正常,我测试了这个保存BezierPath并且似乎工作正常。我创建了一个名为archiving的类,它处理从手机中保存和加载数组和字典。
答案 1 :(得分:0)
这是另一个直接归档/取消归档UIBezierPath的解决方案:
- (NSURL *)documentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
- (void)archivePath:(UIBezierPath*)bPath withName:(NSString *)archiveName
{
NSString *savePath = [[[self documentsDirectory] URLByAppendingPathComponent:archiveName] path];
[NSKeyedArchiver archiveRootObject:bPath toFile:savePath];
}
- (UIBezierPath *)unarchivePathWithName:(NSString *)archiveName
{
return (UIBezierPath *)[NSKeyedUnarchiver unarchiveObjectWithFile:[[[self documentsDirectory] URLByAppendingPathComponent:archiveName] path]];
}
我没有进行任何错误检查或验证文件是否存在,但如果您确定那里有文件,则可以正常工作。以下是如何使用它的示例:
UIBezierPath *bez = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, 500, 100)];
[bez appendPath:[UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, 200, 200)]];
[self archivePath:bez withName:@"path.archive"];
UIBezierPath *bez2 = [self unarchivePathWithName:@"path.archive"];