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;

    }

}

posted on 2015-10-22 13:51  哈利波特大  阅读(406)  评论(0)    收藏  举报