我正在努力使我的 NSMangedObjectClass 配置文件可即时/可导出。如果我在 NSArrays 中编写关系,我会以这种方式
尝试
导出工作正常,因为 NSSet 尚未实现。writeToFile
- (void) exportProfile:(Profile *)profile toPath:(NSString *)path{
//Profile
NSMutableDictionary *profileDict = [[self.selectedProfile dictionaryWithValuesForKeys:[[[self.selectedProfile entity] attributesByName] allKeys]] mutableCopy];
NSMutableArray *views = [NSMutableArray array];
//Views
for (View *view in selectedProfile.views) {
NSMutableDictionary *viewDict = [[view dictionaryWithValuesForKeys:[[[view entity] attributesByName] allKeys]] mutableCopy];
NSMutableArray *controls = [NSMutableArray array];
//Much more for-loops
[viewDict setObject:controls forKey:@"controls"];
[views addObject:viewDict];
}
[profileDict setObject:views forKey:@"views"];
if([profileDict writeToFile:[path stringByStandardizingPath] atomically:YES])
NSLog(@"Saved");
else
NSLog(@"Not saved");
[profileDict release];
}
但是如果想在另一边导入
- (Profile*) importProfileFromPath:(NSString *)path{
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
Profile *newProfile = [NSEntityDescription insertNewObjectForEntityForName:@"Profile" inManagedObjectContext:context];
NSMutableDictionary *profileDict = [NSMutableDictionary dictionaryWithContentsOfFile:[path stringByStandardizingPath]];
[newProfile setValuesForKeysWithDictionary:profileDict];
}
我得到一个例外,这不会让我感到困惑,因为 Profile 需要一个 NSSet 而没有 NSArray。
所以我有两个问题:
[__NSCFArray intersectsSet:]: unrecognized selector sent to instance 0x4e704c0 *** Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '-[__NSCFArray intersectsSet:]: unrecognized selector sent to instance 0x4e704c0'
- 一方面,我无法将 NSSet 写入文件。
- 另一方面是我的 Profile 类需要一个 NSSet。
所以我尝试创建一个实现 writeToFile 的 NSSet 类别
@implementation NSSet(Persistence)
- (BOOL)writeToFile:(NSString*)path atomically:(BOOL)flag{
NSMutableArray *temp = [NSMutableArray arrayWithCapacity:self.count];
for(id element in self)
[temp addObject:element];
return [temp writeToFile:path atomically:flag];
}
+ (id)setWithContentsOfFile:(NSString *)aPath{
return [NSSet setWithArray:[NSArray arrayWithContentsOfFile:aPath]];
}
@end
但是我的函数没有被调用。
还有其他方法可以编写我的 NSSet 或告诉setValuesForKeysWithDictionary
Key“views”是 NSArray 吗?
还是一种简单的方式来导入/导出 ManagedObjects?