//
//  NSDictionary+gmsafekit.m
//  OJia
//
//  Created by lerosua on 15/3/25.
//  Copyright (c) 2015年 com.ojia. All rights reserved.
//

#import "NSDictionary+gmsafekit.h"

@implementation NSDictionary (gmsafekit)

- (NSString *)safeStringForKey:(id)key
{
    return [self safeStringForKey:key or:nil];
}

- (NSString *)safeStringForKey:(id)key or:(NSString *)fall
{
    //改为自定义方法，兼容NSNumber对象转成string
    id obj = [self objectForKey:key];
    if ([obj isKindOfClass:[NSString class]]) {
        return obj;
    }else if((NSNull *)obj == [NSNull null]){
        return fall;
    }
    else if ([obj respondsToSelector:@selector(stringValue)]) {
        return [obj stringValue];
    } else {
        return fall;
    }


}

- (NSNumber *)safeNumberForKey:(id)key
{
    return [self safeNumberForKey:key or:nil];
}
- (NSNumber *)safeNumberForKey:(id)key or:(NSNumber *)fall
{
    id obj = [self objectForKey:key];
    if ([obj isKindOfClass:[NSString class]]) {
        return [NSNumber numberWithInteger:[obj integerValue]];
    } else if ([obj isKindOfClass:[NSNumber class]]) {
        return obj;
    } else {
        return fall;
    }
}

- (NSDictionary *)safeDictionaryForKey:(id)key
{
    return [self safeDictionaryForKey:key or:nil];
}

- (NSDictionary *)safeDictionaryForKey:(id)key or:(NSDictionary *)fall
{
    return [self objectForKey:key expectedClass:[NSDictionary class] or:fall];
}

- (NSArray *)safeArrayForKey:(id)key
{
    return [self safeArrayForKey:key or:nil];
}

- (NSArray *)safeArrayForKey:(id)key or:(NSArray *)fall
{
    return [self objectForKey:key expectedClass:[NSArray class] or:fall];
}

- (id)objectForKey:(id)key expectedClass:(Class)class_
{
    return [self objectForKey:key expectedClass:class_ or:nil];
}

- (id)objectForKey:(id)key expectedClass:(Class)class_ or:(id)fall
{
    id obj = [self objectForKey:key];
    if (class_ && [obj isKindOfClass:class_]) {
        return obj;
    }
    return fall;
}

@end
