在尝试设置该值之前,我需要检查是否存在NSEntityDescription密钥。我有一个来自JSON的数据字典,不想尝试设置我的对象中不存在的键。
Appointment *appointmentObject = [NSEntityDescription insertNewObjectForEntityForName:@"Appointments" inManagedObjectContext:[[DataManager sharedInstance] managedObjectContext]];
for (id key in dict) {
// Check if the key exists here before setting the value so we don't error out.
[appointmentObject setValue:[dict objectForKey:key] forKey:key];
}发布于 2012-03-14 04:45:54
您不应该检查选择器。假设有一个名为entity或managedObjectContext的键。NSManagedObject类肯定会响应这些选择器,但如果您试图将某些错误赋值给这些选择器,那么最好的结果就是代码立即崩溃。运气稍差一点,就会破坏完整的核心数据文件和所有用户数据。
NSEntityDescription有一个名为attributesByName的方法,它返回一个字典,其中包含您的属性名称和相应的NSAttributeDescriptions。因此,这些键基本上是您可以使用的所有属性。
像这样的东西应该是有效的:
Appointment *appointmentObject = [NSEntityDescription insertNewObjectForEntityForName:@"Appointments" inManagedObjectContext:[[DataManager sharedInstance] managedObjectContext]];
NSArray *availableKeys = [[appointmentObject.entity attributesByName] allKeys];
for (id key in dict) {
if ([availableKeys containsObject:key]) {
// Check if the key exists here before setting the value so we don't error out.
[appointmentObject setValue:[dict objectForKey:key] forKey:key];
}
}发布于 2012-09-26 17:04:03
看看这个,
BOOL hasFoo = [[myObject.entity propertiesByName] objectForKey:@"foo"] != nil;
发布于 2012-03-14 03:07:06
我认为你是在问你想要检查appointmentObject是否响应一个属性。在这种情况下:
if([appointmentObject respondsToSelector:NSSelectorFromString(key)])...与getter等效的是propertyName。等同于setter的是setPropertyName。
https://stackoverflow.com/questions/9689996
复制相似问题