Fetching data from PLIST by Fast Enumeration - ios

I am using for in loop to fetch data from plist.For in loop is correct as it is printing value. But,suddenly, it is showing following exception:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString objectAtIndexedSubscript:]: unrecognized selector sent to instance 0x97a14b0'.
Code:
NSString *sss=[[NSBundle mainBundle]pathForResource:#"s" ofType:#"plist"];
NSDictionary *dic=[[NSDictionary alloc]initWithContentsOfFile:sss];
for(NSArray *arr in [dic allKeys])
{
NSLog(#"%#",arr); // Ii is printing value
NSLog(#"%#",arr[0]); // It is showing exceptions
}
Plist:
There is some problem with NSLog(#"%#",arr[0]);. I want to print values of first index of arrays a and b.

here [dic allKeys] will be keys in dic that are NSString like "a", "b" etc.
so for your plist the code should be,
NSString *sss=[[NSBundle mainBundle]pathForResource:#"s" ofType:#"plist"];
NSDictionary *dic=[[NSDictionary alloc]initWithContentsOfFile:sss];
for(NSString *key in [dic allKeys])
{
NSLog(#"%#",key);
NSArray *value = [dic objectForKey:key];
NSLog(#"%#",value[0]);
}

Related

NSInvalidArgumentException', reason: '-[__NSArrayI length]: unrecognized selector sent to instance 0x165d5150'

Hi I am getting this data form server
NSDictionary*feed=[saveDic objectForKey:#"feed"];
NSLog(#"%#",feed); //Outputs: feed = ( { code = yQ7j0t; "user_id" = 889445341091863; } ); }
NSLog(#"%#",[feed valueForKey:#"code"]);
NSString *referralCode = [feed valueForKey:#"code"];
NSLog(#"%#",referralCode);
self.referralCode.text=referralCode;
And beacuse of that I am getting below error.
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI length]: selector sent to instance 0x165d5150'``
Any help will be appreciated.
The issue is, your feed key holds an array. You are not properly handling that in your code, that is why the crash occurs. When you call valueForKey: it retrieves an array of values held by that specific key.
For fixing that you can use:
NSArray *feed = [saveDic objectForKey:#"feed"];
NSArray *referralCodes = [feed valueForKey:#"code"];
NSString *referralCode = referralCodes.count ? referralCodes[0] : #"";
NSLog(#"%#",referralCode);
But I personally prefer using objectForKey: instead of valueForKey:. So you can re-write the code like:
NSArray *feed = [saveDic objectForKey:#"feed"];
NSString *referralCode = feed.count ? [feed[0] objectForKey:#"code"] : #"";
NSLog(#"%#",referralCode);
Some where you use a variable;
yourVaribleName.length
or
[yourVaribleName length]
which should be
yourVaribleName.count
note: the crash says exactly that "yourVaribleName" is NSArray type where you wants length of the NSArray. But NSArray has not feature "length". NSArray has "Count" feature
//try with this code bellow
NSArray *referralCode = [feed valueForKey:#"code"];
NSLog(#"%#",referralCode);
self.referralCode.text=[referralCode componentsJoinedByString:#" "];//#"," or #"" what event you need
Your feed data is in array. So you have retrieve code value from array.Hope it will help you.
NSMutableArray*feed=[saveDic objectForKey:#"feed"];
NSLog(#"%#",feed);
NSLog(#"%#",[feed valueForKey:#"code"]);
NSString *referralCode = [[feed objectAtIndex:indexPath]valueForKey:#"code"];
NSLog(#"%#",referralCode);
self.referralCode.text=referralCode;

Getting an uncaught exception while iterating through result set in iOS sqlite DB

following snippet gives me :
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '- [__NSCFString count]: unrecognized selector sent to instance 0x8ce0c00'
-(void)loadInfo{
// Create the query.
NSString *query = [NSString stringWithFormat:#"select * from tableName where category=\"%#\" ", #"cat1"];
// Load the relevant data.
NSArray *results = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query]];
NSMutableArray *List = [[NSMutableArray alloc]init];
NSLog(#"Count..:%d",results.count);
for(int i=0; i<results.count; i++){
List = [[results objectAtIndex:i] objectAtIndex:[self.dbManager.arrColumnNames indexOfObject:#"itemName"]];
}
NSLog(#"Result..:::: %d", [List count]);
}
What is going wrong here? Cant i print List count? dbmanager is what I have implemented using eg. given in - http://www.appcoda.com/sqlite-database-ios-app-tutorial/
This operation replaces List on every loop iteration with a different object:
List = [[results objectAtIndex:i] objectAtIndex:[self.dbManager.arrColumnNames indexOfObject:#"itemName"]];
Judging from the error, the object happens to be NSString.
What you probably wanted is to add objects to your mutable array List:
[List addObject:[[results objectAtIndex:i] objectAtIndex:[self.dbManager.arrColumnNames indexOfObject:#"itemName"]]];

NSMutableDictionary issues

I'm trying to insert an object in my dictionary, but first, I want to test if it's a NSMutableDictionary :
if ([[[self.response objectForKey:#"X"] objectAtIndex:0] isKindOfClass:[NSMutableDictionary class]]) {
[[[self.response objectForKey:#"X"] objectAtIndex:0]setObject:#"Hello" forKey:#"Y"];
}
I get this issue :
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object'
You can check for the same selector which is crashing,
if([object respondsToSelector:#selector(setObject:forKey:)]) {
//If YES, it is NSMutableDictionary
}
else {
//Not mutable
}
Hope that helps!
Use isMemberOfClass instead of isKindOfClass
Try this,
if ([[[self.response objectForKey:#"X"] objectAtIndex:0] isKindOfClass:[NSDictionary class]]) {
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:[[self.response objectForKey:#"X"] objectAtIndex:0]];
[dict setObject:#"Hello" forKey:#"Y"];
NSMutableArray *xArray = [NSMutableArray arrayWithArray:[self.response objectForKey:#"X"]];
[xArray replaceObjectAtIndex:0 withObject:dict];
[self.response setObject:xArray forKey:#"X"];
}

How to get count of objects in NSArray inside of NSDictionary

I need to get a count of the objects in array inside of NSDictionary. For example:
po _dictionary
{
keys = (
"one",
"two"
);
}
Taking in consideration this is an array : [_dictionary objectForKey:#"keys"]
my question is how can I get the count in the array?
I try this :
[[[_tutorials objectForKey:#"keys"] allKeys ]count];
but I'm getting this error:
* Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: '-[__NSCFArray allKeys]:
unrecognized selector sent to instance 0xa419ea0'
[_dictionary objectForKey:#"keys"] is an NSArray and not an NSDictionary. Therefore, it doesn't understand the allKeys method. Drop it and it should work:
[[_dictionary objectForKey:#"keys"] count];
Here you go:
NSLog(#"%lu", _dictionary[#"keys"].count);
NSDictionary has a method to get a NSArray of keys which I find is much more readable than using objectForKey:
[[_dictionary allKeys] count]
NSLog(#"%d", [[_dictionary objectForKey:#"keys"] count]);
As your [_dictionary objectForKey:#"keys"] is an array you can get the count directly.
NSDictionary *res=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error1];
NSLog(#"%d",[[res valueForKey:#"result"] count]);

Weird crash while accessing array objects at a given index in IOS

We have the following method where we are trying to access an array object at a given index. The array is resultArr. When we do a resultArr count it gives us a result of 13. So we know that the array is not null but when we try to do objectAtIndex it crashes with the error.
Function:
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSArray *keys = [json allKeys];
NSLog(#"keys: %#",keys);
NSArray* htmlAttributions = [json objectForKey:#"html_attributions"]; //2
NSArray* resultArr = (NSArray *)[json objectForKey:#"result"]; //2
NSArray* statusArr = [json objectForKey:#"status"]; //2
NSLog(#"htmlAttributions: %#",htmlAttributions);
NSLog(#"result: %#", resultArr); //3
NSLog(#"status: %#", statusArr); //3
NSLog(#"resultCount: %d",[resultArr count]);
[resultArr objectAtIndex:0];
}
Error:
2012-04-01 22:31:52.757 jsonParsing[5020:f803] resultCount: 13 2012-04-01 22:31:52.759 jsonParsing[5020:f803] -[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x6d2f900 2012-04-01 22:31:52.760 jsonParsing[5020:f803] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x6d2f900'
*** First throw call stack:
Thank you.
The error message is fairly descriptive. One of the objects that your code expects to be an NSArray is actually an NSDictionary. You cannot access fields inside of an NSDictionary by using NSArray methods (and casting from NSDictionary* to NSArray* will not convert an NSDictionary into an NSArray).
This would mean that inside of the JSON, one of your elements was serialized as an object/associative array instead of as a plain array. You can easily determine which one by looking at your JSON data as text, and finding the item that uses { and } instead of [ and ].
You are saying
NSArray* resultArr = (NSArray *)[json objectForKey:#"result"]; //2
But that does not make this object ([json objectForKey:#"result"]) an NSArray. It is an NSDictionary, and sending it a message that NSDictionary does not respond to (objectAtIndex:) causes a crash.
You were able to send it the count message without crashing because NSDictionary does happen to respond to the count message. But your preconception that this is an array is still mistaken.
You cannot cast an NSDictionary* to an NSArray* as you tried to do with this line: NSArray* resultArr = (NSArray *)[json objectForKey:#"result"];, then call -objectAtIndex.

Resources