Error while getting value from NSDictionary - ios

I'm trying to get from JSON parsed in NSDictionary and I'm getting this error all the time.
NSDictionary:
{
"admin_id" = 191767626;
body = "\U043a\U043b\U0430\U0441\U0441, \U043f\U043e\U0447\U0442\U0438 \U0434\U043e\U0434\U0435\U043b\U0430\U043b \U043f\U043e\U0434\U0434\U0435\U0440\U0436\U043a\U0443 \U0433\U0440\U0443\U043f\U043f\U043e\U0432\U044b\U0445 \U0431\U0435\U0441\U0435\U0434";
"chat_active" = "191767626,111273042,108237840,178159348,119271375,90588741,131506543,12657348,251374070,77508447,257350143,222456587,133059311,119425760,95255813,138571437,183017202,57733104,277277624,166958749,138127148,146374071,26326487,71995910,141152531,169957302,148888167,350803848,381660274,94296816,388139636";
"chat_id" = 104;
date = 1488494694;
mid = 1141349;
out = 1;
"photo_100" = "https://pp.userapi.com/c637621/v637621626/2317d/K9M4thCXrP0.jpg";
"photo_200" = "https://pp.userapi.com/c637621/v637621626/2317b/u5opnbkPQo0.jpg";
"photo_50" = "https://pp.userapi.com/c637621/v637621626/2317e/tNBXXHah700.jpg";
"push_settings" = {
"disabled_until" = 1773859745;
sound = 0;
};
"read_state" = 1;
title = CJB;
uid = 79372051;
"users_count" = 32;
}
So I'm interested in getting values for keys chat_id, title and users_count
I tried doing
NSLog(#"%#", [chatInfo objectForKey:#"chat_id"]);
But I'm getting this error
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber objectForKey:]: unrecognized selector sent to instance 0x19478910'
How can I solve this? Thanks in advance!

