I am having problem initializing nsdictionary and adding it to array. I tried two appoaches but failed in both. My dictionary is always null.
Appoach1:
NSMutableDictionary *Data =[[NSMutableDictionary alloc] initWithObjectsAndKeys:@"1",@"State_Name",@"2",@"Name",@"3",@"Address",@"4",@"Ph", nil];// initialized in viewdidload
-(void)find:(NSInteger)Item{
switch (Item) {
case 0:
[Data setValue:string forKey:@"State_Name"];
break;
case 1:
[Data setValue:string forKey:@"Name"];
break;
case 2:
[Data setValue:string f开发者_StackOverflow中文版orKey:@"TAddress"];
break;
case 3:
[Data setValue:string forKey:@"Ph"];
break;
default:
break;
}
}
Approach2:
NSMutableDictionary *Data =[[NSMutableDictionary alloc] initWithObjectsAndKeys:str1,@"State_Name",str2,@"Name",str3,@"Address",str4,@"Ph", nil];
Could any one tell whats wrong with this code. Am I using nsdictionary's in a wrong way?
Thanks
I executed your code What change you have to do is:- in your .h file write:-
NSMutableDictionary *Data;
in your .m file write:-
Data =[[NSMutableDictionary alloc] initWithObjectsAndKeys:@"1",@"State_Name",@"2",@"Name",@"3",@"Address",@"4",@"Ph", nil];// initialized in viewdidload
Code looks correct. My guess is string
is nil. setValue:forKey:
allows nil (in turn removes existing object).
try setObject:forKey:
, it will raise exception if value(string) is nil or check if string is nil ...
To your first approach: What exactly is spposed to be your key and what your value in the initialiser? It seems to me you mixed up the order.
Besides that : you put strings into the dictionary but refere to a nsinteger in your switch. Are you doing a conversion somewhere in between ?
精彩评论