Loop through NSArray of objects that has no id's - Objective C - ios

I have an NSArray that looks like the following
[{
"Id":"456",
"Type":"Dog",
"Sound":"Bark",
},
{
"Id":"789",
"Type":"Cat",
"Sound":"Meow",
}]
I tried the following
for (id key in array) { // Doesn't work
NSLog(#"%#", key[#"Type"]);
}
and I tried
NSLog(#"%#", [array firstObject]); // Doesn't work
This doesn't work however because there is no id to access. I get an NSInvalidArgumentException for both. How would I successfully loop through the two objects that I have and print out the type?

It is a bit confusing, because you say:
I have an NSArray that looks like the following
[{
"Id":"456",
"Type":"Dog",
"Sound":"Bark",
},
{
"Id":"789",
"Type":"Cat",
"Sound":"Meow",
}]
but then, you also say:
NSLog(#"%#", [array firstObject]); // Doesn't work
Of course, you don't indicate what "Doesn't work" means... Does it throw an error? Does it output nothing? Does it output something, but not what you expect?
However, if you did have an array that "looks like that", then let's see what it actually is...
We can think of a Dictionary as:
{ key1:value1, key2:value2, key3:value3, etc... }
and we can think of an Array as:
[object1, object2, object3, etc...]
So, assuming your example data is structured like that in a valid NSArray, that means you have an Array of 2 Dictionary objects. If you want to output them to the console, you can do:
// log the first object in the array
NSLog(#"%#", [array firstObject]);
and the output should be a Dictionary:
{
Id = 456;
Sound = Bark;
Type = Dog;
}
You can also do:
// for each element (each Dictionary) in array, output the dictionary
for (NSDictionary *d in array) {
NSLog(#"%#", d);
}
resulting in:
...[1234:4321] {
Id = 456;
Sound = Bark;
Type = Dog;
}
...[1234:4321] {
Id = 789;
Sound = Meow;
Type = Cat;
}
and, finally:
// for each element (each Dictionary) in array
for (NSDictionary *d in array) {
// for each Key in each Dictionary
for (NSString *key in [d allKeys]) {
NSLog(#"%# - %#", key, d[key]);
}
}
which will give you:
...[1234:4321] Sound - Bark
...[1234:4321] Id - 456
...[1234:4321] Type - Dog
...[1234:4321] Sound - Meow
...[1234:4321] Id - 789
...[1234:4321] Type - Cat
Note that dictionaries are *un-ordered, so don't count on stepping through the keys in the same order each time.
Hope that makes sense. Of course, you still need to find out why you think you have a NSArray when you don't.

Related

Enumerating all the Keys and Values

From API, I am able to get below format.
{
"status": true,
"data": {
"29": "Hardik sheth",
"30": "Kavit Gosvami"
}
}
In that, I want to fetch Key and value both.
How can i do this using NSDictionary?
Sometime, you need to iterate over all the key/value pairs in a dictionary. To do this, you use the method -allKeys to retrieve an array of all the keys in the dictionary; this array contains all the keys, in no particular (ie random) order. You can then cycle over this array, and for each key retrieve its value. The following example prints out all the key-values in a dictionary:
void
describeDictionary (NSDictionary *dict)
{
NSArray *keys;
int i, count;
id key, value;
keys = [dict allKeys];
count = [keys count];
for (i = 0; i < count; i++)
{
key = [keys objectAtIndex: i];
value = [dict objectForKey: key];
NSLog (#"Key: %# for value: %#", key, value);
}
}
As usual, this code is just an example of how to enumerate all the entries in a dictionary; in real life, to get a description of a NSDictionary, you just do NSLog (#"%#", myDictionary);.
Are you using Swift or Objective-C?
In Objective-C you'd use allKeys to get the list of keys, as outlined by #BhavinSolanki in his answer.
In Swift you could do that as well (using the Swift Dictionary keys property, myDictinoary.keys)
Alternately you could use tuples to loop through the keys and values:
for (key, value) in dictionary {
NSLog (#"Key: %# for value: %#", key, value);
}

__NSCFDictionary doesn't respond to any selectors

I am trying to Parse JSON that looks like this:
food = {
"food_id" = 4823;
servings = {
serving = (
{
calcium = 9;
calories = 221;
carbohydrate = "16.20";
cholesterol = 31;
I can successfully retrieve the array at the [food][servings][serving] level, which I confirm via a log statement has the appropriate class, __NSCFArray, but I run into a problem when iterating through that array and trying to do useful things with the contained information:
for (id foodId in resultsPerServing) {
NSLog(#"hree is a result %#", foodId);
foodObjectClass *foodObject = [foodObjectClass new];
NSDictionary *foodIdDictionary = (NSDictionary *)foodId;
if ([foodIdDictionary respondsToSelector:#selector(allKeys)]) {
[foodObject getDetailsFromResponseObject:foodIdDictionary];
} else {
unsigned int mc = 0;
Method * mlist = class_copyMethodList(object_getClass(foodIdDictionary), &mc);
NSLog(#"%d methods", mc);
for(int i=0;i<mc;i++)
NSLog(#"Method no #%d: %s", i, sel_getName(method_getName(mlist[i])));
[NSException raise:#"DIDN'T GET A DICTIONARY" format:#"here is the object %# which has class %#", resultsPerServing, [responseObject class]];
}
}
This causes the NSException to be raised without fail although in the NSException the output from printing the object looks like a dictionary. Additionally, when the exception prints out the class of the object which does not respond to allKeys, that object has class __NSCFDictionary. What gives? Why does this dictionary not have an allKeys method and how can I get a functional dictionary to work with?
Even more puzzling is that the runtime code below (copied from an SO post for which I have lost the link) indicates that the dictionary has 0 methods. Why does this object have no methods? How can I get an object that does have methods?
make a check to confirm that it as NSDictionary first?
if ([foodId isKindOfClass:[NSDictionary class]] ) {
foodIdDictionary = (NSDictionary *)foodId;
[foodObject getDetailsFromResponseObject:foodIdDictionary];
}

Comparing Dictionaries with Objects Value of Array in IOS

I am having N number of Dictionaries & having array that contains objects.
I need to iterate and check whether value for key EmployeeID of dictionary exists at Object. say obj.empId or not in array.
Dictionary looks like below
{
"Message":[
{
"EmpID": 3749,
"Dept": 10,
"EmployeeName": "John",
},
{
},
{
}]
} //so many dictionaries..not one
Example: I already have an array with 10 records say obj.empID holds from 1-10. From service I am getting 10 records say 10 dictionaries. In that key EmpID holds values 5-15.
So, How can I iterate the loop so that to identify that new records are retrieved with different EmpID's then existing Records.
Here is the Code I have done so far..
NSArray *responseArray=responseDict[#"Message"];
for (NSDictionary *dict in responseDict[#"Message"]) {
for (id key in responseDict) {
if ([key isEqualToString:#"EmpID"]) {
for (Employees *empObj in emparray)
{
BOOL isExists=YES;;
if (![empObj.empid isEqualToString:[responseDict objectForKey:key]]) {
isExists=NO;
break;
//here I need to do the logic..
}
}
}
}
}
But it will not get accurate results or logic is nor correct..
Please suggest any better solutions for above task or where I am going wrong..
Any Ideas or suggestions are appreciated..
Thanks..,
Without using so many loops, you may follow below code to check record is exist ot not.
NSArray *responseArray=responseDict[#"Message"];
for (Employees *empObj in emparray)
{
BOOL isExists=NO;
if ([[responseArray valueForKey:#"EmpID"]containsObject:empObj.empid]) {
isExists=YES;
NSLog(#"%# EmpID Exist",empObj.empid);
//here I need to do the logic..
}else{
NSLog(#"%# EmpID Not Exist",empObj.empid);
}
}
Dont use iterations, Code smartly, Use following code...
NSArray *responseArray=responseDict[#"Message"];
NSArray * empIdResponseArray = [responseArray valueForKeyPath:#"#unionOfObjects.EmpID"];
NSArray * empIdLocalArray = [emparray valueForKeyPath:#"#unionOfObjects.empid"];
NSMutableSet *empIdResponseSet = [NSMutableSet setWithArray: empIdResponseArray];
NSSet *empIdLocalSet = [NSSet setWithArray: empIdLocalArray];
[empIdResponseSet intersectSet: empIdLocalSet];
NSArray *commonElementArray = [empIdResponseSet allObjects];
NSMutableArray *newElementArray = [NSMutableArray arrayWithArray:empIdResponseArray];
[newElementArray removeObjectsInArray:commonElementArray];
for (int index = 0; index < newElementArray.count; index++)
{
NSMutableDictionary * dictEmp = [NSMutableDictionary dictionaryWithDictionary:[newElementArray objectAtIndex:index]];
NSLog(#"EMPLOYEE = %#",dictEmp);
// Add your Logic for new records only....
// Enjoy :)
}

iOS filter array of dictionary base on value and not the key

I have array with dictionaries like this:
Array: (
{
customerUS= {
DisplayName = "level";
InternalName = "Number 2";
NumberValue = 1;
},
customerCAN= {
DisplayName = "PurchaseAmount";
InternalName = "Number 1";
NumberValue = 3500;
};
}
)
I want to filter the dictionaries base on particular value and not the key. For example I want all the dictionaries with values on any key of 3500. Does any body knows how can I do this?
I'll really appreciate your help.
Try a predicate format like:
#"%# IN SELF", testValue
When you filter the array each will be run against the IN. When you pass IN a dictionary it uses the values of the dictionary.
you can also use
-keysOfEntriesPassingTest:
of NSDictionary. Just pass in a block like so:
for(NSDictionary *myDictionary in myArray){
NSSet *resultSet = [myDictionary keysOfEntriesPassingTest:^(id key, id object, BOOL *stop) {
//assuming that 3500 is an int, otherwise use appropriate condition.
if([[NSNumber numberWithInt:object] isEqual:[NSNumber numberWithInt:3500]]){
return YES;
}else{
return NO;
}
}];
if (resultSet.count>0){
//do whatever to myDictionary
}
}

Deleting a particular object in NSDictionary

My Categories Dictionary is like this
"category": {
"position": 1,
"updated_at": "2012-11-21T11:02:14+05:30",
"is_default": false,
"name": "Ge",
"folders": [
{
How can i delete a particular Category object alone which has is_default as true?
I tried the following --
for(id obj in category )
{
if([obj isEqualToString:#"is_default"] && [[category objectForKey:#"is_default"] isEqualToNumber:#0])
{
but was unable to find a way to access the key of the particular category and hence delete it.
First thing first: You can not delete object from Dictionary(or Array Or Set) while Enumerating.
But it is not impossible.
Try this:
NSArray *keys = [category allKeys];
for(NSString *key in keys )
{
obj = [category objectForKey:key];
if([key isEqualToString:#"is_default"] && [[category objectForKey:#"is_default"] isEqualToNumber:#0])
{
[category removeObjectForKey:key]
}
}
Comment if you face any problem.
Al The Best.
You can get the keys (an object may be stored in the dictionary multiple times, using different keys) that your object is stored at like this:
NSArray *keys = [myDictionary allKeysForObject:obj];
Now that you have the key(s), it's easy to delete the object:
if (keys.count > 0) {
[myDictionary removeObjectForKey:keys.lastObject];
}
Searching through the values of a dictionary is a relatively slow operation, by the way. If you do this very often, a dictionary might not be the best data structure.

Resources