How can I check if an object in an NSArray is NSNull?

后端 未结 9 1762
忘了有多久
忘了有多久 2020-12-23 18:50

I am getting an array with null value. Please check the structure of my array below:

 (
    \"< null>\"
 )

When I\'m trying to access

9条回答
  •  醉梦人生
    2020-12-23 19:29

    I found the code for working with NSNull has the following problems:

    • Looks noisy and ugly.
    • Time consuming.
    • Error prone.

    So I created the following category:

    @interface NSObject (NSNullUnwrapping)
    
    /**
    * Unwraps NSNull to nil, if the object is NSNull, otherwise returns the object.
    */
    - (id)zz_valueOrNil;
    
    @end
    

    With the implementation:

    @implementation NSObject (NSNullUnwrapping)
    
    - (id)zz_valueOrNil
    {
        return self;
    }
    
    @end
    
    @implementation NSNull (NSNullUnwrapping)
    
    - (id)zz_valueOrNil
    {
        return nil;
    }
    
    @end
    

    It works by the following rules:

    • If a category is declared twice for the same Class (ie singleton instance of the Class type) then behavior is undefined. However, a method declared in a subclass is allowed to override a category method in its super-class.

    This allows for more terse code:

    [site setValue:[resultSet[@"main_contact"] zz_valueOrNil] forKey:@"mainContact"];
    

    . . as opposed to having extra lines to check for NSNull. The zz_ prefix looks a little ugly but is there for safety to avoid namespace collisions.

提交回复
热议问题