美文网首页
NSDictionary 使用细节

NSDictionary 使用细节

作者: 怕腥的鱼 | 来源:发表于2017-03-06 11:17 被阅读15次

    NSDictionary创建有两种方法,
    1.NSDictionary *dic =@{@"xxx":@"xxx”};
    2.NSDictionary *dic =[NSDictionary dictionaryWithObjectsAndKeys:string01,@"xxx",string02,@“xxx”,string03,@"xxx",nil];

    区别在于:
    但是用第一种创建的dic里面的元素一定不能为空,否则就会崩溃。
    但是第二种也有缺陷 当string01 为空的时候 string02 后面的也会变null

    解决方案:
    当object有可能为nil的时候,采用setObject:forKey:

    NSString* string1 = nil;
    
    NSString* string2 = @"string2";
    
    NSMutableDictionary* dic = [NSMutableDictionary dictionary];
    
    if (string1) {
    
        [dic setObject:string1 forKey:@"string1"];
    
    }
    
    if (string2) {
    
        [dic setObject:string2 forKey:@"string2"];
    
    }
    
    [dic setObject:@"string3" forKey:@"string3"];
    

    当然还有更便捷的方法,使用setValue:forKey:

    NSString* string1 = nil;
    
    NSString* string2 = @"string2";
    
    NSMutableDictionary* dic = [NSMutableDictionary dictionary];
    
    [dic setValue:string1 forKey:@"string1"];
    
    [dic setValue:string2 forKey:@"string2"];
    
    [dic setValue:@"string3" forKey:@"string3"];
    

    请注意,setValue:forKey:与setObject:forKey:不完全等同,最大的区别有两点:

    1. setValue:forKey:只接受NSString*类型的key
    2. setValue:forKey:当value为nil时,将调用removeObjectForKey:

    相关文章

      网友评论

          本文标题:NSDictionary 使用细节

          本文链接:https://www.haomeiwen.com/subject/fiwygttx.html