Checking a null value in Objective-C that has been returned from a JSON string

前端 未结 15 1568
北海茫月
北海茫月 2020-11-30 20:34

I have a JSON object that is coming from a webserver.

The log is something like this:

{          
   \"status\":\"success\",
   \"Us         


        
15条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-30 21:22

    I usually do it like this:

    Assuma I have a data model for the user, and it has an NSString property called email, fetched from a JSON dict. If the email field is used inside the application, converting it to empty string prevents possible crashes:

    - (id)initWithJSONDictionary:(NSDictionary *)dictionary{
    
        //Initializer, other properties etc...
    
        id usersmail = [[dictionary objectForKey:@"email"] copy];
        _email = ( usersmail && usersmail != (id)[NSNull null] )? [usersmail copy] : [[NSString      alloc]initWithString:@""];
    }
    

提交回复
热议问题