检查NSEntityDescription键是否存在

Bot*_*Bot 4 core-data objective-c nsentitydescription ios5

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];
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*uch 12

你不应该检查选择器.想象一个叫做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];
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 6

检查一下,

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