my app crashes when add values from fields into an NSDictionary
i am developing an app where a user adds medicine name and number of times he should take it .. (the add view is presented as modal view).
when i NSlog the values populated from the user it seems to be okay when i try insert them to a dictionary the app crashes
NSString *name = [NSString stringWithString:[MedName_Field text]];
int times = [[times_Field text] intValue];
NSLog(@"%@ - %i",name,times); // <- Here it is OK.
//create a di开发者_如何学Cctionary
NSDictionary *dic = [[NSDictionary alloc] init];
[dic setValue:name forKey:@"Name"]; // <- Crash!
Thanks.
NSDictionary
instances are immutable so you can't add/remove anything after they are created. You need to use mutable variant - NSMutableDictionary instead:
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
[dic setValue:name forKey:@"Name"]; // <- No Crash! ;)
NSDictionary
isn't mutable, so you can't create it then add keys and values to it.
Either create a mutable dictionary:
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
[dic setValue:name forKey:@"Name"];
Or add you keys on init
with initWithObjects:forKeys:
:
NSDictionary *dic = [[NSDictionary alloc]
initWithObjects:[NSArray arrayWithObjects:name,nil]
forKeys:[NSArray arrayWithObjects:@"Name",nil]];
But you can't add keys after this because the dictionary is immutable.
精彩评论