Find a Value From Array of NSDictionary? - ios

I have a NSArray containing multiple NSDictionary object and this NSDictionary again has one array of some NSStrings/NSNumbers...
This NSArray looks like below...
(
{
"bins_arr" = (
531662,
549177,
540165,
546616,
549777,
549778,
549779,
532663,
549852,
529495,
532662,
529117,
533890,
544170,
554619,
542418,
540175,
552137,
542531,
542556,
552093,
540531,
552790,
541497,
554637,
526421,
431921,
412800,
431922,
464558,
508159,
456822,
450900,
508126,
508125,
517700,
430463,
414746,
461797,
438628,
461796,
510460,
520386,
421175,
455038,
524133,
518936,
455390,
405450,
456407,
438587,
405451,
493714,
549149
);
"issuing_School" = ABCDEF;
status = 0;
title = ABCDEF;
},
{
"bins_arr" = (
429393,
416644,
416645,
416643,
416646,
436390,
436389,
436388,
470613,
524253,
428306,
489604,
478893,
414767,
428348,
469645,
421493,
470614,
543705
);
"issuing_School" = PQRS;
status = 0;
title = "PQRS";
},
{
"bins_arr" = (
422316,
421560,
483541
);
"issuing_School" = TCSB;
status = 0;
title = "TCSB";
}
)
Now I need to find out a given NString/NSNumber inside the NSArray, if it gets found I need to fine corresponding issuing_School value as well, for example If I find 461797 so it should search it and find that issuing_School of this is PQRS.
One way of doing it is to get the each NSArray inside NSArray-->NSDictionary and loop through the whole NSArray and match the given number with the number present and in the NSArray, but I don't want this search since this NSArray have so may object of NSDictionary and all NSDictionary object again have big NSArray.
Can Any one suggest me some awesome view to achieve this.
Thanks in Advance.

Turn your arrays into sets.
NSArray* array = ...;
NSSet* set = [[NSSet alloc] initWithArray:array];
if ([set containsObject:aNumber]) ...
No loop involved. Constant time no matter how many elements in the set.

Related

Can't get value of NSSingleEntryDictionary

