简体   繁体   中英

Performance with conditional statements in Objective-C and NSMutableDictionary

Basically my dictionary looks like:

object:[NSNumber numberWithBool:] key: [NSNumber numberWithInteger:ID]

I want to add objects to a NSMutableDictionary if they don't exist already. I also want to overwrite any values of NO with YES if there are two IDs that are the same and one value is a YES.

eg

ID:5, YES
ID:5, NO
ID:5, YES

I want the result to be ID:5 YES in my dictionary. I do this:

if ([dict objectForKey:[NSNumber numberWithInteger:conditionsListID]] != nil) {
   [dict setObject:[NSNumber numberWithBool:theValue forKey:[NSNumber numberWithInteger:conditionsListID];
else {
  if (theValue) {
       [dict setObject:[NSNumber numberWithBool:theValue forKey:[NSNumber numberWithInteger:conditionsListID];

  }
}
}

I was wondering if it matters if I even check if the value that exists already has NO, or if I just overwrite it if my new value has YES or not since in the end, YES is what I want. Is there really any difference between the two? Thanks.

Just call setObject:forKey: and the dictionary will take care of the logic you want. According to the API docs:

"If aKey already exists in the dictionary, the dictionary's previous value object for that key is sent a release message and anObject takes its place."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM