How to sort NSDictionary value in iphone - iphone

I want to sort the Dictionary value following is my dictionary response that have four key value pair like- "artist_id", "artworks_count","first_name","last_name". I want to sort it according to "first_name" how to do. please help me.
2012-03-02 16:10:41.299 Paddle8[4928:207] The currentArtistNameDict is-- >{
"artist_id" = 370;
"artworks_count" = 1;
"first_name" = Gerri;
"last_name" = Davis;
}
2012-03-02 16:10:41.300 Paddle8[4928:207] The currentArtistNameDict is-- >{
"artist_id" = 369;
"artworks_count" = 1;
"first_name" = Stephen;
"last_name" = Cimini;
}
2012-03-02 16:10:41.302 Paddle8[4928:207] The currentArtistNameDict is-- >{
"artist_id" = 367;
"artworks_count" = 1;
"first_name" = Melinda;
"last_name" = Buie;
}
2012-03-02 16:10:41.305 Paddle8[4928:207] The currentArtistNameDict is-- >{
"artist_id" = 358;
"artworks_count" = 7;
"first_name" = Kcho;
"last_name" = "<null>";
}
Any help is highly Appreciated..

NSDictionary objects are by definition unsorted, so you'd be best off iterating through your dictionary and putting the items into an NSMutableArray, and then using the sortUsingDescriptors method to sort the array.
Here's an example that might help:
scores = [NSMutableArray arrayWithArray:[defaults
objectForKey:#"HighScores"]];
[scores addObject:[NSDictionary dictionaryWithObjectsAndKeys:#"Andrew", #"Name", [NSNumber numberWithUnsignedInt:45], #"Score", nil]];
[scores addObject:[NSDictionary dictionaryWithObjectsAndKeys:#"Andrew2", #"Name", [NSNumber numberWithUnsignedInt:55], #"Score", nil]];
[scores sortUsingDescriptors:[NSArray arrayWithObject:[[[NSSortDescriptor alloc] initWithKey:#"Score" ascending:NO] autorelease]]];
(taken from http://www.iphonedevsdk.com/forum/iphone-sdk-development/6146-sort-array-dictionary-objects.html)

Related

Copy from array of dictionary to array of dictionary

I am collecting Ids in an array from an array of Dictionaries like this
NSArray *places= #[
{place_id = #"3dsfdDfGDH";
place_url = #"/Peru/Lambayeque/Chiclayo";
place_name = #"Peru";}
,
{place_id = #"HUHiKcZVU7ItMyQ";
place_url = #"/Peru/La+Libertad/Huanchaco";
place_name = #"Peru";}
,
{place_id = #"7JL1K5FVUbg0vg";
place_url = #"/United+Kingdom/England/Buckley+Hill";
place_name = #"United Kingdom";}
];
NSArray *placeIds= [places valueForKeyPath:place_id];
It is working perfectly but What I want is another Array with place_id as well as place_url but NOT Name.
something Like
I want NSArray *PlaceIdAndURL to have dictionaries like below
#[
{place_id = #"3dsfdDfGDH";
place_url = #"/Peru/Lambayeque/Chiclayo";}
,
{place_id = #"HUHiKcZVU7ItMyQ";
place_url = #"/Peru/La+Libertad/Huanchaco";}
,
{place_id = #"7JL1K5FVUbg0vg";
place_url = #"/United+Kingdom/England/Buckley+Hill";}
];
How can I get without looping whole array just like the one i got first one with ValueForKeyPath above
I don't think it is possible in one liner that won't iterate....but here is the code that will do the job. Actually, you can make this logic into a method and add as your category to NSArray and NSMutableArray...
places_dup will contain the dictionaries you are looking for.
NSArray *places= #[
#{#"place_id" : #"NFxmX.VVU7LtQwQ",
#"place_url" : #"/Peru/Lambayeque/Chiclayo",
#"place_name" : #"dadfasdf"}
,
#{#"place_id" : #"HUHiKcZVU7ItMyQ",
#"place_url" : #"/Peru/La+Libertad/Huanchaco",
#"place_name" : #"dadfasdf"}
,
#{#"place_id" : #"7JL1K5FVUbg0vg",
#"place_url" : #"/United+Kingdom/England/Buckley+Hill",
#"place_name" : #"dadfasdf"}
];
NSMutableArray *places_dup = [#[] mutableCopy];
[places enumerateObjectsUsingBlock:^(id item, NSUInteger idx, BOOL *stop) {
NSDictionary *dictionary = (NSDictionary *) item;
NSMutableDictionary *filteredDictionary = [NSMutableDictionary dictionaryWithDictionary:dictionary];
[filteredDictionary removeObjectForKey:#"place_name"];
[places_dup addObject:filteredDictionary];
}];

Adding Static Dictionary data into my static array

Hi I have prepared static dictionary with data like Like
{ Age = 25, Name = Ajay;}
My requirement is I want to add this dictionary into My Array, I need a format like
({ Age = 25, Name = Ajay;})
My Code:
mainArray = [[NSMutableArray alloc] init];
dictMain = [[NSMutableDictionary alloc] init];
// dictMain = #{ #"Name" : #"Ajay", #"Age" : #"25" };
[dictMain setValue:#"Ajay" forKey:#"Name"];
[dictMain setValue:#"25" forKey:#"Age"];
[self dictMain];
I would do this like so:
NSArray *myArray = #[ #{#"Name": #"Ajay", #"Age": #"25"} ];
This will give you an immutable array with the data you want. Note though, that I would use #25 for your age (which will give you an NSNumber), instead of #"25", which will give you a string.
And if you really need to return a dictionary of an array of a dictionary, then you can do:
NSDictionary *myDict = #{ #[ #{#"Name": #"Ajay", #"Age": #"25"} ] };
Add NSDictionary to NSMutableArray.
NSMutableArray *mainArray = [[NSMutableArray alloc] init];
NSDictionary *dictMain = #{ #"Name" : #"Ajay", #"Age" : #"25" };
[mainArray addObject: dictMain];
Update:
NSDictionary *dictMain = #{ #"Name" : #"Ajay", #"Age" : #"25" };
NSArray *mainArry = #[dictMain];
NSDictionary *dict = #{#"key" : mainArry};

Create a NSMutableArray in xcode?

I need to create a NSMutableArray with dictionaries like the one shown below..Donno how to do it ./
(
{
businessName = "IBM Business Continuity & Recovery Service";
city = "Costa Mesa";
phone = "(714) 668-6900";
state = CA;
street = "600 Anton Blvd";
zip = 92626;
},
{
businessName = "IBM Sanno";
city = Lomita;
phone = "(310) 626-0613";
state = CA;
street = "25835 Appian Way";
zip = 90717;
},
{
businessName = "Ewert's IBM Typewriter Service";
city = "";
phone = "(559) 732-3215";
state = "";
street = "";
zip = "";
},
)
Please guide me
NSMutableDictionary *list = [[NSMutableDictionary alloc] init];
[list setObject:businessName.text forKey:#"businessName"];
[list setObject:city.text forKey:#"city"];
[list setObject:phone.text forKey:#"phone"];
[list setObject:state.text forKey:#"state"];
[list setObject:street.text forKey:#"street"];
[list setObject:zip.text forKey:#"zip"];
NSMutableArray *listArraySignup = [[NSMutableArray alloc] init];
[listArraySignup addObject:list];
If you want a NSMutableArray with dictionaries, you can do something like this
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity: 10];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithCapacity: 10];
[dict setObject: #"IBM Business Continuity & Recovery Service" forKey: #"businessName"];
set other objects like this
[array addObject: dict];
[dict release];
Add the other dictionaries like this in the array and you will be good to go :)
There are many ways to do this.
If you were planning on adding these dictionaries dynamically (roughly speaking):
NSMutableArray *dictionaries = [[NSMutableArray alloc] init];
NSDictionary *exampleDict = [[NSDictionary alloc] initWithObjectsAndKeys:
#"IBM Business Continuity & Recovery Service", #"businessName",
#"Costa Mesa", #"city",
#"(714) 668-6900", #"phone",
#"CA", #"state",
#"600 Anton Blvd", #"street",
#"92626", #"zip", nil];
[dictionaries addObject:exampleDict];
with new Objective-C Literals
NSArray *array = #[
#{
#"businessName" : #"IBM Business Continuity & Recovery Service",
#"city" : #"Costa Mesa",
#"phone" : #"(714) 668-6900",
#"state" : #"CA",
#"street" : #"600 Anton Blvd",
#"zip" : #(92626)
},
#{
#"businessName" : #"IBM Sanno",
#"city" : #"Lomita",
#"phone" : #"(310) 626-0613",
#"state" : #"CA",
#"street" : #"25835 Appian Way",
#"zip" : #(90717)
},
#{
#"businessName" : #"Ewert's IBM Typewriter Service",
#"phone" : #"(559) 732-3215"
}
];
try this one, use NSDictionary

Re-arrange NSArray and NSDictionary entries

I have array with nsdictionary objects, for ex.:
({"someKey" = "title";
"name" = "someName";
},
{"someKey" = "title";
"name" = "anotherName";
}
{"someKey" = "newTitle";
"name" = "someName";
}
)
Please, help me to sort it in this format:
({"someKey" = "title";
"names": (
{"name" = "someName"},
{"name" = "anotherName"}
)
},
{"someKey" = "newTitle";
"names": (
{"name" = "someName"}
)
}
)
Thanks..
As far as i understand from your question you want to pick individual objects into one single dictionary object..
NSArray *yourArray=.... /* array which contains this data: ({"someKey" = "title";
"name" = "someName";
},
{"someKey" = "title";
"name" = "anotherName";
}
)*/
NSMutableDictionary *newDictionary=[[NSMutableDictionary alloc]init];
for(int i=0;i<[yourArray count];i++){
[newDictionary setObject:[yourArray objectAtIndex:i] forKey:#"names"];
}
({"someKey" = "title";
"name" = "someName";
},
{"someKey" = "title";
"name" = "anotherName";
}
)
Assuming above is equivalent to
NSArray *array=[NSArray arrayWithObjects:dictionary1,dictionary2,nil];
then to achieve below result
(
{
"someKey" = "title";
"names": (
{"name" = "someName"},
{"name" = "anotherName"}
)
}
)
We have this :
//Get name array
NSMutableArray *names=[NSMutableArray array];
for(int i=0;i<[array count];i++)
{
NSDictionary *dictionary=[array objectAtIndex:i];
[names addObject:[dictionary valueForKey:#"name"];
}
NSDictionary *newDictionary=[NSDictionary dictionaryWithOjbectsAndKeys:#"someKey",#"title",names,#"names",nil];
//Your final result is an array with one object ( A Dictionary )
NSArray *finalArray=[NSArray arrayWithObjects: newDictionary,nil];
You just need to traverse the current structure and build a new dictionary with the title as the unique key:
NSEnumerator* arrayEnumerator = [myArray objectEnumerator];
NSDictionary* = dictFromArray;
NSMutableArray* titleArray = [[NSMutableArray alloc] init];
NSMutableDictionary* titleDict = [[NSMutableDictionary alloc] init];
while(dictFromArray = [arrayEnumerator nextObject])
{
currentTitle = [dictFromArray objectForKey:#"someKey"];
currentName = [dictFromArray objectForKey:#"name"];
if([titles containsObject:currentTitle)
{
NSMutableDictionary namesArray = [titleDict objectForKey:currentTitle];
[namesArray addObject:currentName];
}
else
{
[titles addObject:currentTitle];
[titleDict addObject:[NSMutableArray arrayWithObject:currentName] forKey:currentTitle];
}
}
This should give you a dictionary that looks like:
{
title =
(
someName,
anotherName
);
newTitle =
(
someName
)
}
To get the exact structure you have above, I think this should work:
NSArray* titleKeys = [titleDict allKeys];
NSEnumerator* keyEnumerator = [titleKeys objectEnumerator];
NSMutableArray* finalArray = [[NSMutableArray alloc] init];
NSString* key;
while (key = [keyEnumerator nextObject])
{
[finalArray addObject: [NSDictionary
dictionaryWithObjects:(key, [dictArray objectForKey:key])
forKeys:(#"someKey", #"names")]];
}

Sorting mutable array by dictionary key

I have already looked through a few answers using the various sorting methods of NSMutableArray, but for some reason they are not working for me.
I am just trying to sort the mutable array which contains dictionaries by the Delay key within each dictionary. However, the "sorted" array is the exact same as the original array.
By the way, it works fine if I create a dummy mutable array and populate it with dictionaries containing numbers, but for some reason it won't sort this mutable array that I am initializing.
What am I doing wrong?
Here's my code:
playlistCalls = [[NSMutableArray alloc] initWithArray:[currentPlaylist objectForKey:#"Tunes"]];
NSLog(#"original %#", playlistCalls);
NSSortDescriptor *delay = [NSSortDescriptor sortDescriptorWithKey:#"Delay" ascending:YES];
[playlistCalls sortUsingDescriptors:[NSArray arrayWithObject:delay]];
NSLog(#"sorted %#", playlistCalls);
Here's the array containing the dictionaries:
2012-06-04 15:48:09.129 MyApp[57043:f503] original (
{
Name = Test Tune;
Delay = 120;
Volume = 100;
},
{
Name = Testes;
Delay = 180;
Volume = 100;
},
{
Name = Testing;
Delay = 60;
Volume = 100;
}
)
2012-06-04 15:48:09.129 MyApp[57043:f503] sorted (
{
Name = Test Tune;
Delay = 120;
Volume = 100;
},
{
Name = Testes;
Delay = 180;
Volume = 100;
},
{
Name = Testing;
Delay = 60;
Volume = 100;
}
)
The code above is fine when I use NSNumbers in my dictionary. That leads me to believe that the Delay value is stored as strings in your dictionary. What you will need to do then is sort by the strings integerValue.
NSSortDescriptor *delay =
[NSSortDescriptor sortDescriptorWithKey:#"Delay.integerValue" ascending:YES];
Please try the following, it worked with me
NSDictionary *dic;
NSMutableArray *arr = [[NSMutableArray alloc] init];
dic = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:120], #"Delay",
[NSNumber numberWithInt:100], #"Volume",
nil];
[arr addObject:dic];
dic = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:160], #"Delay",
[NSNumber numberWithInt:100], #"Volume",
nil];
[arr addObject:dic];
dic = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:100], #"Delay",
[NSNumber numberWithInt:100], #"Volume",
nil];
[arr addObject:dic];
NSSortDescriptor *sortDesc = [[NSSortDescriptor alloc] initWithKey:#"Delay" ascending:YES];
[arr sortUsingDescriptors:[NSArray arrayWithObject:sortDesc]];