Objective: compare values stored in Mutable array(which are changing constantly) to the index of a static Array. When the values match I would like to add the object(s) of the static array to a new mutable array.
Example:
Values of MutableArray at present state:
(1,2,3)
(Index) - Values of Static Array:
(0) - "Zero"
(1) - "One"
(2) - "Two"
(3) - "Three"
(4) - "Four"
Take values from initial MutableArray and compare them to the static array index's. Output the values at those index's to a new MutableArray
("One","Two","Three")
The initial array is derived by passing the MutableArrayContents for a search via predicate into this:
NSMutableArray *indexArray = [NSMutableArray array];
for (NSMutableArray* obj in _searchResults)
{
if([_questionsArray containsObject:obj] && ![indexArray containsObject:obj])
[indexArray addObject:#([_questionsArray indexOfObject:obj])];
}
IndexArray is the array of "index's".
I've tried for loops but they are not working correctly, any help would be appreciated.
Thanks!
You can try this:
NSArray *staticArr = #[#"Zero",#"One",#"Two",#"Three",#"Four"];
NSArray *otherArr = #[#1,#2,#3];
NSMutableArray * array = [[NSMutableArray alloc] initWithCapacity:[otherArr count]];
for(int i = 0; i < [staticArr count]; i++) {
for(int j = 0; j < [otherArr count]; j++) {
if([[otherArr objectAtIndex:j] intValue] == i) {
[array insertObject:[staticArr objectAtIndex:i] atIndex:j];
break;
}
}
}
Try this method
NSArray *staticArr = #[#"Zero", #"One", #"Two", #"Three", #"Four"];
NSArray *otherArr = #[#(1), #(2), #(3)];
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:[otherArr count]];
[staticArr enumerateObjectsUsingBlock:^(NSString *string, NSUInteger staticIndex, BOOL *staticStop) {
[otherArr enumerateObjectsUsingBlock:^(NSNumber *number, NSUInteger index, BOOL *stop) {
if (number.integerValue == staticIndex) {
[array insertObject:string atIndex:index];
}
}];
}];
I am typing this on a tab. Please forgive any formatting issues
NSMutableArray *indices; //I am omitting the adding of data, it contains required indices as NSNumber objects
NSArray *staticArr = #[#"One", #"Two", #"Three", #"Four", #"Five"];
NSMutableArray *array = [NSMutableArray new];
for(NSNumber *index in indices) {
NSInteger idx = [index integerValue];
If(idx < staticArr.count)
{
[array addObject:[staticArr objectAtIndex:idx];
}
}
This will be in the order of the elements in indices array and may have repetitions in case there are repetitions in indices array.
This is the most straightforward way, there are many ways to get the subarray using Apple's API
I have an array that contains movie objects. These objects are stored in a movie array. My movie object is below.
Movie.h
NSString * name;
NSString * cat_name;
I want to add my original array to a UITableView with dynamic rows and sections but I'm finding it difficult. I think the best way to do this is by having an array of arrays.
For example, there would be an array that contains all horror movies, an array that contains all fiction etc. All in one array. I think that would allow me to get the desired end product. I'm finding it difficult code it though.
EDIT The content of the array is dynamic, so I will not know how many objects will be in it at launch (it's being parsed from JSON). So I need to dynamically create the right amount of sections etc.
NSMutableDictionary * mainDictionary = [[NSMutableDictionary alloc] init];
Movie * firstHorrorMovie = [[Movie alloc] init];
firstHorrorMovie.name = #"Psycho";
firstHorrorMovie.cat_name = #"Horror";
Movie * secondHorrorMovie = [[Movie alloc] init];
secondHorrorMovie.name = #"Paranormal Activity";
secondHorrorMovie.cat_name = #"Horror";
Movie * comedyMovie = [[Movie alloc] init];
comedyMovie.name = #"The new guy";
comedyMovie.cat_name = #"Comedy";
NSArray * horrorMovies = [NSArray arrayWithObjects:firstHorrorMovie, secondHorrorMovie, nil];
NSArray * comedyMovies = [NSArray arrayWithObjects:comedyMovie, nil];
[mainDictionary setValue:horrorMovies forKey:#"Horror"];
[mainDictionary setValue:comedyMovies forKey:#"Comedy"];
OR (in your case - dynamically)
NSMutableDictionary * anotherMainDictionary = [[NSMutableDictionary alloc] init];
NSArray * array = [NSArray arrayWithObjects:firstHorrorMovie, secondHorrorMovie, comedyMovie, nil];
for (Movie * movie in array) {
NSMutableArray * array = [anotherMainDictionary valueForKey:movie.cat_name];
if (array) {
[array addObject:movie];
[anotherMainDictionary setValue:array forKey:movie.cat_name];
} else {
NSMutableArray * newArray = [NSMutableArray arrayWithObject:movie];
[anotherMainDictionary setValue:newArray forKey:movie.cat_name];
}
}
I have an NSArray of names and ages. Now I am trying to create a new NSDictionary with item 0 holding the first name and first age and item 1 holding the second name and second age from the corresponding NSArray? Is that possible?
In my viewDidLoad:
NSMutableArray *Names = [[NSMutableArray alloc] init];
NSMutableArray *ages = [[NSMutableArray alloc] init];
for(int i = 0; i < 4; i++) {
[Names addObject:[candidates objectAtIndex:i]];
[ages addObject:[studenAge objectAtIndex:i]];
}
But how can I make an NSDictionary from this by order?
Final result
I want to write this NSDictionary into a .plist so it look like this:
Details
{
item 0
{
name:rahul
age:25
}
item 1
{
name:ram
age:26
}
item 2
{
name:aajy
age:20
}
item 4
{
name:raj
age:25
}
}
Dictionaries do not have an order.
Probably you want to add dictionaries to the array:
NSMutableArray *persons=[[NSMutableArray alloc]init];
for(int i=0;i<4;i++)
{
[persons addObject:# { #"name" : candidate[i], #"age" : studenAge[i] }];
}
You can sort this array with the sort-Methods of NSArray, NSMutableArray.
As mentioned by #Amin, dictionaries don't maintain order and since you seem to want an indexed access here is what I suggest as the final structure: an array of dictionaries:
NSMutableArray *details = [NSMutableArray array];
for (int i=0; i<4; i++) {
[details addObject:#{#"name": canditate[i], #"age":studentAge[i]}];
}
This will give you the following structure:
[{name:rahul, age:25}, {name:ram age:26},...]
We have an app that calls a SOAP web service and retrieves a long list of XML, which the app then parses into an NSArray of NSDictionary objects. The NSArray contains a list of Rental Apartment information, each of which is stored into an NSDictionary.
The entire list may contain 10 different types of Apartments (i.e. 2-room, 3-room), and we need to split the NSArray into smaller NSArrays based on Room-Type, which has the key "roomType" in the NSDictionary objects.
Currently our algorithm is
Use [NSArray valueForKeyPath:#"#distinctUnionofObjects.room-type"]
to obtain a list of unique room-type values.
Loop through the list of unique room-type values
For each unique room-type value, use NSPredicate to retrieve matching items from the Original list
Our code is below (renamed for clarity):
NSArray *arrOriginal = ... ...; // Contains the Parsed XML list
NSMutableArray *marrApartmentsByRoomType = [NSMutableArray arrayWithCapacity:10];
NSMutableArray *arrRoomTypes = [arrOriginal valueForKeyPath:#"distinctUnionOfObjects.roomType"];
for(NSString *strRoomType in arrRoomTypes) {
NSPredicate *predicateRoomType = [NSPredicate predicateWithFormat:#"roomType=%#", strRoomType];
NSArray *arrApartmentsThatMatchRoomType = [arrOriginal filteredArrayUsingPredicate:predicateRoomType]; // TAKES A LONG TIME EACH LOOP-ROUND
[marrApartmentsByRoomType addObject:arrApartmentsThatMatchRoomType];
}
However, step 3 is taking a long time as the original list may contain large amount (>100,000) of items. It seems that NSPredicate goes through the entire list for each key value. Is there a more efficient way of splitting a large NSArray into smaller NSArrays, based on NSDictionary keys?
If the order of your splited Arrays is not important, i have a solution for you:
NSArray *arrOriginal;
NSMutableDictionary *grouped = [[NSMutableDictionary alloc] initWithCapacity:arrOriginal.count];
for (NSDictionary *dict in arrOriginal) {
id key = [dict valueForKey:#"roomType"];
NSMutableArray *tmp = [grouped objectForKey:key];
if (tmp == nil) {
tmp = [[NSMutableArray alloc] init];
[grouped setObject:tmp forKey:key];
}
[tmp addObject:dict];
}
NSMutableArray *marrApartmentsByRoomType = [grouped allValues];
This is quite performant
- (NSDictionary *)groupObjectsInArray:(NSArray *)array byKey:(id <NSCopying> (^)(id item))keyForItemBlock
{
NSMutableDictionary *groupedItems = [NSMutableDictionary new];
for (id item in array) {
id <NSCopying> key = keyForItemBlock(item);
NSParameterAssert(key);
NSMutableArray *arrayForKey = groupedItems[key];
if (arrayForKey == nil) {
arrayForKey = [NSMutableArray new];
groupedItems[key] = arrayForKey;
}
[arrayForKey addObject:item];
}
return groupedItems;
}
Improving #Jonathan answer
Converting array to dictionary
Maintaining the same order as it was in original array
//only to a take unique keys. (key order should be maintained)
NSMutableArray *aMutableArray = [[NSMutableArray alloc]init];
NSMutableDictionary *dictFromArray = [NSMutableDictionary dictionary];
for (NSDictionary *eachDict in arrOriginal) {
//Collecting all unique key in order of initial array
NSString *eachKey = [eachDict objectForKey:#"roomType"];
if (![aMutableArray containsObject:eachKey]) {
[aMutableArray addObject:eachKey];
}
NSMutableArray *tmp = [grouped objectForKey:key];
tmp = [dictFromArray objectForKey:eachKey];
if (!tmp) {
tmp = [NSMutableArray array];
[dictFromArray setObject:tmp forKey:eachKey];
}
[tmp addObject:eachDict];
}
//NSLog(#"dictFromArray %#",dictFromArray);
//NSLog(#"Unique Keys :: %#",aMutableArray);
//Converting from dictionary to array again...
self.finalArray = [[NSMutableArray alloc]init];
for (NSString *uniqueKey in aMutableArray) {
NSDictionary *aUniqueKeyDict = #{#"groupKey":uniqueKey,#"featureValues":[dictFromArray objectForKey:uniqueKey]};
[self.finalArray addObject:aUniqueKeyDict];
}
Hope, It will help when client wants final array in same order as input array.
I am new to iOS and want to create an NSArray like this which contains an NSDictionary.
[
{
Image: 1, 2,3
Title: 1,2,3
Subtitle:1,2,3
}
]
I have tried this.
NSArray *obj-image=#[#"Test.png",#"Test.png",#"Test.png"];
NSArray *obj-title=#[#"Test",#"Test",#"Test"];
NSArray *obj-subtitle=#[#"Test",#"Test",#"Test"];
NSDictionary * obj_dictionary ={ image : obj_image, title:obj_title, subtitle:obj_subtitle}
NSArray * obj_array= [obj_dictionarry];
But not working and how to access them.
First of all, you initialization of Arrays and Dictionaries is wrong. You cannot use "-" in the names, period.
Second, you need to allocate and then initialize the objects. This is how you do that with arrays:
NSArray *images = [NSArray arrayWithObjects: #"TestImage",#"TestImage",#"TestImage",nil];
NSArray *titles = [NSArray arrayWithObjects: #"TestTitle",#"TestTitle",#"TestTitle",nil];
NSArray *subtitles = [NSArray arrayWithObjects: #"TestSubTitle",#"TestSubTitle",#"TestSubTitle",nil];
Then you need Mutable dictionary and mutable arrays to work with the data (mutable means you can change the values inside, add or remove objects etc.)
This is the most basic example of what you are trying to achieve:
NSArray *images = [NSArray arrayWithObjects: #"TestImage",#"TestImage",#"TestImage",nil];
NSArray *titles = [NSArray arrayWithObjects: #"TestTitle",#"TestTitle",#"TestTitle",nil];
NSArray *subtitles = [NSArray arrayWithObjects: #"TestSubTitle",#"TestSubTitle",#"TestSubTitle",nil];
NSMutableArray *objectsMutable = [[NSMutableArray alloc] init];
for (NSString *string in images) {
NSMutableDictionary *dictMutable = [[NSMutableDictionary alloc] init];
[dictMutable setObject:string forKey:#"image"];
//determining the index of the image
NSInteger stringIndex = [images indexOfObject:string];
[dictMutable setObject:[titles objectAtIndex:stringIndex] forKey:#"title"];
[dictMutable setObject:[subtitles objectAtIndex:stringIndex] forKey:#"subtitle"];
NSDictionary *dict = [[NSDictionary alloc] init];
dict = dictMutable;
[objectsMutable addObject:dict];
}
NSArray *objects = objectsMutable;
NSLog(#"%#", objects);
Hope this helps.
As you can see, I'm going through the images array, capturing the index of each one, an then just apply values of other arrays from the same index into a mutable dictionary.
All I do after that is just make a regular dictionary and array to put the data inside. This is ho the Log will look:
(
{
image = TestImage;
subtitle = TestSubTitle;
title = TestTitle;
},
{
image = TestImage;
subtitle = TestSubTitle;
title = TestTitle;
},
{
image = TestImage;
subtitle = TestSubTitle;
title = TestTitle;
}
)
You have an array with three objects inside, each with their own image, title and subtitle.
Here is code :
NSMutableArray *array = [[NSMutableArray alloc] init];
NSMutableDictionary *mdict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:#"object1",#"key1",#"object2",#"key2",nil];
[array addObject:mDict];
so now if u need to access dictionary from array then :
NSMutableDictionary *mDict1 = [array objectatindex:0];
NSLog(#"%#",[mDict1 valueForkey:#"key1"];
--> print object 1.
This is the way to store array of dictionaries:
NSDictionary *dic=#{#"kishore":#"hai"};
NSMutableArray *arr=[[NSMutableArray alloc]init];
[arr addobject:dic];
this is the way to get those values:
[arr objectforkeyValue #"kishore"];
NSMutableArray *dictArray = [[NSMutableArray alloc] init]; // created and initiated mutable array
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; // created and initiated mutable Dictionary
[dict setObject:#"object1" forKey:#"1"]; // added a key pair in dictionary (you can set multiple objects)
[dictArray addObject:dict]; // added dictionary to array (you can add multiple dictionary to array )
NSLog(#"dictionary inside an array : %#",dictArray[0][#"1"]); // access dictionary from array
You can try something like this
[NSArray arrayWithObjects:#{#"Image":#[#1,#2,#3]},#{#"Title":#[#1,#2,#3]},#{#"SubTitle":#[#1,#2,#3]}, nil];
You can easily create objects of array and access them back using following way.
NSArray *objimage=#[#"Test1.png",#"Test2.png",#"Test3.png"];
NSArray *objtitle=#[#"Test1",#"Test2",#"Test3"];
NSArray *objsubtitle=#[#"Test1",#"Test2",#"Test3"];
NSDictionary *obj_dictionary = #{#"image":objimage,#"Title":objtitle, #"subtitle":objsubtitle};
NSArray * obj_array= [[NSArray alloc] initWithObjects:obj_dictionary, nil]; // Create Array of nested objects
if([obj_array count] > 0) {
NSArray * imageArray = obj_array[0][#"image"]; // Access the nested objects in Array.
NSLog(#"%#", imageArray[0]);
}
first of all u need to declare correct variable name
NSArray *objImage=#[#"Test.png",#"Test.png",#"Test.png"];
NSArray *objTitle=#[#"Test",#"Test",#"Test"];
NSArray *objSubtitle=#[#"Test",#"Test",#"Test"];
at this point all u are created all the array, and u need to create dictionary like below
NSDictionary *obj_dictionary = #{#"image":objImage,#"title":objTitle, #"subtitle":objSubtitle};
// NSArray * obj_array = obj_dictionary[#"image"];
NSArray * obj_array = #[obj_dictionary]; //u can crate array of dictionary like this
in above obj_dictionary will contains all the array like below,
Title = (
Test,
Test,
Test
);
image = (
"Test.png",
"Test.png",
"Test.png"
);
subtitle = (
Test,
Test,
Test
);
and u can access the object in the dictionary like below using a key for example
NSArray * obj_array_images = obj_dictionary[#"image"];
gives an array of images that is associated with key image, similarly u can access other array like this by providing different keys associated with the dictionary obj_dictionary for example
NSArray * obj_array_titles = obj_dictionary[#"title"];
NSArray * obj_array_subtitles = obj_dictionary[#"subtitle"];
edit
NSArray *objImage=#[#"Test.png",#"Test.png",#"Test.png"];
NSArray *objTitle=#[#"Test",#"Test",#"Test"];
NSArray *objSubtitle=#[#"Test",#"Test",#"Test"];
NSDictionary *obj_dictionary = #{#"image":objImage,#"title":objTitle, #"subtitle":objSubtitle};
// NSArray * obj_array = obj_dictionary[#"image"];
NSArray * obj_array = #[obj_dictionary]; //u can crate array of dictionary like this