Recently, when I was doing a project, I encountered a pit crash, which was caused by a nil pointer when Nsdictionary was initialized. Suppose we are now initializing a nsdictionary of {key1:value1, key2:value2, key3:value3}, there are generally two ways to initialize it:
1, the use of standard initialization method:
Nsdictionary *dictionary =[[nsdictionary alloc] initwithobjectsandkeys:value1,@ "key1", value2,@ "key2", Value3,@ "value3", nil];
2. New supported initialization methods after using ios6.0:
Nsdictionary *dictionary [email protected]{@ "key1" : value1,@ "key2 " : value2,@"key3" : Value3};
Now we assign a value to the value1 value2 Value3 and set the value2 to the nil pointer:
NSString *value1 =@ "value1"; NSString *value2 =nil; NSString *value3 =@ "value3";
If you use the second initialization method, the running program will find a crash with the following log:
dictionarytextdemo[29390:1329578'nsinvalidargumentexception' -[__nsplaceholderdictionary InitWithObjects:forKeys:count:]: Attempt to insert nil object from objects[1] '
The discovery system will prevent you from inserting a nil pointer to object[1] and query the official Apple document to get
inch New as is if Object Isnil.
This means that the initialization method must be used to ensure that both key and value are not nil, so we need to judge the initialization before initializing it, and if Nil does not join the dictionary. However, if there is a need for value to be empty, value can be assigned [NSNull null] so that it can be successfully inserted into the dictionary, and the final printout is
dictionarytextdemo[29510:1338517""; value3 = Value3;}
Another workaround is to use the standard initialization method, which is the first initialization method. But at the same time also pay attention to a problem, using
Ndictionary *dictionary = [[Nsdictionary alloc]initwithobjectsandkeys:value1,@ "key1", value2,@ "key2", Value3,@ "value3", nil];
If we set one of the keys or value to the nil pointer, then the system will be judged to complete the entire object insertion, which is equivalent to the last nil we initialized the array and the dictionary. This approach, though, avoids the exception thrown when the nil pointer is inserted, but can be a major security risk in a project and is difficult to spot. Therefore, the second method of initialization is recommended, and the nil pointers must be judged and used selectively.[NSNull null]To achieve the characteristics of the demand. Similarly, the use of Nsarray should also pay attention to such problems.
iOS nsdictionary initialized pits