iOS之NSDictionary使用集合和各种为空判断

本文介绍了如何将JSON字符串转换为Objective-C中的字典,并提供了判断字典是否为空、是否包含特定键的方法。此外,还详细说明了如何处理字典中可能存在的null值,避免程序因读取null值而崩溃。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

========JSON字符串转换成字典========


 NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];

=========判断字典内容是否为空=======

NSDictionary *dic=[[NSDictionaryalloc]init];

    

    if(dic.count==0 ){

    

    NSLog(@"字典为空02");////

    }



 NSDictionary *dict;

    NSLog(@"字典---%@",dict);

    if (!dict) {

        NSLog(@"字典为空");////

    }else {

        NSLog(@"字典不为空");

    }


NSDictionary *dict;

    NSLog(@"字典---%@",dict);

    if (![dictcount]) {

        NSLog(@"字典为空");//////

    }else {

        NSLog(@"字典不为空");

    }



========判断字典包含某个key===

方法一:

 NSDictionary *dict=@{@"key":@""

                         };

    NSLog(@"字典---%@",dict);

    if(![[dictallKeys]containsObject:@"key"]){

    

        NSLog(@"键值为空");

    }else {

        NSLog(@"键值不为空");/////

    }


 方法二:NSDictionary *dict=@{

                         @"s":@{@"a":@"ax"

                                 

                                 }

                         

                         };

    NSLog(@"字典---%@",dict);

    if (!dict[@"q"]) {

        NSLog(@"字典键不存在");//////

    }else {

        NSLog(@"字典键存在");

    }



============

APP开发过程中,我们有时候要从服务器加载数据时,一般是都是用json或者xml解析后用NSDictionary保存,但是从服务器加载过来的数据直接使用时会崩溃,是因为在NSDictionary中的某个值为<null>或者NSnull ,但是我们用一般的检查根本检查不出来,如if( [obc objectForKey:key]==nil) 没有效果,这时候就要对NSDictionary的中值做处理了,把NSDictionary中值为<null>或者NSnull替换成@""就行了,上函数:




- (id) processDictionaryIsNSNull:(id)obj{

    const NSString *blank = @"";

    

    if ([obj isKindOfClass:[NSDictionary class]]) {

        NSMutableDictionary *dt = [(NSMutableDictionary*)obj mutableCopy];

        for(NSString *key in [dt allKeys]) {

            id object = [dt objectForKey:key];

            if([object isKindOfClass:[NSNull class]]) {

                [dt setObject:blank

                       forKey:key];

            }

            else if ([object isKindOfClass:[NSString class]]){

                NSString *strobj = (NSString*)object;

                if ([strobj isEqualToString:@"<null>"]) {

                    [dt setObject:blank

                           forKey:key];

                }

            }

            else if ([object isKindOfClass:[NSArray class]]){

                NSArray *da = (NSArray*)object;

                da = [self processDictionaryIsNSNull:da];

                [dt setObject:da

                       forKey:key];

            }

            else if ([object isKindOfClass:[NSDictionary class]]){

                NSDictionary *ddc = (NSDictionary*)object;

                ddc = [self processDictionaryIsNSNull:object];

                [dt setObject:ddc forKey:key];

            }

        }

        return [dt copy];

    }

    else if ([obj isKindOfClass:[NSArray class]]){

        NSMutableArray *da = [(NSMutableArray*)obj mutableCopy];

        for (int i=0; i<[da count]; i++) {

            NSDictionary *dc = [obj objectAtIndex:i];

            dc = [self processDictionaryIsNSNull:dc];

            [da replaceObjectAtIndex:i withObject:dc];

        }

        return [da copy];

    }

    else{

        return obj;

    }

====================================

@property(nonatomic,strong)NSMutableArray *muarr;

@property(nonatomic,copy)NSString *str;

@property(nonatomic,strong)NSDictionary *dict;

@property(nonatomic,copy)void(^block)(int x);


NSLog(@"--arr--%@,--str---%@--,dict---%@--,self.block---%@",self.muarr,self.str,self.dict,self.block);

    if(!self.muarr){

        NSLog(@"数组nil");

    }

    if(self.muarr.count==0){

        NSLog(@"空数组");

    }

    if(!self.str){

         NSLog(@"字符串nil");

    }

    if([self.strisEqualToString:@""]){

        NSLog(@"空字符串");

    }

    if(!self.dict){

         NSLog(@"字典nil");

    }

    if(self.dict.count==0){

        NSLog(@"空字典");

    }

    if(!self.block){

         NSLog(@"block ---nil");

    }

    结果:

2018-01-17 08:53:08.018374+0800 FastApps[19950:1346083] --arr--(null),--str---(null)--,dict---(null)--,self.block---(null)

2018-01-17 08:53:08.018495+0800 FastApps[19950:1346083] 数组nil

2018-01-17 08:53:08.018602+0800 FastApps[19950:1346083] 空数组

2018-01-17 08:53:08.018659+0800 FastApps[19950:1346083] 字符串nil

2018-01-17 08:53:08.018706+0800 FastApps[19950:1346083] 字典nil

2018-01-17 08:53:08.018765+0800 FastApps[19950:1346083] 空字典

2018-01-17 08:53:08.018839+0800 FastApps[19950:1346083] block ---nil


     后台返回的字段"bank_card" = "<null>";-------如果是用字典去值,则结果是字符串"<null>"

,如果用mjextention字典转模型后去取值,则转换成nil;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值