0

I have a core data field that is a String which is optional. Sometimes in my json response I will get back null. If I don't do the following code check below, the program crashes. Is there a better way to do this?

story.author = [newsStory valueForKeyPath:@"author_title"] != [NSNull null] ? [newsStory valueForKeyPath:@"author_title"] : @"Staff Writer";
Chris Muench
  • 17,444
  • 70
  • 209
  • 362
  • 1
    You can wrap the check into a Maccro. possibly repost : http://stackoverflow.com/questions/9137920/nsnull-handling-for-nsmanagedobject-properties-values – Damien Locque Jul 11 '12 at 15:19
  • possible duplicate of [NSNull handling for NSManagedObject properties' values](http://stackoverflow.com/questions/9137920/nsnull-handling-for-nsmanagedobject-properties-values) – jscs Jul 11 '12 at 17:42

1 Answers1

0

You way looks good. If you end up using this idiom a lot you may to set the default value for this attribute to "Staff Writer" in your data model in Xcode.

Note as of Mac OS X 10.5 you can replace [newsStory valueForKeyPath:@"author_title"] with the easier to read dot syntax newsStory.author_title. The two statements use exactly the same code paths as described in the Core Data Programming Guide.

torrey.lyons
  • 5,519
  • 1
  • 23
  • 30