簡體   English   中英

檢查密鑰存在於NSDictionary中

[英]Check key exists in NSDictionary

我如何檢查是否存在?:

[[dataArray objectAtIndex:indexPathSet.row] valueForKey:@"SetEntries"]

我想知道這個密鑰是否存在。 我怎樣才能做到這一點?

非常感謝你 :)

編輯:dataArray中有對象。 這些對象是NSDictionaries。

我假設[dataArray objectAtIndex:indexPathSet.row]返回一個NSDictionary ,在這種情況下,你可以簡單地檢查valueForKey的結果為nil.

例如:

if ([[dataArray objectAtIndex:indexPathSet.row] valueForKey:@"SetEntries"] != nil) {
    // The key existed...

}
else {
    // No joy...

}

所以我知道你已經選擇了答案,但我發現這在NSDictionary上作為一個類別非常有用。 在這一點上,您開始通過所有這些不同的答案開始提高效率。 嗯... 6 of 1 ...

- (BOOL)containsKey: (NSString *)key {
     BOOL retVal = 0;
     NSArray *allKeys = [self allKeys];
     retVal = [allKeys containsObject:key];
     return retVal;
}

檢查它是否為零:

if ([[dataArray objectAtIndex:indexPathSet.row] valueForKey:@"SetEntries"] != nil) {
    // SetEntries exists in this dict
} else {
    // No SetEntries in this dict
}

這也可以使用以下語法使用Objective-C文字:

NSDictionary *dict = @{ @"key1" : @"value1", @"key2" : @"value2" };
if (dict[@"key2"])
NSLog(@"Exists");
else
NSLog(@"Does not exist");
if ((NSNull *)[[dataArray objectAtIndex:indexPathSet.row] valueForKey:@"SetEntries"] != nil) {
    // SetEntries exists in this dict
} else {
    // No SetEntries in this dict
}

這是正確的答案。

試試這個:

if ([dict objectForKey:@"bla"]) {
   // use obj
} else {
   // Do something else like create the object
}

這個做的相同,但代碼較少:

if (dataArray[indexPathSet.row][@"SetEntries"] != nil) { /* the key exists */        } 
else                                                   { /* the key doesn't exist */ }

檢查字典包含任何值。 我更喜歡[dic allKeys] .count> 0來檢查。

使用(unsigned long)選項:

if ( (unsigned long)[[dataArray objectAtIndex:indexPathSet.row] valueForKey:@"SetEntries"] ) {
    // Key exist;
}else{
    // Key not exist;
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM