代码改变世界

NSDictionary的分类

2013-10-16 09:10  甘超波  阅读(430)  评论(0编辑  收藏  举报
@implementation NSDictionary (extra)


//根据key值的到字典中的object
- (id)getObjectByKey:(NSString*)key {
    NSArray *array = [key componentsSeparatedByString:@"/"];
    NSDictionary *dic = self;
    for (int i=0; i<[array count]-1; i++) {//注意i<[arrary count]-1
        dic = [dic objectForKey:[array objectAtIndex:i]];
    }
    return [dic objectForKey:[array objectAtIndex:[array count]-1]];
}

/*
 根据key值得到字符串,如为空则返回@“”
 */
- (id)getStringByKey:(NSString*)key {
    NSArray *array = [key componentsSeparatedByString:@"/"];
    NSDictionary *dic = self;
    for (int i=0; i<[array count]-1; i++) {//注意 i<[array count]-1
        dic = [dic objectForKey:[array objectAtIndex:i]];
    }
    NSString *temp = [dic objectForKey:[array objectAtIndex:[array count]-1]];
    if (!temp) {
        temp = @"";
    }
    return temp;
}

 用法

 NSString *returnCode = [aBackDic getStringByKey:@"business/group/returnCode"];