开发者

Core Data object into an NSDictionary with possible nil objects

I have a core data object that has a bunch of optional values. I'm pushing a table view controller and passing it a reference to the object so I can display its contents in a table view. Because I want the table view displayed a specific way, I am storing the values from the core data object into an array of dictionaries then using the array to populate the table view. This works great, and I got editing and saving working properly. (i'm not using a fetched results controller because I don't have anything to sort on)

The issue with my current code is that if one of the 开发者_如何学Pythonitems in the object is missing, then I end up trying to put nil into the dictionary, which won't work.

I'm looking for a clean way to handle this, I could do the following, but I can't help but feeling like there's a better way.

*passedEntry is the core data object handed to the view controller when it is pushed, lets say it contains firstName, lastName, and age, all optional.

if ([passedEntry firstName] != nil) {
    [dictionary setObject:[passedEntry firstName] forKey:@"firstName"]
}
else {
    [dictionary setObject:@"" forKey:@"firstName"]
}

And so on. This works, but it feels kludgy, especially if I end up adding more items to the core data object down the road.


What you could do is iterate through all of the object's properties using the objc_* runtime functions like so:

unsigned int property_count;
objc_property_t * prop_list = class_copyPropertyList([CoreDataObject class], &property_count);

for(int i = 0; i < property_count; i++) {
   objc_property_t prop = prop_list[i];
   NSString *property_name = [NSString stringWithCString:property_getName(prop) encoding:NSUTF8StringEncoding];
   id obj = [passedEntry valueForKey:property_name];
   [dictionary setObject:((obj != nil) ? obj : [NSNull null]) forKey:property_name];
}

free(prop_list);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