NSDictionary--value為nil

調(diào)試的過(guò)程中還是得注意這個(gè),不然字典莫名其妙的少了點(diǎn)keys,定位很麻煩。

給NSDictionary設(shè)置value時(shí)--value為nil時(shí)程序會(huì)不會(huì)crash?

答:分情況

  • 使用字面量,會(huì)crash

  • 使用setObject:ForKey:會(huì)crash,

  • 使用dictionaryWithObjectsAndKeys:不會(huì)crash,

  • 使用setValue:ForKey:不會(huì)crash。

  • 直接賦值dict[@"key"]=nil:不會(huì)crash。

詳細(xì)情況可以看下面注釋


    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                          @"99", @"key1",
                          @"02", @"key2",
                          [self value],@"key3",
                          @"end",@"end", nil]; 
// 編譯運(yùn)行都可以通過(guò),但是當(dāng)[self value]為空時(shí),后面所有的key和value都無(wú)法添加上了,但是沒(méi)有添加上key&value


    NSDictionary *dict2 = @{
        @"key1": @"99",
        @"key2": @"02",
        @"key3":[self value],
        @"end":@"end"}; 
//*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[2]'
    
    
    [dict setValue:[self value] forKey:@"value"]; 
// 編譯運(yùn)行都可以通過(guò),但是沒(méi)有添加上key&value,不影響后面的setValue執(zhí)行

    [dict setValue:@"~~~" forKey:@"value2"];
    [dict setValue:@"[self value]" forKey:@"value3"];
    [dict setValue:@"[self " forKey:@"value4"];
    dict[@"value"] = [self value]; 
    // 直接賦值也沒(méi)有問(wèn)題

    [dict setObject:[self value] forKey:@"value"]; 
// *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSDictionaryM setObject:forKey:]: object cannot be nil (key: value)'
    NSLog(@"%@", dict);
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容