Core Data object in NSDictionary with possible nil objects

I have a main data object that has a bunch of optional values. I press the table view controller and pass it an object reference so that I can display its contents in a table. Since I want the table view to be displayed in a specific way, I save the values ​​from the main data object to an array of dictionaries, and then use the array to populate the table view. This works great, and I got editing and working. (I do not use the selected result controller because I have nothing to sort)

The problem with my current code is that if one of the elements in the object is missing, I end up trying to put zero in a dictionary that won't work.

I am looking for a clean way to handle this, I could do the following, but I cannot help but feel that there is a better way.

* receivedEntry is the main data object passed to the view controller when it is clicked, it allows you to say that 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 main data object along the way.

+4
source share
1 answer

What you can do is objc_* over all the properties of an object using the objc_* runtime functions, for example:

 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); 
+5
source

Source: https://habr.com/ru/post/1333968/


All Articles