NSString 、NSDictionary、NSMutableArray 返回值为空时的处理方法

#import "NSDictionary+safeDictionary.h"

 

NSString * const kEmptyString = @"";

@implementation NSDictionary (NSDictionary_Utils)

 // return an empty string if the value is null or not a string.

- (NSString *)stringForKey:(id)key

{

    NSString *result = [self objectForKey:key];

    if([result isKindOfClass:[NSString class]])

    {

        return result;

    }

    if ([result isKindOfClass:[NSNumber class]]) {

        return [NSString stringWithFormat:@"%@",result];

    }

    else {

        return kEmptyString;

    }

}

 

// return nil if the object is null or not a NSDictionary.

- (NSDictionary *)dictionaryForKey:(id)key

{

    NSDictionary *result = [self objectForKey:key];

    if([result isKindOfClass:[NSDictionary class]])

    {

        return result;

    }

    else {

        return nil;

    }

}

 

//  return nil if the object is null or not a NSArray.

- (NSMutableArray *)arrayForKey:(id)key

{

    NSMutableArray *result = [self objectForKey:key];

    if([result isKindOfClass:[NSArray class]])

    {

        return result;

    }

    else {

        return nil;

    }

}

1
原文地址:https://www.cnblogs.com/fantasy3588/p/4900711.html