I have an NSDictionary, named "thisList", and I need to get the value of its key "list_collection".
Xcode indicates that the value is a "NSSingleEntryDictionary".
The value itself contains an array with yet another dictionary.
Please take a look at the screenshot:
Now, no matter what I try (objectforKey/valueforKey) or whatever type of object I initialize (NSArray/NsMutableArray/NSDictionary/NSMutableDictionary) I end up with a nil value.
Apparently, I miss some essential knowledge on how to handle this.
My question: how should I initialize an object with the value of the key "list_collection".
Here is a (partial) dump of the json:
Printing description of thisList:
{
archived = 0;
"chapter_part" = "";
"chapter_title" = "";
comment = "";
"cover_id" = "<null>";
"created_at" = "2017-01-06T12:59:04.000+01:00";
"date_created" = "06 January 2017";
deleted = 0;
id = 141384502;
isMyList = 1;
keywords = (
);
"list_collection" = {
lists = (
{
"speech_locale" = EN;
subject = engels;
words = (
{
word = attitude;
},
The to me most logical approach would be:
NSDictionary * myDic = [thisList objectForKey:#"list_collection"];
Note: I didn't explicitly initialize 'myDic' here.
To put things in context, here is my code:
NSString * hlists = [json objectForKey:#"lists"];
NSData* data = [hlists dataUsingEncoding:NSUTF8StringEncoding];
NSArray *wrtsLists = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonParsingError];
Lists = [[NSMutableArray alloc]init];
for (NSDictionary *thisList in wrtsLists){
WordList* theList = [[WordList alloc]init];
theList.title = [thisList valueForKey:#"title"];
[Lists addObject:theList];
NSDictionary *myDic = thisList[#"list_collection"];
>>>>this is where I put a breakpoint. myDic is nil here
}
Thanks for your insights.
You can simply get "list_collection" array from "thisList" using by this code
NSDictionary *myDic = thisList[#"list_collection"];
In the end, I figured out, that it was an Xcode problem.
The Debug area just didn't correctly display the values of my objects.
I restarted Xcode, and things started to work as expected.
I lost several hours of my life on this. But I learned a lot, thanks to your good advises.
Try this hope it helps You
NSDictionary *myDic = [thelist valueForKey:"list_collection"];

How to put NSDictionary inside NSDictionary into UITableView?

I receive following NSDictionary from my server. I don't know how to access each row and put them in UITableView. I need a for loop or something to access each of them one by one: I get following when I say:
NSLog(#"%#",dict);
{
chores = (
{
"first_due_date" = "2016-03-12";
frequency = weekly;
id = 1;
name = TEST;
parent = Blah;
"previous_chores" = (
);
},
{
"first_due_date" = "2016-03-12";
frequency = weekly;
id = 2;
name = TEST2;
parent = Blah;
"previous_chores" = (
);
},
{
"first_due_date" = "2016-03-12";
frequency = weekly;
id = 3;
name = TEST3;
parent = Blah;
"previous_chores" = (
);
}
);
}
I guess you can directly use the array without split it like following:
Suppose you have an array with dictionary and inside the dictionary as your data and kiran said:
NSArray *arrChores = [dict valueForKey #"Chores"];
Your array look like 0th index is:
{
"first_due_date" = "2016-03-12";
frequency = weekly;
id = 1;
name = TEST;
parent = Blah;
"previous_chores" = (
);
}
so you can print the name like following in cellForrowIndex:
NSLog(#"=== %#",[[arrChores objectAtIndex:indexPath.row]valueForKey:#"name"])
More easy and less maintain :)
Create a model for Chores.
Looking at the dictionary.
Chores is an array consisting of dictionaries in it.
So you can have array like this
arrChoresGlobal = [NSMutableArray new];
NSArray *arrChores = [dict valueForKey #"Chores"];
Then iterate this array and have a model.
like below
for(NSDictionary *dctChore in arrChores)
{
SomeModel *obj = [SomeModel new];
obj.first_due_date = [dctChore valueForKey:#"first_due_date"];
[arrChoresGlobal addObject:obj];
}
Then use this array count in numberOfRows in tableview
return [arrChoresGlobal count];
and in cellForRowAtIndexPath
SomeModel *obj = [arrChoresGlobal objectAtIndex:indexPath.row];
Edit :- Longer but systematic way :)

How to get values from nested array/ dictionary iOS 7

I fetch values from dictionary and need to display in UITableView, but everything works fine.
On some spot it stops running and shows thread
-[__NSCFString objectAtIndex:]: unrecognized selector sent to instance 0xbfa7670
The code below, which I used to fetch value..
[NSString stringWithFormat:#"%#",[[pageCat1 valueForKeyPath:#"img3"] objectAtIndex:indexPath.row]]
My values are fetched properly in dictionary but lags to display it?
pageCat (
{
img3 = "http://xxx.in/images/page_cat_img/75x75/4.jpg";
name = "PVC Flexible Wires";
page = (
{
id = {
text = 1;
};
img4 = "http://xxxx.in/images/page_img/75x75/1.jpg";
name = "SINGLE CORE FLEXIBLE WIRES ABOVE 6 SQMM";
},
{
id = {
text = 72;
};
img4 = "http://xxx.in/images/page_img/75x75/72.jpg";
name = "SINGLE CORE FLEXIBLE WIRES BELOW 6 SQMM";
}
);
},
{
img3 = "http://xxx.in/images/page_cat_img/75x75/3.jpg";
name = "Bare Copper Wires";
page = {
id = {
text = 29;
};
img4 = "http://xxx.in/images/page_img/75x75/29.jpg";
name = "Tinned Copper Fuse Wires";
};
},
{
img3 = "http://xxx.in/images/page_cat_img/75x75/48.jpg";
name = "Properties of Wire";
page = {
id = {
text = 85;
};
img4 = "http://xxx.in/images/page_img/75x75/85.jpg";
name = "Wires - Normal, HR - PVC, FR, FRLS & Zero Halogen";
};
}
)
Actually look at the log value, it has array and set of values.. i can't find whether it is in what form..
Can anyone help me to find the solution??
Thanks,
Yazh
it looks like [pageCat1 valueForKeyPath:#"img3"] returns a NSString and not a NSArray like you expect
make sure that it returns a NSArray before applying objectAtIndex:
it seems that pageCat1 is a NSArray so you need to write something like:
NSString *path = pageCat1[0][#"img3"];
...
As the error already tells, [pageCat1 valueForKeyPath:#"img3"] returns a NSString and you are calling objectAtIndex: on it which is not recognized for this class. Obviously, pageCat1 differs from what you expected.
Try NSLog(#"%#", pageCat1); to see what it really looks like.
// Edit
pageCat1 (as seen in your update) is an NSArray that contains items of type NSDictionary. What you really want to do is NSString *imgURL = [[pageCat1 objectAtIndex:indexPath.row] objectForKey:#"img3"];
Explanation:
1. [pageCat1 objectAtIndex:indexPath.row] returns a NSDictionary
2. [__dictionary__ objectForKey:#"img3"] returns the NSString containing your image URL
Actually I used XML data, for that i used third party to parse data. Its all of third party which parsed alternate data as array and other as non-array. Finally I check the array with
isKindOfClass
and convert it into array. Therefore my problem in app solved. :-)
Thanks to all who help me..
Please try this one:
//Assuming json is your main dictionary
NSDictionary *pageCat = [json objectForKey:#"pageCat"];
NSMutableArray *array = [[pageCat valueForKey:#"img3"]mutableCopy];
NSLog(#"Value=%#", [array objectAtIndex:indexPath.row]);

Get all similar values of key of bunch of (NSDictionary)s within an NSMuttableArray

I have a NSMuttableArray having values like
(
{
MedicineAlarmTime = "18:00:00";
MedicineDateTime = "24/04/2014 16:00:09";
},
{
MedicineAlarmTime = "18:00:00";
MedicineDateTime = "24/04/2014 16:00:26";
},
{
MedicineAlarmTime = "19:00:00";
MedicineDateTime = "24/04/2014 16:00:26";
},
{
MedicineAlarmTime = "19:00:00";
MedicineDateTime = "24/04/2014 16:00:26";
}
)
Is it possible to retrieve arrays of similar "MedicineAlarmTime" like
array1 = (
{
MedicineAlarmTime = "18:00:00";
MedicineDateTime = "24/04/2014 16:00:09";
},
{
MedicineAlarmTime = "18:00:00";
MedicineDateTime = "24/04/2014 16:00:26";
}
)
array2 = (
{
MedicineAlarmTime = "19:00:00"
MedicineDateTime = "24/04/2014 16:00:09";
},
{
MedicineAlarmTime = "19:00:00";
MedicineDateTime = "24/04/2014 16:00:26";
}
)
NSMutableDictionary *groupedAlarms = [NSMutableDictionary dictionary];
for (NSDictionary *alarm in originalArray) {
NSString *alarmTime = [alarm objectForKey: MedicineAlarmTime];
NSMutableArray *alarmGroup = [groupedAlarms objectForKey: MedicineAlarmTime]
if (alarmGroup) {
[alarmGroup addObject: alarm];
} else {
alarmGroup = [NSMutableArray arrayWithObjects: alarm, nil];
[groupedAlarms setValue:alarmGroup forKey:alarmTime];
}
}
This creates an NSMutableDictionary, groupedAlarms. The keys in groupedAlarms are the alarm times from the dictionaries in the original array--the actual alarm time value. The values for each key are arrays. The arrays contain the dictionaries of the original array--sorted based on the alarm time (which is used as the key to the array which contains them).
If you want the "alarmGroup" from the above example to be more general and not group exact matches only, you can use the same forin loop structure. The checks to determine whether to put it in an existing group or create a new group become slightly more complex, but the important thing is, we still don't need to presort the array and then iterate through it a second time.
The only reason I can see for pre-sorting would be if you had a set number of groups you wanted, and a set number of objects in each group. Then you can't really know what group to put each object in until the array has been sorted.
But here, we're trying to put objects in groups with similar object, so the algorithm is simple:
Grab an object. See if it belongs in an existing group. If not, create a new group for this object. Move to the next object.
And for any downvoters... I can't really provide example code for a more complex example than the existing sample code in this answer unless the original question is made more clear.
Sure. You just have to write code for it.
First, you use the NSArray method sortedArrayUsingDescriptor: to get an array that is sorted by MedicineAlarmTime, so array elements that you might want together will actually be together. Then you iterate through the array, comparing the MedicineAlarmTime to check if two array elements are "similar" enough for you, and create arrays with those groups, using the NSArray method subArrayWithRange:

Add data from an array using its value for key to another Array

Hi i have two Arrays one being Parsed Data that has multiple entries at each cell (FolderName & ID) i want this data to be saved into another array like it is stored in the first array
FilteredData = [[NSMutableArray alloc]initWithArray:[ParsedData ValueForKey:#"FolderName"]];
SearchData = [[NSMutableArray alloc]initWithArray:FilteredData];
This is what i have been trying, The data Containing a dictionary at each entry is ParsedData, And the Array in which i have to copy these items is SearchData.
The Array (Parsed Data) Containing the dictionary looks like this
PARSED DATA (
{
CreatedBy = 1;
FolderName = Posteingang;
ID = 13000;
ParentID = 0;
},
{
CreatedBy = 1;
FolderName = Freigaben;
ID = 13001;
ParentID = 0;
},
From this Array I need to Get the FolderName And the ID and get them in the SearchData Array
SearchData (
Posteingang;
13000;
Freigaben;
13001;
)
I hope the question is clear now
check this one,
NSMutableArray *searchData = [NSMutableArray new];
for(NSDictionary *dict in ParsedDataArray){//here ParsedDataArray means PARSED DATA array name
NSDictionary *tempDict=[[NSDictionary alloc]initWithObjectsAndKeys:[dict ValueForKey:#"FolderName"],#"FolderName",[dict ValueForKey:#"ID"],#"ID" nil],
[searchData addObject:dict];
}
It seems like you misspelled the method name, it should be:
dictionaryWithObjectsAndKeys:
Notice the "s" after Object.
I want a dictionary inside an array which contains foldername and id
So you can get it using this:
NSMutableArray *searchData = [NSMutableArray new];
for(NSDictionary *dict in parsedDataArray){
NSDictionary *tempDict=#{#"FolderName":dict[#"FolderName"],
#"ID":dict[#"ID"]};
[searchData addObject:tempDict];
}
EDIT:
#[#"key:#"object"] is the new dictionary literal.
If you are using Xcode 4.3 or older need to do as:
NSDictionary *tempDict=#{#"FolderName":dict[#"FolderName"],
#"ID":dict[#"ID"]};
means,
NSDictionary *tempDict=[NSDictionary dictionaryWithObjectsAndKeys:[dict objectForKey:#"FolderName"], #"FolderName",[dict objectForKey:#"ID"],#"ID", nil];

Resources