How to implement "group by values" in NSMutableArray? - iphone

I am using NSMutableArray. I want to fetch the values by date like we do in SQL group by "log_date".
logMuArray (
{
"log_currenttime" = "4:30pm";
"log_date" = "11.12.2011";
"log_duration" = "1:30";
},
{
"log_currenttime" = "4:33pm";
"log_date" = "11.12.2011";
"log_duration" = "2:21";
},
{
"log_currenttime" = "4:40pm";
"log_date" = "11.12.2011";
"log_duration" = "5:30";
},
{
"log_currenttime" = "7:30pm";
"log_date" = "12.12.2011";
"log_duration" = "1:30";
},
{
"log_currenttime" = "7:33pm";
"log_date" = "12.12.2011";
"log_duration" = "2:21";
},
{
"log_currenttime" = "7:40pm";
"log_date" = "12.12.2011";
"log_duration" = "5:30";
},
{
"log_currenttime" = "07:16pm";
"log_date" = "19.12.2011";
"log_duration" = "0:07";
},
{
"log_currenttime" = "7:31pm";
"log_date" = "19.12.2011";
"log_duration" = "0:04";
},
{
"log_currenttime" = "7:33pm";
"log_date" = "19.12.2011";
"log_duration" = "0:03";
},
{
"log_currenttime" = "7:33pm";
"log_date" = "19.12.2011";
"log_duration" = "0:06";
},
{
"log_currenttime" = "7:35pm";
"log_date" = "19.12.2011";
"log_duration" = "0:05";
}
)
**So, I have just performed....
NSLog(#"logMuArray %#",[logMuArray valueForKey:#"log_date"]);
But I want to fetch the UNIQUE dates only.**
I have thought about NSPredicate or Mutable Set etc...
logMuArray (
"11.12.2011",
"11.12.2011",
"11.12.2011",
"12.12.2011",
"12.12.2011",
"12.12.2011",
"19.12.2011",
"19.12.2011",
"19.12.2011",
"19.12.2011",
"19.12.2011"
)
Thanks in advance.....
EDIT:
I have also heared about "#distinctUnionOfObjects"
......

Shanti's answer is close. You want to use the Key-Value Coding collection operator #distinctUnionOfObjects. Place the operator immediately preceding the key which you want it to affect, as if it is a part of the key path you are accessing:
[logMuArray valueForKeyPath:#"#distinctUnionOfObjects.log_date"]
Notice the use of valueForKeyPath:, not valueForKey: The former is a method in the Key-Value Coding protocol, and allows accessing arbitrary depth of attributes. The key path is an NSString made up of dot-separated keys. The result of each key lookup is used in turn to access the next key (starting with the original receiver); by default, valueForKey: is simply called at each step.

You should use NSSet for UNIQUE items like :
NSSet *filteredData = [NSSet setWithArray:[logMuArray valueForKey:#"log_date"]];

You can use KVC for this.
[logMuArray valueForKey:#"#distinctUnionOfArrays.log_date"]
edit: Editing this wrt Josh's Response
[logMuArray valueForKeyPath:#"#distinctUnionOfArrays.log_date"]

Try this logic might help you
-(NSMutableArray *) makeUnique :(NSMutableArray *) array {
int i;
int count = [array count];
for (i =0; i< count ; i++) {
NSRange range = NSMakeRange (i+1, count);
[array removeObject:[array objectAtIndex:i] inRange:range];
}
return array;
}

You can incorporate a set
Here is some example code
NSMutableArray * mArray = [NSMutableArray array];
NSDictionary *d1 = [NSDictionary dictionaryWithObjectsAndKeys:#"foo",#"bar",#"bar",#"oooo",nil];
NSDictionary *d2 = [NSDictionary dictionaryWithObjectsAndKeys:#"boo",#"bar",#"bar",#"oooo",nil];
NSDictionary *d3 = [NSDictionary dictionaryWithObjectsAndKeys:#"boo",#"bar",#"bar",#"oooo",nil];
[mArray addObject:d1];
[mArray addObject:d2];
[mArray addObject:d3];
NSLog(#"the array\n%#", mArray);
NSLog(#"just bar %#", [mArray valueForKey:#"bar"]);
//get unique values
NSSet * set = [NSSet setWithArray:[mArray valueForKey:#"bar"]];
NSLog(#"unique just bar %#", [set allObjects]);
and here is the output
2011-12-20 01:50:59.034 TestEnvironment[32401:207] the array
(
{
bar = foo;
oooo = bar;
},
{
bar = boo;
oooo = bar;
},
{
bar = boo;
oooo = bar;
}
)
2011-12-20 01:50:59.036 TestEnvironment[32401:207] just bar (
foo,
boo,
boo
)
2011-12-20 01:50:59.038 TestEnvironment[32401:207] unique just bar (
foo,
boo
)

Related

Filtering an NSDictionary within a dictionary with particular text

I am getting a web service repsonse that is an array of dictionary. Each dictionary has objects whose values itself is another dictionary.I need to implement the search within this response,like if i enter "technology" and go for search, I should get those dictionary from the array that has "technology anywhere within that dictionary", Is there a solution to sort out
{
key1 = {
0 = {
"id" = 608;
"b" = "Apple-Iphone";
};
1 = {
"id" = 609;
"b" = "Iphone";
};
2 = {
"id" = 610;
"b" = "Show Text";
};
};
key2 = "Technology resources";
"key3" = {
0 = {
"id" = 1608;
"b" = "I love reading";
};
1 = {
"id" = 1609;
"b" = "I prefer iphone to others";
};
2 = {
"id" = 1610;
"b" = "Mobile technology is great.I am happy to a be developer";
};
};
"key4" = "Mobile technology is the fun";
}
This is First Method
NSMutableDictionary *dict;
NSArray *allKeys = [dict allKeys];
for (NSString *key in allKeys)
{
NSDictionary *innerDict = [dict objectForKey:key];
NSArray *allInnerKeys = [innerDict allKeys];
for (NSString *innerKey in allInnerKeys)
{
NSDictionary *mostInnerDict = [dict objectForKey:innerKey];
NSString *b = [mostInnerDict objectForKey:b];
NSString *search = #"Technology";
NSString *sub = [b substringFromIndex:NSMaxRange([b rangeOfString:search])];
if(sub)
{
// ADD mostInnerDict Object to your Results Array
}
}
}
Or You can Try The Simpler Method
Get Response in NSDATA
Covert NSDATA To NSString
and search in NSSTRING for Substring

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")]];
}

How to get values from unknown key in NSDictionary iphone?

I have one more big problem while parse the values from Webservice response. I dont know the key for the values in the webservice response. For example,
class = (
{
"ObjectiveC" =
(
{
"brief_desc" = "ObjectiveC";
date = "2008-02-27";
"event_status" = Attended;
},
{
"brief_desc" = "ObjectiveC";
date = "2008-03-05";
"event_status" = Attended;
},
{
"brief_desc" = "ObjectiveC";
date = "2008-03-12";
"event_status" = Missed;
},
);
},
{
"Java" = (
{
"brief_desc" = "Java";
date = "2008-02-27";
"event_status" = Attended;
},
{
"brief_desc" = "Java";
date = "2008-03-05";
"event_status" = Attended;
},
{
"brief_desc" = "Java";
date = "2008-03-12";
"event_status" = Missed;
},
);
}
);
In this response even we dont know the keys "ObjectiveC" and "Java". The keys("ObjectiveC and Java") should be change in every response retured. How to get values of key (Unknown key)? How can i parse this response and get the values?
I would enumerate through the keys to get the value. Here is an example of enumeration in objective-c.
NSEnumerator *enumerator = [myDictionary keyEnumerator];
id key;
while ((key = [enumerator nextObject])) {
//assuming value will be string
NSString *valueForKey = [myDictionary valueForKey:key];
//assuming value is another dictionary
NSDictionary *subDictionary = [myDictionary objectForKey:key];
}
And if you don't know the keys of the sub dictionaries, you can enumerate through those as well.
NSDictionary has - (NSArray *)allKeys and - (NSArray *)allValues. One of those might help
NSDictionary * lessonDict = [[NSDictionary alloc] initWithObjectsAndKeys:#"Key", #"Value", #"Key 2", #"Value 2", nil];
NSArray *values = [lessonDict allValues];
NSArray *keys = [lessonDict allKeys];
NSLog(#"Keys: %#",keys);
NSLog(#"Values: %#",values);

How to store values of JSON in ARRAY/ String

I have the following JSON value:
-(
{ Key = IsEmail;
Value = 1; },
{ Key = TrackingInterval;
Value = 20; },
{ Key = IsBackup;
Value = 1; },
{ Key = WipeOnRestore;
Value = 1; }
)
How might I go about parsing this object into an array or string? - i.e. eack key values to be stored in an array and each Value to be stored in another array.
Please help me out with this.
Thanks :)
This approach uses the json-framework.
I've shortened your example:
NSString *jsonString = #"[{\"Key\":\"IsEmail\",\"Value\":\"1\"},{\"Key\":\"TrackingInterval\",\"Value\":\"20\"},{\"Key\":\"IsBackup\",\"Value\":\"1\"}]";
NSMutableArray *keys = [NSMutableArray array];
NSMutableArray *values = [NSMutableArray array];
NSArray *json = [jsonString JSONValue];
for (NSDictionary *pair in json) {
[keys addObject:[pair objectForKey:#"Key"]];
[values addObject:[pair objectForKey:#"Value"]];
}
NSLog(#"%#", keys);
NSLog(#"%#", values);
Output:
2011-05-18 14:23:55.698 [36736:207] (
IsEmail,
TrackingInterval,
IsBackup
)
2011-05-18 14:23:55.700 [36736:207] (
1,
20,
1
)
Refere
http://www.xprogress.com/post-44-how-to-parse-json-files-on-iphone-in-objective-c-into-nsarray-and-nsdictionary/
http://mobileorchard.com/tutorial-json-over-http-on-the-iphone/
http://mobile.tutsplus.com/tutorials/iphone/iphone-json-twitter-api/
http://blog.zachwaugh.com/post/309924609/how-to-use-json-in-cocoaobjective-c
Your data is not vald json, You may want to structure it more like this:
var theObj = { IsEmail: 1, TrackingInterval: 20, IsBackup: 1, WipeOnRestore: 1 };
Then you could populate your key and value arrays something like this:
var keys = new Array();
var values = new Array();
for (prop in theObj) {
keys.push(prop);
values.push(theObj[prop]);
}
if the JSON is in below format,
responseString=[ {
Key = IsEmail;
Value = 1;
},
{
Key = TrackingInterval;
Value = 20;
},
{
Key = IsBackup;
Value = 1;
},
{
Key = WipeOnRestore;
Value = 1;
}]
then,
NSArray *resultArray=[responseSrting JSONValue];
NSMuatbleArray *keyArray=[[NSMutableArray alloc] init];
NSMutableArray *valueArray=[[NSMutableArray alloc] init];
for(NSDictionary *dict in resultsArray){
[keyArray addObject:[dict objectForKey:#"Key"]];
[valueArray addObject:[dict objectForKey:#"Value"]];
}
then, all your keys are stored in keyArray and all your values are stored in valueArray

Loop through NSDictionary to create separate NSArrays

I have a large NSDictionary that I need to loop through and create separate NSArrays. Here are the contents:
(
{
id = {
text = "";
};
sub = {
text = " , ";
};
text = "";
"thumb_url" = {
text = "";
};
title = {
text = "2010-2011";
};
type = {
text = "title";
};
},
{
id = {
text = "76773";
};
sub = {
text = "December 13, 2010";
};
text = "";
"thumb_url" = {
text = "http://www.puc.edu/__data/assets/image/0004/76774/varieties/thumb.jpg";
};
title = {
text = "College Days - Fall 2010";
};
type = {
text = "gallery";
};
},
{
id = {
text = "";
};
sub = {
text = "";
};
text = "";
"thumb_url" = {
text = "";
};
title = {
text = "2009-2010";
};
type = {
text = "title";
};
},
{
id = {
text = "76302";
};
sub = {
text = "December 3, 2010";
};
text = "";
"thumb_url" = {
text = "http://www.puc.edu/__data/assets/image/0019/76303/varieties/thumb.jpg";
};
title = {
text = "Christmas Colloquy";
};
type = {
text = "gallery";
};
}
)
Each section has a type key, which I need to check. When it finds the title key, I need to add those to an array. Then the next sections that would use the gallery key needs to be in its own array until it finds another title key. Then the gallery keys after that into their own array.
I am using a UITableView section titles and content. So, the NSDictionary above should have one NSArray *titles; array, and two other arrays each containing the galleries that came after the title.
I have tried using a for loop but I just can't seem to get it right. Any ideas would be appreciated.
It's somewhat unclear by your log, but I'm guessing your NSDictionary has values of NSDictionary? If so:
NSMutableArray *titles = [NSMutableArray array];
// etc.
for (id key in sourceDictionary) {
NSDictionary *subDictionary = [sourceDictionary objectForKey:key];
if ([subDictionary objectForKey:#"type"] == #"title")
[titles addObject:[subDictionary objectForKey:#"title"]];
// etc.
}
Your question is a bit unclear... but this is how you would properly loop through an NSDictionary.
EDIT:
NSMutableDictionary *galleries = [NSMutableDictionary dictionary];
NSString *currentTitle;
for (id key in sourceDictionary) {
NSDictionary *subDictionary = [sourceDictionary objectForKey:key];
NSString *type = [subDictionary objectForKey:#"type"];
if (type == #"title") {
currentTitle = [subDictionary objectForKey:#"title"];
if ([galleries objectForKey:currentTitle] == nil)
[galleries setObject:[NSMutableArray array] forKey:currentTitle];
} else if (type == #"gallery" && currentTitle != nil)
[[galleries objectForKey:currentTitle] addObject:subDictionary];
}
After this loop, galleries will contain keys of type NSString (with values of the titles), and corresponding objects of type NSArray (with values of the gallery NSDictionarys). Hopefully this is what you were going for.
NSString *key;
for(key in someDictionary){
NSLog(#"Key: %#, Value %#", key, [someDictionary objectForKey: key]);
}
Modern Objective-C syntax:
NSMutableArray *things = [NSMutableArray array];
NSMutableArray *stuff = [NSMutableArray array];
NSMutableArray *bits = [NSMutableArray array];
[dictionaries enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[things addObject:[obj valueForKeyPath:#"thing"]];
[stuff addObject:[obj valueForKeyPath:#"enclosing_object.stuff"]];
[bits addObject:[obj valueForKeyPath:#"bits"]];
}];