iOS NSDictionary 키가 비어 있을 때 충돌 방지

2900 단어
NSDictionary 값이 비어 있으면 프로그램에서 할당 충돌이 발생합니다.
해결 방안은 NSDictionary에 확장 분류를 추가하여 꺼낸value를 비웁니다
.h  
#import 

@interface NSDictionary (Extension)

/**
      NSInteger(    )

 @param key   Key 
 @return NSInteger
 */
- (NSInteger)integerValueForKey:(id)key;

/**
      int(    )
 
 @param key   Key 
 @return int
 */
- (int)intValueForKey:(id)key;

/**
      long long(    )
 
 @param key   Key 
 @return long long
 */
- (long long)longlongValueForKey:(id)key;

/**
      BOOL(    )
 
 @param key   Key 
 @return BOOL
 */
- (BOOL)boolValueForKey:(id)key;

/**
      float(    )
 
 @param key   Key 
 @return float
 */
- (float)floatValueForKey:(id)key;

/**
         (    )
 
 @param key   Key 
 @return NSString
 */
- (NSString *)stringValueForKey:(id)key;

/**
        (    )
 
 @param key   Key 
 @return NSArray
 */
- (NSArray *)arrayValueForKey:(id)key;

/**
          (    )
 
 @param key   Key 
 @return NSMutableArray
 */
- (NSMutableArray *)mutableArrayValueForKey:(NSString *)key;

/**
        (    )
 
 @param key   Key 
 @return NSDictionary
 */
- (NSDictionary *)dictionaryValueForKey:(id)key;

@end
.m  
#import "NSDictionary+Extension.h"

@implementation NSDictionary (Extension)

- (NSInteger)integerValueForKey:(id)key {
    id value = [self notNullValueForKey:key];
    return value == nil ? 0 : [value integerValue];
}

- (int)intValueForKey:(id)key {
    id value = [self notNullValueForKey:key];
    return value == nil ? 0 : [value intValue];
}


- (long long)longlongValueForKey:(id)key {
    id value = [self notNullValueForKey:key];
    return value == nil ? 0 : [value longLongValue];
}

- (BOOL)boolValueForKey:(id)key {
    id value = [self notNullValueForKey:key];
    return value == nil ? NO : [value boolValue];
}

- (float)floatValueForKey:(id)key {
    id value = [self notNullValueForKey:key];
    return value == nil ? NO : [value floatValue];
}

- (NSString *)stringValueForKey:(id)key {
    return [self notNullValueForKey:key];
}

- (NSArray *)arrayValueForKey:(id)key {
    id value = [self notNullValueForKey:key];
    if(![value isKindOfClass:[NSArray class]]) {
        return nil;
    }
    return value;
}

- (NSMutableArray*)mutableArrayValueForKey:(NSString *)key {
    id value = [self notNullValueForKey:key];
    if(![value isKindOfClass:[NSMutableArray class]]) {
        return nil;
    }
    return value;
}

- (NSDictionary *)dictionaryValueForKey:(id)key {
    id value = [self notNullValueForKey:key];
    if(![value isKindOfClass:[NSDictionary class]]) {
        return nil;
    }
    return value;
}

#pragma mark     null
- (BOOL)isNullValue:(id)value {
    return [value isEqual:[NSNull null]];
}

- (id)notNullValueForKey:(id)key {
    id value = [self objectForKey:key];
    if([self isNullValue:value]) {
        return nil;
    }
    return value;
}
@end

좋은 웹페이지 즐겨찾기