Try like this :
NSLog(#"%#", [[chatInfo objectForKey:#"chat_id"] stringValue]);
Or
NSLog(#"%#",[NSString stringWithFormat:#"%#", [[chatInfo objectForKey:#"chat_id"] stringValue]]);
Hope this will work for you.

Try this and use breakpoints on NSLogs for understand what is wrong:
if ([chatInfo isKindOfClass:[NSArray class]]) {
NSArray *array = (NSArray *) chatInfo;
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if ([destinationVC isKindOfClass:[NSDictionary class]]) {
NSDictionary *dictionary = (NSDictionary *) destinationVC;
if (dictionary[#"chat_id"]) {
NSLog(#"chat_id: %#", dictionary[#"chat_id"]);
} else {
NSLog(#"chat_id: not found");
}
} else {
NSLog(#"its not dictionary, check your JSON mapping");
}
}];
} else {
NSLog(#"This is not NSArray!");
}

Related

'NSInvalidArgumentException', reason: '-[NSTaggedPointerString objectForKey:]: unrecognized selector sent to instance 0xa000000617461644'

I am developing simple app that gets json data and stores into different variables
here is my code that gets json data
if ([method isEqualToString:#"getmobiledata"]){
defaultDict = [[NSMutableDictionary alloc]init];
[defaultDict addEntriesFromDictionary:[NSJSONSerialization JSONObjectWithData:[data dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil]];
mobile = [defaultDict objectForKey:#"data"];
}
here is my son data:
{
data = (
{
id = 1;
package = 819MB;
rate = "$1";
type = Somnet;
},
{
id = 2;
package = "1,638MB";
rate = "$2";
type = Somnet;
},
);
}
here is paring json into nstring :
for(NSDictionary *getData in mobile){
NSString *idno = [getData objectForKey : #"id"];
NSString *package = [getData objectForKey :#"package"];
NSString *rate = [getData objectForKey :#"rate"];
NSString *type = [getData objectForKey :#"type"];
}
please help me how to solve this
The data model will collide with the same name as the system property ID, and it will collide and crash.
You can use a new ID like this:
- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
if([key isEqualToString:#"id"])
self.NewId = value;
}

NSDictionary get property within list of objects - Objective C

How would I get "Dog" from the following dictionary?
{
Id = "123";
Animal = [{
Id = "456";
Type = "Dog";
Sound = "Bark";
},
{
Id = "789";
Type = "Cat";
Sound = "Meow";
}]
}
I tried
NSString *firstAnimalType = dictionary[#"Animal"][#"Type"];
However since there are multiple animals, it can't recognize what I am trying to find. How would I get the first animal out of the list so that I can access its type? Thanks!
You can use some thing like this, first get animal object and if it exists then find its type from it
NSDictionary *firstAnimal = [dictionary[#"Animal"] firstObject];
if(firstAnimal) //in case your firstAnimal is Empty or it may be nil then may create any unwanted issues in further code so just check it first.
{
NSString *firstAnimalType = firstAnimal[#"Type"];
}
Enumeration method will help and you can stop when and where you want
[myDict[#"Animal"] enumerateObjectsUsingBlock:^(id _Nonnull objList, NSUInteger idx, BOOL * _Nonnull stop) {
NSLog(#"%#",objList[#"Type"]);
*stop = YES; //You can stop where you want
}];
You can simply access the first element of the array with castings and get its Type value.
NSString *firstAnimalType = ((NSDictionary *)[((NSArray *)dictionary[#"Animal"]) objectAtIndex: 0])[#"Type"];
for (NSDictionary *animal in dictionary[#"Animal"]) {
NSString *type = animal[#"Type"];
if ([type isKindOfClass:[NSString class]] && [type isEqualToString:#"Dog"]) {
// Dog found
}
}
Here you go:
NSArray *aryFinalAni = [dicMain valueForKey:#"Animal"];
NSArray *aryType = [aryFinalAni valueForKeyPath:#"Type"];
if([aryType containsObject:#"Dog"])
{
int indexOfDog = (int)[aryType indexOfObject:#"Dog"];
NSMutableDictionary *dicDog = [aryFinalAni objectAtIndex:indexOfDog];
NSLog(#"%#",dicDog);
}
else
{
NSLog(#"There is no Dog found.");
}
Try this code:
{
Id = "123";
Animal = [{
Id = "456";
Type = "Dog";
Sound = "Bark";
},
{
Id = "789";
Type = "Cat";
Sound = "Meow";
}]
}
1> NSArray *items = dictionary["Animal"];
2>
NSPredicate *predicate1 = [NSPredicate predicateWithFormat: #"Type CONTAINS[cd] %#", "Dog"];
NSArray *arrData = [items filteredArrayUsingPredicate:predicate1];
if arrData.count > 0 {
dictionary = [arrData objectAtIndex:0];
}
Result:
{
Id = "456";
Type = "Dog";
Sound = "Bark";
}

NSArrayM unrecognized selector error

I need some help understanding why I am getting an unrecognized selector error
I have a NSMutableDictionary
#interface CallDetailViewController () {
NSMutableDictionary * thisDictionary;
}
#end
That gets populated from the MasterTabController
- (void) some method {
thisDictionary = [[(MasterTabController *)self.tabBarController detailDictionary] mutableCopy];
NSLog(#"Check dictinoary: %#", [thisDictionary description]);
}
Outputting a description shows the data is there
Check dictinoary: (
{
DATEIN = "2015-12-11 13:33:41";
"ETA" = "2015-12-14 13:54:16";
RecordKey = 2961;
Destination = "Some address";
Location = "Some location";
} )
But when I try to access an object in it:
NSLog(#"Destination: %#", [thisDictionary objectForKey:#"Destination"]);
I get the following error.
-[__NSArrayM objectForKey:]: unrecognized selector sent to instance 0x7a73f9a0
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM objectForKey:]:
unrecognized selector sent to instance 0x7a73f9a0'
The array is populated from a JSON value that returns an array of records called Record. After the JSON is returned, I pull out just section that contains the record.
NSDictionary * dictTowx = [NSDictionary dictionaryWithDictionary:[dictJSON objectForKey:#"ThisResponse"]];
NSDictionary * dictData = [NSDictionary dictionaryWithDictionary:[dictTowx objectForKey:#"Data"]];
NSArray * arrRecordSet = [dictData objectForKey:#"Recordset"];
NSDictionary * dicRecord= [arrRecordSet objectAtIndex:0];
self.detailDictionary = [dicRecord objectForKey:#"Record"];
The RAW JSON:
{
ThisResponse = {
Data = {
Recordset = (
{
Record = (
{
DATEIN = "2015-12-11 13:33:41";
"ETA" = "2015-12-14 13:54:16";
RecordKey = 2961;
Destination = "Some address";
Location = "Some location";
}
);
}
);
};
};
}
What am I doing wrong?
Please try to assign like this
self.detailDictionary = [[dicRecord objectForKey:#"Record"] objectAtIndex:0];
and then access like this
NSLog(#"Destination: %#", [thisDictionary objectForKey:#"Destination"]);
Enjoy programming.
- (void) some method {
thisDictionary = [[(MasterTabController *)self.tabBarController detailDictionary] mutableCopy];
NSLog(#"Check dictinoary: %#", [thisDictionary description]);
}
try replacing
thisDictionary = [[(MasterTabController *)self.tabBarController detailDictionary] mutableCopy];
with
thisDictionary = [[NSMutableDictionary alloc]initWithDictionary: [[{MasterTabController *)self.tabBarController detailDictionary] mutableCopy]]];
i think your problem may be you are not instantiating the dictionary before setting it to objects from another.

Adding a value and key into an NSMutableArray - Objc

I've read and tried a dozen or more variants of my own question, but still need some help please.
I have a large existing array, and I want to add a new object (key and value) to each record.
This is an element in the incoming array:
{
"trip_id": 65,
"arrival_time": "08:56:08",
"departure_time": "08:56:08",
"stop_id": 1161,
"stop_sequence": 8,
"stop_headsign": 0
},
This is what I want to achieve:
{
"trip_id": 65,
"arrival_time": "08:56:08",
"departure_time": "08:56:08",
"stop_id": 1161,
"stop_name": "a stop name",
"stop_sequence": 8,
"stop_headsign": 0
},
This is my code so far -- the commented lines are other attempts:
NSString *nameKey = #"stop_name";
int i=0;
for (i=0; i<stopTimesArray.count; i++) {
NSNumber *stopTimesId = [stopTimesArray[i] valueForKey:#"stop_id"];
int j=0;
for (j=0; j<stopArray.count; j++) {
NSNumber *stopId = [stopArray[j] valueForKey:#"stop_id"];
if (stopId == stopTimesId) {
NSString *stopNameString = [stopArray[j] valueForKey:#"stop_name"];
NSLog(#"stopNameString: %#", stopNameString);
[outgoingStopTimesDictionary setObject:stopNameString forKey:#"stop_name"];
//[outgoingStopTimesArray addObject:outgoingStopTimesDictionary];
//[outgoingStopTimesArray addObjectsFromArray:stopTimesArray[i]];
//[stopTimesArray[i] addObject:#{#"stop_name":stopNameString}];
//[stopTimesArray[i] addObject:#{#"stop_name":stopNameString}];
[stopTimesArray[i] addObject: outgoingStopTimesDictionary];
}
}
}
//NSLog(#"outgoingStopTimesArray: %#", outgoingStopTimesArray);
//NSLog(#"outgoingStopTimesDictionary: %#", outgoingStopTimesDictionary);
//NSLog(#"stopTimesArray: %#", stopTimesArray);
The error I am getting with approach is:
stopNameString: S Monroe Street, NB # 18th Street S, NS
[__NSCFDictionary addObject:]: unrecognized selector sent to instance 0x7fd7f2c22760
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary addObject:]: unrecognized selector sent to instance 0x7fd7f2c22760'
I'm either getting a null dictionary, or an unrecognised object exception when I try to add the dictionary to my array. Please point me to a working answer, and I'll delete my question.
It appears that your goal is to add one new key/value pair to the dictionary at stopTimesArray[i]. Here's your code all cleaned up with what I believe you need:
for (NSMutableDictionary *stopTimesDictionary in stopTimesArray) {
NSNumber *stopTimesId = stopTimesDictionary[#"stop_id"];
for (NSDictionary *stopDictionary in stopArray) {
NSNumber *stopId = stopDictionary[#"stop_id"];
if ([stopTimesId isEqual:stopId]) {
NSString *stopNameString = stopDictionary[#"stop_name"];
stopTimesDictionary[#"stop_name"] = stopNameString;
// Uncomment the following line if "stop_id" is unique within the "stopArray"
// break;
}
}
}
Since it seems your stopTimesArray contains immutable dictionaries, the above code won't work as written. Here is a solution that deals with that:
for (NSInteger i = 0; i < stopTimesArray.count; i++) {
NSDictionary *stopTimeDictionary = stopTimesArray[i];
NSNumber *stopTimesId = stopTimesDictionary[#"stop_id"];
for (NSDictionary *stopDictionary in stopArray) {
NSNumber *stopId = stopDictionary[#"stop_id"];
if ([stopTimesId isEqual:stopId]) {
NSString *stopNameString = stopDictionary[#"stop_name"];
NSMutableDictionary *tempDict = [stopTimesDictionary mutableCopy];
tempDict[#"stop_name"] = stopNameString;
[stopTimesArray replaceObjectAtIndex:i withObject:tempDict];
// Uncomment the following line if "stop_id" is unique within the "stopArray"
// break;
}
}
}
dictTo=[NSDictionary new];
dictTo =
#{
#"vPLocationLat" : [NSString stringWithFormat:#"%#",[[[[json valueForKey:#"result"] valueForKey:#"geometry"] valueForKey:#"location"] valueForKey:#"lat"]],
#"vPLocationLong" : [NSString stringWithFormat:#"%#",[[[[json valueForKey:#"result"] valueForKey:#"geometry"] valueForKey:#"location"] valueForKey:#"lng"]]
};
arrLocationList =[NSMutableArray new];
arrLocationList =[dictTo[#"data"] mutableCopy];
another Solution
-> Try to implement your Code as per in given Code
NSMutableArray* newArray = [NSMutableArray array];
NSArray* oldArray = outerDictionary[#"scores"];
for (NSDictionary* dictEntry in oldArray) {
NSString* leagueCode = dictEntry[#"league_code"];
if ([leagueCode isEqualToString #"epl"]) {
[newArray addObject:dictEntry];
}
}
Another one Solution
Try something like this.
Assume your array is called array and yourNewNameString is your new value for name
for(NSMutableDictionary *dict in array){
if([[dict objectForKey:#"id"]integerValue]==5){
[dict setObject:yourNewNameString forKey#"name"];
}
}
edit This is assuming you initialized your array with NSMutableDictionarys (Not just NSDictionarys)
//You can create dictionary and add it into NSMutableArray Object Like..
NSMutableArray *arr = [[NSMutableArray alloc] init];
NSDictionary *inventory = #{
#"Mercedes-Benz SLK250" : [NSNumber numberWithInt:13],
#"Mercedes-Benz E350" : [NSNumber numberWithInt:22],
#"BMW M3 Coupe" : [NSNumber numberWithInt:19],
#"BMW X6" : [NSNumber numberWithInt:16],
};
[arr addObject:inventory];
//You can access using key like...
NSString *strForBMWX6 = [[arr objectAtIndex:0] valueForKey:#"BMW X6"];
// in your case you just miss objectAtIndex:j
First, thanks #rmaddy.
I modified his answer a bit, but his was basically correct.
My final code looks like this:
for (NSInteger i = 0; i < stopTimesArray.count; i++) {
NSDictionary *stopTimesDictionary = stopTimesArray[i];
NSNumber *stopTimesId = stopTimesDictionary[#"stop_id"];
for (NSDictionary *stopDictionary in stopArray) {
NSNumber *stopId = stopDictionary[#"stop_id"];
if ([stopTimesId isEqual:stopId]) {
NSString *stopNameString = stopDictionary[#"stop_name"];
NSMutableDictionary *tempDict = [stopTimesDictionary mutableCopy];
tempDict[#"stop_name"] = stopNameString;
[outgoingStopTimesArray addObject:tempDict];
break;
}
}
}

ios - how do I parse JSON data that comes in a slightly different format than previously [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I used to have JSON data that came from the server. It was formatted like this:
(
{
comment = 1;
"comment_id" = 41;
"commenter_id" = 1;
date = "2013-04-02";
"first_name" = Alex;
"plan_id" = 27;
privacy = 0;
"solution_part" = 1;
}
)
and I parsed it like this:
-(void)loadTitleStrings
{
theArray = [NSMutableArray array];
if(!standardUserDefaults)
standardUserDefaults = [NSUserDefaults standardUserDefaults];
NSLog(#"Arrayyy: %#", items_array);
NSString *is_private = [standardUserDefaults objectForKey:#"is_private"];
NSMutableArray *titleStrings = [NSMutableArray array];
for(NSDictionary *dictionary in items_array)
{
//NOT SURE WHAT THIS IS FOR, SEEMS WEIRD
NSString *tcid = [dictionary objectForKey:#"comment_id"];
[theArray addObject:tcid];
//NSLog(#"Arrayyy: %#", theArray);
NSString *string;
if(!is_private || [is_private isEqualToString:#"0"])
{
string = [NSString stringWithFormat:#"%#: %#", [dictionary objectForKey:#"first_name"], [dictionary objectForKey:#"comment"]];
}
else
{
string = [NSString stringWithFormat:#"%#", [dictionary objectForKey:#"comment"]];
}
[titleStrings addObject:string];
}
cellTitleArray = titleStrings;
}
But now there was a change on the server and the data comes in a format like this:
{
data = (
{
comment = 1;
"comment_id" = 41;
"commenter_id" = 1;
date = "2013-04-02";
"first_name" = Alex;
"plan_id" = 27;
privacy = 0;
"solution_part" = 1;
},
{
comment = 2;
"comment_id" = 42;
"commenter_id" = 1;
date = "2013-04-02";
"first_name" = Alex;
"plan_id" = 27;
privacy = 0;
"solution_part" = 1;
}
);
And the original code to parse it crashes. I am not certain exactly in what the format difference is. How would I change the original code to work with the new data format?
This is the error that I get:
2013-04-02 12:31:28.798 Funding[70605:11303] -[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x72b9a10
2013-04-02 12:31:28.800 Funding[70605:11303] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x72b9a10'
*** First throw call stack:
(0x1dd5012 0x126ce7e 0x1e604bd 0x1dc4bbc 0x1dc494e 0x14a52 0x1695b 0x17cb731 0x17da014 0x17ca7d5 0x1d7baf5 0x1d7af44 0x1d7ae1b 0x21687e3 0x2168668 0x1b0ffc 0x26dd 0x2605)
libc++abi.dylib: terminate called throwing an exception
Thanks,
Alex
This is how I would do it..
-(void)loadTitleStrings
{
theArray = [NSMutableArray array];
if(!standardUserDefaults)
standardUserDefaults = [NSUserDefaults standardUserDefaults];
NSLog(#"Arrayyy: %#", items_array);
NSString *is_private = [standardUserDefaults objectForKey:#"is_private"];
NSMutableArray *titleStrings = [NSMutableArray array];
for(NSDictionary *dictionary in items_array)
{
NSArray *comments = [dictionary objectForKey:#"data"];
for (NSDictionary * comment in comments)
{
NSString *tcid = [comment objectForKey:#"comment_id"];
[theArray addObject:tcid];
//NSLog(#"Arrayyy: %#", theArray);
NSString *string;
if(!is_private || [is_private isEqualToString:#"0"])
{
string = [NSString stringWithFormat:#"%#: %#", [comment objectForKey:#"first_name"], [dictionary objectForKey:#"comment"]];
}
else
{
string = [NSString stringWithFormat:#"%#", [comment objectForKey:#"comment"]];
}
[titleStrings addObject:string];
}
cellTitleArray = titleStrings;
}
Basically, I will get the data dictionary, then inside the data dictionary, iterate comment by comment...
Hope this helps... You might need to change it accordingly to your situation because I do not know the full story...

Resources