检查NSEntityDescription键是否存在

时间:2012-03-13 18:35:42

标签: objective-c core-data ios5 nsentitydescription

在尝试设置值之前,我需要检查是否存在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];
}

3 个答案:

答案 0 :(得分:12)

你不应该检查选择器。想象一下名为entitymanagedObjectContext的密钥。 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];
    }
}

答案 1 :(得分:6)

检查一下,

BOOL hasFoo = [[myObject.entity propertiesByName] objectForKey:@"foo"] != nil;

答案 2 :(得分:-1)

我认为您要求检查约会对象是否响应属性。在那种情况下:

if([appointmentObject respondsToSelector:NSSelectorFromString(key)])...

getter等价物是propertyName。 setter等效项是setPropertyName。

相关问题