I'm trying to acces my JSON in Objective-C from a higher scope. But it keeps crashing and I have no idea why.
The following code works:
- (void)fetchedData:(NSData *)responseData {
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONOnkectWithData: responseData
options:kNilOptions
error:&error];
NSArray* nameAndPlace = [[json objectForKey:#"objects"] objectForKey:#"havens"];
//NSArray* productArray = [[json objectForKey:#"objects"] objectForKey:#"products"];
NSLog(#"FROM ---> %#", nameAndPlace);
for (NSDictionary *mapPointLoop in nameAndPlace) {
NSString * name = [mapPointLoop objectForKey:#"name"];
NSString * longitudeGet = [mapPointLoop objectForKey:#"longitude"];
NSString * latitudeGet = [mapPointLoop objectForKey:#"latitude"];
myAnnotation *annotation1 = [[myAnnotation alloc] init];
CLLocationCoordinate2D coordinate1;
coordinate1.longitude = longitude;
coordinate1.latitude = latitude;
annotation1.coordinate = coordinate1;
annotation1.title = name;
[mainMap addAnnotation:annotation1];
//NSLog(#"FROM ---> %#", mapPointLoop);
}
}
But when I use this it crashes:
- (void)fetchedData:(NSData *)responseData {
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
NSArray* nameAndPlace = [json objectForKey:#"objects"];
//NSArray* productArray = [[json objectForKey:#"objects"] objectForKey:#"products"];
NSLog(#"FROM -> %#", nameAndP1ace);
for (NSDictionary *mapPointLoop in nameAndPlace) {
NSString * name = [[mapPointLoop objectForKey:#"havens"] objectForKey:#"name"];
NSNumber * longitudeGet = [mapPointLoop objectForKey:#"longitude"];
NSNumber * latitudeGet = [mapPointLoop objectForKey:#"latitude"];
float latitude = [latitudeGet floatvalue];
float longitude = [longitudeGet floatvalue];
myAnnotation *annotation1 = [[myAnnotation alloc] init];
CLLocationCoordinate2D coordinate1;
coordinate1.longitude = longitude;
coordinate1.latitude = latitude;
annotation1.coordinate = coordinate1
annotation1.title = name;
[mainMap addAnnotation:annotation1];
//NSLog(#"FROM -> %#", mapPointLoop):
}
}
It crashes with the error...
2014-05-20 17:49:57.709 labelAPortTest[5556:60b] * Terminating app
due to uncaught exception 'NSInvalidArgumentException', reason:
'-[__NSCFString objectForKey:]: unrecognized selector sent to instance
0x1172426b0'
It crash because when you take the name:
NSString *name = [[mapPointLoop objectForKey:#"havnes"] objectForKey:#"name"];
this:
[mapPointLoop objectForKey:#"havens"]
is an NSArray and not an NSDictionary with the key name.
In fact in your first code you take the objectForKey:#"objects"] objectForKey:#"havens]"
so you have this situation:
NSDictionary ~> objects ~> NSDictionary ~> havens ~> NSArray (of NSDictionary)
then you go to through a for cycle getting 1 to 1 the NSDictionary in the NSArray.
Second case (that crash):
NSDictionary ~> objects ~> NSDictionary
but your are putting that in an NSArray going again with the for cycle..on an NSDictionary.
But it keeps crashing and I have no idea why.
The reason is right here:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x1172426b0'
You have an uncaught exception. Furthermore, you have some information about what that exception is, namely that you're sending the objectForKey: message to an object that doesn't implement it.
The first thing you should do is to set a breakpoint for all exceptions:
That'll cause the debugger to stop as soon as the exception is thrown instead of waiting until the app exits, which will give you a lot more context. You should be able to see which object is getting the unknown message. If that doesn't make the problem completely clear, set a breakpoint a line or two before the exception happens and step through the code a line at a time until you find the problem.
Related
I've the following code for receiving response from PHP web service in JSON Format:
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *responseStringWithEncoded = [[NSString alloc] initWithData: mutableData encoding:NSUTF8StringEncoding];
NSLog(#"Response from Server : %#", responseStringWithEncoded);
[self getData:responseStringWithEncoded];
}
-(void) getData:(NSString *) responseStringWithEncoded{
NSData *data = [responseStringWithEncoded dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"object for key ime = %#", [json objectForKey:#"imei"]);
NSString * jimei = [json objectForKey:#"imei"];
NSLog(#"jimei = %#", jimei);
// NSDictionary * jimei = [json objectForKey:#"imei"];
imeiLable.text = jimei;
}
I am successfully retrieving data in simulator but when assigning one value among received string(NSDictionary) to imeiLable.text it gives following error.
Here is the output:
Request data = { URL: http://localhost/getjsonimei.php?imei=478593219801234 }
Response from Server : {"id":7,"imei":478593219801234,"mname":"Samsung Glaxy","pamount":"2000 rupees","pname":"Faizi","address":"House number 88, block 31","cnumber":11122233,"nic":"87456893"}
object for key ime = 478593219801234
jimei = 478593219801234
Here is detailed description of simulator resulting string(dictionary) and error.
2017-05-24 20:01:13.229 imiechecker[4005:61372] -[__NSCFNumber length]: unrecognized selector sent to instance 0xb01b3472adbb0923
2017-05-24 20:01:13.263 imiechecker[4005:61372] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber length]: unrecognized selector sent to instance 0xb01b3472adbb0923'
I also tried following approach:
NSDictionary * jimei = [json objectForKey:#"imei"];
but having the same error.
Please suggest where I am doing it wrong?
Your IMEI number is of data type NSNumber, not NSString.
Try this:
NSString * jimei = [NSString stringWithFormat:#"%#", [json objectForKey:#"imei"]];
imeiLable.text = jimei;
I'm trying to parse the following JSON information that comes out of my PHP file:
{
"netSales":0,
"voidSales":0,
"discountSales":0,
"guestCount":null,
"servedCount":null,
"loggedIn":9
}
My string is set something like this:
NSURL * url = [NSURL URLWithString:salesStr];
NSData * data = [NSData dataWithContentsOfURL:url];
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(#"response type is %#",[json class]);
//Set up our cities array
arrayOfStore = [[NSMutableArray alloc]init];
for (int i = 0; i < json.count; i++)
{
NSString * netSales = json[i][#"netSales"];
NSString * voids = json[i][#"voidSales"];
NSString * discounts = json[i][#"discountSales"];
NSString * guestCount = json[i][#"guestCount"];
NSString * peopleServed = json[i][#"servedCount"];
NSString * employeesClock = json[i][#"loggedIn"];
Store * myStore = [[Store alloc]initWithNetSales: (NSString *) netSales andVoids: (NSString *) voids andDiscounts: (NSString *) discounts andGuestCount: (NSString *) guestCount andPeopleServed: (NSString *) peopleServed andEmployeesClock: (NSString *) employeesClock];
[arrayOfStore addObject:myStore];
But it's returning the error message:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x8ddb930'
What does this error mean?
EDIT: I extended my code a bit.
Your error message, "[__NSCFDictionary objectAtIndex:]: unrecognized selector sent", is informing you that you attempted to call objectAtIndex (an array method) on an object that was really a dictionary.
Your code snippet appears to assume that the JSON is an array of dictionaries. But on the basis of what you've shared with us, it looks like a simple dictionary. That is consistent with the error message you received. You could remedy this by just calling objectForKey, and eliminate the call to objectAtIndex.
By the way, netSales appears to be a number, not a string, so use NSNumber rather than NSString.
So, putting those together, I think you'd want:
NSNumber *netSales = json[#"netSales"]; // or [json objectForKey:#"netSales"];
I was passed NSstring it is coming properly data into uitableview but when I am parsing integer value it showing exception Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: -[__NSCFNumber isEqualToString:]: unrecognized selector sent to instance 0x744e9d0
This is my code
(void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData options:kNilOptions error:&error];
NSArray * values=[json objectForKey:#"loans"];
NSLog(#"Array: %#",values);
for (NSDictionary *file in values)
{
NSNumber *fileTitle=[file objectForKey:#"id"];
// NSString *fileTitle = [file objectForKey:#"sector"];
[titles addObject: fileTitle];
}
[self.mainTableView reloadData];
}
You are assigning string value to NSNumber type.
Try to use this
NSString *fileTitle=[file objectForKey:#"id"];
[titles addObject: fileTitle];
and use string value.
[[titles addObject: fileTitle] stringValue];
I guess you are doing something like this in your -tableView: cellForIndexPath:
UITableViewCell *cell = [...];
cell.titleLabel.text = titles[indexPath.row];
You can only use NSString for -[UILabel setText:] method.
Convert your NSNumber to NSString with a simple -[NSNumber stringValue] or using NSNumberFormatter.
Everything seems ok. Just replace
NSNumber *fileTitle=[file objectForKey:#"id"];
by NSString *fileTitle = [file objectForKey:#"id"];
I just fetched data but when i try to append it to string from NSData , compiler occurs Exception error .
My code seems like this:
NSDictionary *allDAtaDictionary = [NSJSONSerialization JSONObjectWithData:_webData options:0 error:nil];
NSString *jSonStatus = [allDAtaDictionary objectForKey:#"status"];
if([jSonStatus isEqualToString:#"OK"])
{
NSDictionary *results = [allDAtaDictionary objectForKey:#"user_details"];
NSLog(#"User Details : %#",results);
All things works well until these line just starts:
NSString *userID = [results objectForKey:#"userID"];
The error output is :
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray objectForKey:]:
unrecognized selector sent to instance 0x9485a00'
and this is my jSOn output , NSLog(#"User Details : %#",results);
User Details : (
{
userCity = California;
userCountry = "United States";
userDOB = "1988-03-02";
userDetails = "";
userEmail = "xxx#xxx.com";
userFBID = 715296184;
userFullName = "John Mc Grager";
userGender = Male;
userID = 70;
userLastLoginTime = "2013-05-29 10:51:27";
userLatitude = "37.7858";
userLongtitude = "-122.406";
userNickName = warblader;
userPassword = "";
userStatus = 1;
userToken = "";
}
)
Seems like the JSON is an array with one dictionary in it. What you show us here at least.
So
NSArray *results = [allDAtaDictionary objectForKey:#"user_details"];
NSLog(#"User Details : %#",results);
assert(results.count>0);
NSDictionary *user = [results objectAtIndex:0];
NSString *userID = [results objectForKey:#"userID"];
NSLog(#"%#", userID);
First of all you need save use the serialised data into an array.. Then you have to use it accordingly .. in this case
NSArray *allDAtaDictionary = [NSJSONSerialization JSONObjectWithData:_webData options:0 error:nil];
Log the array in index 0 and the see what you are getting. After this you can start parsing the data.
The exception is occuring due to this. Check my answer here to parse JSON How to parse JSON with multiple instance in Object C
Your response probably has An array in it, which result Dictionary is being holding, so you need to use ObjectAtIndex rather calling objectForKey
Hello i get a json that looks like this:
features: (
{
attributes = {
Gecontroleerd = Ja;
};
geometry = {
x = "5.968097965285907";
y = "52.50707112779077";
};
}
)
From this code:
NSDictionary *root = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil];
NSArray *data = [root objectForKey:#"features"];
NSLog(#"features: %#", data );
for (NSArray *row in data) {
NSString *latitude = row[5];
NSString *longitude = row[7];
NSString *crimeDescription = #"test";
NSString *address = #"banaan";
And u need to x values 5.968097965285907 for latitude
and y values 52.50707112779077 for longitude
But i get this error:
[__NSCFDictionary objectAtIndexedSubscript:]: unrecognized selector sent to instance 0x14831450
2012-11-14 10:10:59.000 ArrestPlotter[6330:c07] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary objectAtIndexedSubscript:]: unrecognized selector sent to instance 0x14831450'
*** First throw call stack:
(0x1860012 0x1655e7e 0x18eb4bd 0x184fbbc 0x184f94e 0x2dbc 0x3b8f 0x1cc1e 0x16696b0 0xfa0035 0x17e3f3f 0x17e396f 0x1806734 0x1805f44 0x1805e1b 0x224a7e3 0x224a668 0x4a765c 0x25bd 0x24e5 0x1)
libc++abi.dylib: terminate called throwing an exception
(lldb)
Does anyone wich row i need to select?
I guess that the only thing is that the row number needs to be changed. Or maybe there should be something like this : [1][5]. Im not quite sure how this works
NSArray *data = [root objectForKey:#"features"];
NSLog(#"features: %#", data );
for (NSDictionary *dic in data) {
NSDictionary geometry = [dic objectForKey:#"geometry"];
// Do what you want..
NSString *myAwesomeX = [geometry objectForKey:#"x"];
NSString *myAwesomeY = [geometry objectForKey:#"y"];
}
The problem here is that you are trying to send a selector message to object row, that is in memory a NSDictionary (NSCFDictionary?) object, and you are trying to manage it like a NSArray.
The method objectAtIndexedSubscript (is underlying called by row[5] and row[7]) exists in NSDictionary, but no in NSArray.
Change
for (NSArray *row in data) {
by
for (NSDictionary *row in data) {
Also, you have to change the management of data inside for, look at the result of your log statement and act accord whit it.
I hope this will help!