-[__NSArrayM objectForKey:]: unrecognized selector sent to instance 0x9d0d720 - ios

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[jsonArray removeAllObjects];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
responseData = nil;
NSMutableArray *sdf = [(NSDictionary*)[responseString JSONValue] objectForKey:#"DataTable"];
NSMutableArray * myArray = [[NSMutableArray alloc] init];
NSMutableDictionary * myDict = [[NSMutableDictionary alloc] init];
if (([(NSString*)sdf isEqual: [NSNull null]])) {
// Showing AlertView Here
}else {
for (int i=0; i<[sdf count]; i++) {
myDict=[sdf objectAtIndex:i];
[myArray addObject:[myDict objectForKey:#"RxnCustomerProfile"]];
}
jsonArray=[myArray mutableCopy];
NSMutableDictionary *dict=[jsonArray objectAtIndex:0];
if ([dict count]>1) {
// Showing AlertView Here
}
}
}
Hi Everyone, I have an issue regarding the -[__NSArrayM objectForKey:]: .
Tried to solve but did not get the better solution for it. Please help me to
find the solution. Thanks In Advance
Below is the issues
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM objectForKey:]: unrecognized selector sent to instance 0x19731d40'

This is a debugging problem and nobody can really solve it for you as you are using non-local variables whose definition and values are unknown, don't mention that you are using SBJSON (I guess), etc. But let's see if we can give you some pointers. Your error:
[__NSArrayM objectForKey:]: unrecognized selector sent to instance
That tells you that you sent a dictionary method (objectForKey) to an array (__NSArrayM). So somewhere you have an array when you think you have a dictionary.
Now you declare and allocate a dictionary:
NSMutableDictionary * myDict = [[NSMutableDictionary alloc] init];
but then assign to it:
myDict=[sdf objectAtIndex:i];
So this discards the dictionary you allocated and instead assigns whatever is at index i in the array sdf. How do you know, as opposed to think, that the element of the array is a dictionary? You don't test to check...
So where did sdf come from? This line:
NSMutableArray *sdf = [(NSDictionary*)[responseString JSONValue] objectForKey:#"DataTable"];
So that calls JSONValue on some unknown string, assumes the result is a dictionary (could it be an array? or a failure?), looks up a key (did your error come from this line?), and assumes the result is an array.
So what you need to do is go and test all those assumptions, and somewhere you'll find an array where you think you have a dictionary.
Happy hunting!

YOU FETCH THE VALUE IN ARRAY FORMAT AND YOU INTEGRATE METHOD IN DICTIONARY.

You do not need to iterate keys and values of dict can directly pass values to array inside else part like:
myArray = [sdf objectForKey:#"RxnCustomerProfile"];
Key RxnCustomerProfile itself containing array not dictionary.
Change your if else part use below code:
if (([(NSString*)sdf isEqual: [NSNull null]])) {
// Showing AlertView Here
}else {
myArray = [sdf objectForKey:#"RxnCustomerProfile"];
}

NSMutableArray *sdf = [(NSDictionary*)[responseString JSONValue] objectForKey:#"DataTable"];
Check Sdf
if([sdf isKindOfClass:[NSDictionary class]])
{
NSLog(#"Dictionary");
}
else if([sdf isKindOfClass:[NSArray class]])
{
NSLog(#"NSArray");
}
else if([sdf isKindOfClass:[NSMutableArray class]])
{
NSLog(#"NSMutableArray");
}

First of all it seems like your json is not actually correctly formatted. Without knowing what responseData looks like it's difficult to say exactly what is wrong. But in your code there are a few areas where it can be improved.
First of all you don't need to use [responseString JSONValue]. You can short circuit it entirely with
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil];
NSArray *sdf = responseDictionary[#"DataTable"];
Now, the rest all depends on the data in responseData.
But you can make your code a little bit cleaner with (if I understand what you're trying to achieve correctly:
NSMutableArray *myArray = [NSMutableArray array];
if ([sdf isEqual:[NSNull null]]) {
// Showing AlertView here
} else {
for (NSDictionary *myDict in sdf) {
[myArray addObject:dict[#"RxnCustomerProfile"]];
}
}
// No idea what you're trying to achieve here, but here goes:
jsonArray = [myArray mutableCopy];
NSDictionary *dict = jsonArray.first;
if (dict.count > 1) {
// Showing AlertView here
}
Some things to note. You make very liberal use of NSMutableArray and NSMutableDictionary for no apparent reason. Only use mutable if you're actually changing the array or dictionary.

Related

How to add an index to an NSMutableArray based on value in another array?

I've looked at lots of questions about NS(Mutable)Arrays. I guess I am not grokking the concept, or the questions don't seem relevant.
What I' trying to do is the following:
Incoming Array 1:
Name
Code
Start time
End Time
etc
Incoming Array 2
Code
Ordinal
What I want:
Ordinal
Name
Code
Start time
End Time
etc
This is my code at present:
int i=0;
for (i=0; i < stationListArray.count; i++) {
NSString *slCodeString = [stationListArray[i] valueForKey:#"Code"];
NSLog(#"slCodeString: %#", slCodeString);
int j=0;
for (j=0; j< lineSequenceArray.count; j++) {
NSString *lsCodeString = [lineSequenceArray[j]valueForKey:#"StationCode"];
NSLog(#"lsCodeString: %#", lsCodeString);
if ([slCodeString isEqualToString:lsCodeString]) {
NSLog(#"match");
NSString *ordinalString = [lineSequenceArray[j] valueForKey:#"SeqNum"];
NSLog(#"ordinalString: %#", ordinalString);
[stationListArray[i] addObject:ordinalString]; <------
}
}
}
I'm logging the values and they return correctly.
The compiler doesn't like the last statement. I get this error:
[__NSCFDictionary addObject:]: unrecognized selector sent to instance 0x7f9f63e13c30
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary addObject:]: unrecognized selector sent to instance 0x7f9f63e13c30'
Here is an excerpt from the StationListArray:
(
{
Address = {
City = Greenbelt;
State = MD;
Street = ".....";
Zip = 20740;
};
Code = E10;
Lat = "39.0111458605";
Lon = "-76.9110575731";
Name = Greenbelt;
}
)
NSString *ordinalString = [lineSequenceArray[j] valueForKey:#"SeqNum"]; //Is NSString
[stationListArray[i] addObject:ordinalString];//<----- trying to call addObject method of NSMutableArray on NSDictionary -> Not GOOD
When you do [stationListArray[i] you get NSDictionary in your case
(Generally it returns an NSObject that is inside the NSArray at the given index, in your case is NSDictionary).
So in order to complete your desired operation: you should make an NSMutableDictionary instance (In this case it should be the mutableCopy from the stationListArray[i]'s NSObject which is NSDictionary, when you do mutableCopy it copies the entire NSDictionary and makes it Mutable)
make the changes on it and then assign it in to the stationListArray[i]
For example:
NSMutableDictionary * tempDict = [[stationArray objectAtIndex:i]mutableCopy];//Create a mutable copy of the `NSDictionary` that is inside the `NSArray`
[[tempDict setObject:ordinalString forKey:#"Ordinal"]; //In this line you are adding the Ordinal `NSString` in to the tempDict `NSMutableDictionary` so now you have the desired `NSMutableDictionary`. You can change the key to whatever you wish.
[stationArray replaceObjectAtIndex:i withObject:[tempDict copy]];//Swap the original(old NSDictionary) with the new updated `NSMutableDictionary` I used the copy method in order to replace it with the IMMUTABLE `NSDictionary`
[stationListArray[i] addObject:ordinalString]; <------
This is not an NSMutableArray. You must use
[stationListArray addObject:ordinalString]; <------
instead of the what you have done.
Here is the way you can write a better understandable code because for me the code is not clear.You can also try like this in loop to achieve what you want.
NSMutableArray *array = [NSMutableArray new];
NSMutableDictionary *dictMain = [NSMutableDictionary new];
NSMutableDictionary *dictAddress = [NSMutableDictionary new];
[dictAddress setValue:#"Greenbelt" forKey:#"City"];
[dictAddress setValue:#"MD" forKey:#"State"];
[dictAddress setValue:#"....." forKey:#"Street"];
[dictAddress setValue:#"20740" forKey:#"Zip"];
[dictMain setValue:dictAddress forKey:#"Address"];
[dictMain setValue:#"E10" forKey:#"Code"];
[dictMain setValue:#"39.0111458605" forKey:#"Lat"];
[dictMain setValue:#"-76.9110575731" forKey:#"Lon"];
[dictMain setValue:#"Greenbelt" forKey:#"Name"];
[array addObject:dictMain];

__NSCFString objectForKeyedSubscript: exception

I take datas from server. My app work fine in Sinulator and test device iPhone 4s, but one man have problem on iPod 4. He get exception:
-[__NSCFString objectForKeyedSubscript:]: unrecognized selector sent to instance 0x1d263a20
I cann't use this device so I write code to know where crash was.
if (![dictionaryRest[#"compliments"] isEqual:[NSNull null]]) {
NSMutableArray *array = [NSMutableArray new];
NSMutableArray *firstArray = [NSMutableArray new];
for (NSDictionary *dic in dictionaryRest[#"compliments"]) {
Compliment *compl = [Compliment new];
if (![dic[#"ID_promotions"] isEqual:[NSNull null]])
compl.ID = [dic[#"ID_promotions"] integerValue];
So in last 2 strings this exception was. What the reason of this? So I understand that I need use
if ([dict objectForKey:[#"compliments"])
instead
if (![dict[#"compliments"] isEqual:[NSNull null]])
and in all another cases.
I test now and I have in my dictionary for ID:
You have an NSString instance in your dictionary where you expect a dictionary.
Note that your "use this instead of that" has nothing to do with the problem.
-objectForKeyedSubscript: is an instance method on NSDictionary object.
__NSCFString objectForKeyedSubscript: exception indicates that the method -objectForKeyedSubscript is somehow getting called on some NSString object.
So basically you just have to properly check for the class of the object before you can safely assume that it is actually dictionary.
if([dic isKindOfClass:[NSDictionary class]])
{
id obj = dic[#"key"];
}

[__NSCFString count]: unrecognized selector sent to instance 0x6a7a1a0 while taking datas from json string

- (void)viewDidLoad
{
binding.logXMLInOut = YES; // to get logging to the console.
StationDetailsJsonSvc_getAvailableStations *request = [[StationDetailsJsonSvc_getAvailableStations new] autorelease];
request.userName=#"twinkle";
request.password=#"twinkle";
StationDetailsJsonSoap11BindingResponse *resp = [binding getAvailableStationsUsingParameters:request];
for (id mine in resp.bodyParts)
{
if ([mine isKindOfClass:[StationDetailsJsonSvc_getAvailableStationsResponse class]])
{
resultsring = [mine return_];
NSLog(#"list string is%#",resultsring);
}
}
#pragma mark parsing
SBJsonParser *parserq = [[SBJsonParser alloc] init];
//if successful, i can have a look inside parsedJSON - its worked as an NSdictionary and NSArray
results= [parserq objectWithString:resultsring error:nil];
NSLog(#"print %#",results);
for (status in results)
{
NSLog(#"%# ",[status objectForKey:#"1" ]);
events=[status objectForKey:#"1"];
NSLog(#"get%#",events);
NSLog(#"events%#",events);
}
events=[status objectForKey:#"1"];
NSLog(#"post%#",events);
self.navigationController.navigationBarHidden=YES;
[whethertableview reloadData];
[super viewDidLoad];
}
this is my code am not getting tableview contents if i run my app crashes getting [NSCFString count]:unrecognized selector sent to instance
You should not get count on NSString but on arrays
you should call [yourString length] to check if the string has something.
You are trying to get the count of a string , which is crashing the App
There are various improvements you could make with this code, but I think I see the problem:
As you are not using ARC, you need to retain what you take out of the parser:
So instead of:
events=[status objectForKey:#"1"]
You need to do:
events= [[status objectForKey:#"1"] retain];
Your crash is caused by accessing a variable that has already been released. More than likely it is the events variable.
...and to add to this. events is probably an NSArray which 'count' is being called on. And [status objectForKey:#"1"] is returning a string... there are many possibilities which i'm speculating about. If events is an NSArray, this isn't the way to add objects to the array.. you repeatedly call events=[status objectForKey:#"1"]; in a loop too.

JSON not working as expected on iOS

I'm currently trying to parse this JSON
[{"id":"1","dish_name":"Pasta & ketchup","category":"main","rating":"5","rating_count":null,"author":"Me","ingredients":"Pasta\nKetchup\nWater","description":"Very good for students\nCheap too!","picture":null,"protein":"7","fat":"11","carbs":"12","calories":"244","developer_lock":"1"},{"id":"2","dish_name":"Pasta & Kødsovs","category":"main","rating":"5","rating_count":null,"author":"Me","ingredients":"Pasta\nKødsovs\nWater","description":"Very good for students\nCheap too!","picture":null,"protein":"7","fat":"11","carbs":"12","calories":"244","developer_lock":"1"}]
But it fails and crashes with this code
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSError *error = NULL;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
recipes = [[NSArray alloc] initWithArray:[json objectForKey:#"dish_name"]];
[uit reloadData];
}
Do someone have any clue, why it crashes with error -[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x8077240
?
Thanks in advance.
The error message beginning with [__NSCFArray objectForKey:] means that you have an NSArray (the root object of the JSON is an array - notice the opening and closing square brackets) and you're trying to treat it as a dictionary. All in all,
recipes = [[NSArray alloc] initWithObject:[json objectForKey:#"dish_name"]];
should be
recipes = [[NSArray alloc] initWithObject:[[json objectAtIndex:0] objectForKey:#"dish_name"]];
Note that there are two objects in the array, so you might want to use [json objectAtIndex:1] as well.
Edit: if you have a dynamic number of recipes, you can do this:
recipes = [[NSMutableArray alloc] init];
for (NSDictionary *dict in json) {
[recipes addObject:[dict objectForKey:#"dish_name"]];
}
If your json NSDictionary were a real & valid NSDictionary object, your call to this:
[json objectForKey:#"dish_name"]
should return exactly this:
"Pasta & ketchup"
Which is definitely not an array. It's a NSString object.
Which would be why the call to "initWithArray" is bombing.

Cannot access NSDictionary

I created a JSON using a PHP script.
I am reading the JSON and can see that the data has been correctly read.
However, when it comes to access the objects I get unrecognized selector sent to instance...
Cannot seem to find why that is after too many hours. Any help would be great!
My code looks like that:
NSDictionary *json = [[NSDictionary alloc] init];
json = [NSJSONSerialization JSONObjectWithData:receivedData options:kNilOptions error:&error];
NSLog(#"raw json = %#,%#",json,error);
NSMutableArray *name = [[NSMutableArray alloc] init];
[name addObjectsFromArray: [json objectForKey:#"name"]];
The code crashes when reaching the last line above.
The output like this:
raw json = (
{
category = vacancies;
link = "http://blablabla.com";
name = "name 111111";
tagline = "tagline 111111";
},
{
category = vacancies;
link = "http://blobloblo.com";
name = "name 222222222";
tagline = "tagline 222222222";
}
),(null)
2012-06-23 21:46:57.539 Wind expert[4302:15203] -[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0xdcfb970
HELP !!!
json is an array from what you've shown, not a dictionary. I can tell this because of the parentheses surrounding the whole of the log output for json. Inside the array are dictionaries, which I can tell by the fact that they are surrounded by braces.
So, it looks like you want something like this:
NSError *error = nil;
NSArray *json = [NSJSONSerialization JSONObjectWithData:receivedData options:kNilOptions error:&error];
NSLog(#"raw json = %#,%#",json,error);
NSMutableArray *name = [[NSMutableArray alloc] init];
for (NSDictionary *obj in json) {
[name addObject:[obj objectForKey:#"name"]];
}
As an aside you will notice I have removed the unnecessary initialisation of json to an object before overwriting in the next line with JSONObjectWithData:options:error:. In an ARC world it wouldn't be a leak but it's still completely unnecessary to allocate an object just to get rid of it again a moment later. Also I added in the NSError *error = nil; line since that was not there and was obviously necessary to compile.
The problem appears to be that the root level of your JSON is an array, not a dictionary (note the parenthesis instead of curly brace as the first character in the logged output). Arrays do not have objectForKey selector. Perhaps you intend to take objectAtIndex:0 first, or else iterate over all the the items?
As an aside, the first line of your code makes a completely wasted initialization of an NSDictionary. It is simply overwritten and deallocated on the very next line.

Resources