NSDictionary initialization for iOS, iosnsdictionary
Recently, when I was working on a project, I encountered a very bad crash because of the nil pointer crash during NSDictionary initialization. Assume that we want to initialize an NSDictionary of {key1: value1, key2: value2, key3: value3}. There are two initialization methods:
1. Use the standard initialization method:
NSDictionary *dictionary =[[NSDictionary alloc] initWithObjectsAndKeys:value1,@"key1",value2,@"key2", value3 ,@"value3",nil];
2. New initialization methods supported after ios6.0 are used:
NSDictionary *dictionary =@{@"key1" : value1,@"key2" : value2,@"key3" : value3};
Now we assign values to value1 value2 value3 and set value2 as the nil pointer:
NSString *value1 =@"value1";NSString *value2 =nil;NSString *value3 =@"value3";
If the second initialization method is used, the running program will find a crash. The log is as follows:
DictionaryTextDemo[29390:1329578] Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: ' -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[1]'
The system will prevent you from inserting an nil pointer to object [1 ].
DiscussionThis method steps through the objects andkeys arrays, creating entries in the new dictionary as it goes. AnNSInvalidArgumentException is raised if a key or value object isnil.
That is to say, when using this initialization method, we must ensure that both the key and value are not nil. Therefore, we need to judge the key and value before initialization. If it is nil, no dictionary is added. However, if you want to leave the value empty, you can assign the value[NSNull null]
In this way, the dictionary can be inserted successfully and the output is
DictionaryTextDemo[29510:1338517] dictionary : {key1 = value1;key2 = "";value3 = value3;}
Another solution is to use the standard initialization method, that is, the first initialization method. However, you must also pay attention to the following problem:
NDictionary *dictionary = [[NSDictionary alloc]initWithObjectsAndKeys:value1,@"key1",value2,@"key2", value3 ,@"value3",nil];
If we set one of the keys or values as the nil pointer, the system will determine that all objects are completely inserted, which is equivalent to the last nil when we initialize the array and dictionary. Therefore, although this method can avoid exceptions thrown when inserting nil pointers, it may become a major security risk in the project and is difficult to detect. Therefore, we recommend that you use the second initialization method and make necessary judgments on the nil pointer.
[NSNull null]
To meet the needs of features. Similarly, you should also pay attention to this type of problem when using NSArray.