我正在尝试设置通用模型,以便从后端检索数据并在我的iPhone应用程序中处理数据。我试图通过为所有类创建一个基类来实现这一目标,其中所有逻辑都定义为检索,保存和链接数据。最后一部分是我正在努力的部分。
在每个类中,我定义了对象名称(在Core Data中),如果某个对象与其他对象有关系,还有两个数组的对象名称数组(一个用于hasOne,一个用于hasMany)。
但是我似乎无法将检索到的对象转换为存储为字符串的某个类。这是我目前的代码:
/**
Update the relationsships of an object which has relationsships from the type 'HasOne'.
@param object
Object from which the relations has to be updated.
*/
- (void)updateRelationshipsHasOne:(id)object {
for(NSString *relation in self.hasOne) {
Class class = NSClassFromString(self.table);
id anInstance = [class alloc];
anInstance = object;
NSString *key = [[NSString alloc] initWithFormat:@"%@_id",[relation lowercaseString]];
id delegata = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [delegata managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:relation inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat: @"db_id == %i",[[object valueForKey:key] intValue]];
[fetchRequest setPredicate:predicate];
NSError *error;
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
if(fetchedObjects && [fetchedObjects count] > 0) {
id otherInstance = [fetchedObjects objectAtIndex:0];
SEL s = NSSelectorFromString([[NSString alloc] initWithFormat:@"set%@",relation]);
[anInstance performSelector:s withObject:otherInstance];
}
}
}
如果我将'anInstance'和'otherInstance'同时转换为所需的类,一切顺利。但是,整个目的是使方法通用,所以我需要一些方法来将两个变量都转换为存储为字符串的类。
非常感谢您提供任何帮助!
编辑: 我收到的错误信息是:
2016-03-21 20:34:19.024 DeDamen[12303:834645] -[Heat setEvent]: unrecognized selector sent to instance 0x7fe2829d8cd0
2016-03-21 20:34:19.026 DeDamen[12303:834645] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Heat setEvent]: unrecognized selector sent to instance 0x7fe2829d8cd0'
*** First throw call stack:
(
0 CoreFoundation 0x0000000109e68e65 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x00000001094c0deb objc_exception_throw + 48
2 CoreFoundation 0x0000000109e7148d -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
3 CoreFoundation 0x0000000109dbe90a ___forwarding___ + 970
4 CoreFoundation 0x0000000109dbe4b8 _CF_forwarding_prep_0 + 120
5 ******* 0x0000000105d255ab -[CommonBase updateRelationshipsHasOne:] + 1627
6 ******* 0x0000000105d24e60 -[CommonBase updateRelationships:] + 256
7 ******* 0x0000000105d248a9 -[CommonBase save:handler:] + 1065
****
)
libc++abi.dylib: terminating with uncaught exception of type NSException
在这里,模型“Heat”指的是对象'anInstance',而模型'Event'指的是对象'otherInstance'。关系是:一个热火有一个事件,一个事件有很多热量