NSDictionary flatten hierarchy - iphone

I've got an NSDictionary object like this:
dictionary: {
data = {
"access_token" = "xxx";
"expires_in" = 00;
"refresh_token" = "yyy";
"token_type" = bearer;
};
}
How can I flatten it so that I remove the 'data' object? Is there a quick way to do that?
So the output should look like this:
dictionary: {
"access_token" = "xxx";
"expires_in" = 00;
"refresh_token" = "yyy";
"token_type" = bearer;
};

NSDictionary *dataDict = [mainDict objectForKey:#"data"];

flat dict in your example:
//grab data
NSDictionary *data = [yourDict objectForKey:#"data"];
assert(data != nil);
NSDictionary *flatDict = data; //OR data.copy // OR [NSDictionary dictionaryWithDictionary:data];

It doesn't look like "data" is an NSDictionary. Try
id what = [dict objectForKey : #"data"];
NSLog(#"%#", [what class]);
What does it say?

using recursive function, the only problem with this method is it will replace the old data if key happened to be the same in the nested dictionary
- (NSDictionary *)flattedDictionary{
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for (NSString *key in self.allKeys) {
id object = [self objectForKey:key];
if (![object isKindOfClass:[NSDictionary class]] && !isNull(object)) {
[dict setObject:object
forKey:key];
} else if ([object isKindOfClass:[NSDictionary class]]){
[dict addEntriesFromDictionary:[object flattedDictionary]];
}
}
return [NSDictionary dictionaryWithDictionary:dict];
}

Related

How to swap `NSMutableDictionary` key and values in place?

I have a NSMutableDictionary and I want to swap values & keys. i.e, after swapping values becomes keys and its corresponding keys with become values All keys and values are unique. Looking for an in place solution because size is very big . Also, the keys and values are NSString objects
NSMutableDictionary *d = [NSMutableDictionary dictionaryWithDictionary:#{
#"key1" : #"value1",
#"key2" : #"value2"}];
for (NSString *key in [d allKeys]) {
d[d[key]] = key;
[d removeObjectForKey:key];
}
NSLog(#"%#", d); // => { value1 : key1,
// value2 : key2 }
Assumptions
unique values (as they will become keys)
values conform to NSCopying (same as above)
no value is equal to any key (otherwise colliding names will be lost in the process)
Here is another way to invert dictionary. The simplest for me.
NSArray *keys = dictionary.allKeys;
NSArray *values = [dictionary objectsForKeys:keys notFoundMarker:[NSNull null]];
[dictionary removeAllObjects]; // In case of huge data sets release the contents.
NSDictionary *invertedDictionary = [NSDictionary dictionaryWithObjects:keys forKeys:values];
[dictionary setDictionary:invertedDictionary]; // In case you want to use the original dictionary.
EDIT: I had written a few lines of codes to get the OP started into the task of creating his own algorithm. The answer was not well received so I have crafted a full implementation of an algorithm that does what he asks, and goes one step further.
Advantages:
Makes no assumptions regarding the contents of the dictionary, for example, the values need not conform to the 'NSCopying' protocol
Transverses the whole hierarchy of a collection, swapping all the keys
It's fast since it uses recursion and fast enumeration
Does not alter the contents of the original dictionary, it creates a brand new one
Code has been implemented through categories to both collections:
#interface NSDictionary (Swapping)
- (NSDictionary *)dictionaryBySwappingKeyWithValue;
#end
#interface NSDictionary (Swapping)
- (NSDictionary *)dictionaryBySwappingKeyWithValue
{
NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithCapacity:self.count];
[self enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
id newKey = nil;
if ([value isKindOfClass:[NSDictionary class]]) {
newKey = [value dictionaryBySwappingKeyWithValue];
} else if ([value isKindOfClass:[NSArray class]]) {
newKey = [value arrayBySwappingKeyWithValue];
} else {
newKey = value;
}
if (![newKey conformsToProtocol:#protocol(NSCopying)]) {
newKey = [NSValue valueWithNonretainedObject:newKey];
}
mutableDictionary[newKey] = key;
}];
return [NSDictionary dictionaryWithDictionary:mutableDictionary];
}
#end
and...
#interface NSArray (Swapping)
- (NSArray *)arrayBySwappingKeyWithValue;
#end
#implementation NSArray (Swapping)
- (NSArray *)arrayBySwappingKeyWithValue
{
NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:self.count];
[self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if ([obj isKindOfClass:[NSDictionary class]]) {
NSDictionary *newDict = [obj dictionaryBySwappingKeyWithValue];
mutableArray[idx] = newDict;
} else if ([obj isKindOfClass:[NSArray class]]) {
NSArray *newArray = [obj arrayBySwappingKeyWithValue];
mutableArray[idx] = newArray;
} else {
mutableArray[idx] = obj;
}
}];
return [NSArray arrayWithArray:mutableArray];
}
#end
As an example, assume you have a dictionary with the following structure:
UIView *view = [[UIView alloc] init];
NSDictionary *dict = #{#"1" : #"a",
#"2" : #[ #{ #"5" : #"b" } ],
#"3" : #{#"6" : #"c"},
#"7" : view};
NSDictionary *newDict = [dict dictionaryBySwappingKeyWithValue];
Printing the newDict object in the console will give you this output:
(lldb) po mutableDictionary
{
a = 1;
({b = 5;}) = 2;
{c = 6;} = 3;
"<30b50617>" = 7;
}
As you can see, not only have the keys and values been swapped at the first level of the hierarchy, but deep inside each collection.
"<30b50617>" represents the UIView object wrapped inside a NSValue. Since UIView does not comply to the NSCopying protocol, it needs to be handled this way if you want it to be a key in your collection.
Note: Code was done in a couple of minutes. Let me know if I missed something.
for (NSString *key in [myDictionary allKeys]) {
NSString *value = [responseDataDic objectForKey:key];
[myDictionary removeObjectForKey:key];
[myDictionary addObject:key forKey:value];
}
Assumption:
No key = value;
Complexity:
No extra space required. Will loop through once and replace all key value pairs.
NSArray* allKeys = [theDict allKeys];
NSArray* allValues = [theDict allValues];
NSMutableDictionary* newDict = [NSMutableDictionary dictionaryWithObjects:allKeys forKeys:allValues];

Creating an Array of values from an Array of Dictionaries

The question sounds weird but I'm getting an array of dictionaries as parsed result.
Something like this:
parsed content: (
{
"name" = "John";
"lastname" = "Doe";
"foo" = "bar";
}
What would be the suggestion for best way to create an array of values??
Like this?
- (void)flattenDictionary:(NSDictionary *)d intoKeys:(NSMutableArray *)keys andValues:(NSMutableArray *)values {
for (id key in [d allKeys]) {
[keys addObject:key];
[values addObject:[d valueForKey:key]];
}
}
- (void)flattenDictionaries:(NSArray *)arrayOfDictionaries {
NSMutableArray *keys = [NSMutableArray array];
NSMutableArray *values = [NSMutableArray array];
for (NSDictionary *d in arrayOfDictionaries) {
[self flattenDictionary intoKeys:keys andValues:values];
}
NSLog(#"now we have these values %#", values);
NSLog(#"corresponding to these keys %#", keys);
}
You can get the values with:
NSArray *values = dictionary.allValues;
Or, loop through it:
[dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id object, BOOL *stop) {
    NSLog(#"%# = %#", key, object);
}];
To do that loop through them and create an array.

Convert NSMutableArray to NSDictionary in order to use objectForKey?

I have an NSMutableArray that looks like this
{
"#active" = false;
"#name" = NAME1;
},
{
"#active" = false;
"#name" = NAME2;
}
Is there a way to convert this to an NSDictionary and then use objectForKey to get an array of the name objects? How else can I get these objects?
There is a even shorter form then this proposed by Hubert
NSArray *allNames = [array valueForKey:#"name"];
valueForKey: on NSArray returns a new array by sending valueForKey:givenKey to all it elements.
From the docs:
valueForKey:
Returns an array containing the results of invoking
valueForKey: using key on each of the array's objects.
- (id)valueForKey:(NSString *)key
Parameters
key The key to retrieve.
Return Value
The value of the retrieved key.
Discussion
The returned array contains NSNull elements for each object that returns nil.
Example:
NSArray *array = #[#{ #"active": #NO,#"name": #"Alice"},
#{ #"active": #NO,#"name": #"Bob"}];
NSLog(#"%#\n%#", array, [array valueForKey:#"name"]);
result:
(
{
active = 0;
name = Alice;
},
{
active = 0;
name = Bob;
}
)
(
Alice,
Bob
)
If you want to convert NSMutableArray to corresponding NSDictionary, just simply use mutableCopy
NSMutableArray *phone_list; //your Array
NSDictionary *dictionary = [[NSDictionary alloc] init];
dictionary = [phone_list mutableCopy];
This is an Array of Dictionary objects, so to get the values you would:
[[myArray objectAtIndex:0]valueForKey:#"name"]; //Replace index with the index you want and/or the key.
This is example one of the exmple get the emplyee list NSMutableArray and create NSMutableDictionary.......
NSMutableArray *emloyees = [[NSMutableArray alloc]initWithObjects:#"saman",#"Ruchira",#"Rukshan",#"ishan",#"Harsha",#"Ghihan",#"Lakmali",#"Dasuni", nil];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for (NSString *word in emloyees) {
NSString *firstLetter = [[word substringToIndex:1] uppercaseString];
letterList = [dict objectForKey:firstLetter];
if (!letterList) {
letterList = [NSMutableArray array];
[dict setObject:letterList forKey:firstLetter];
}
[letterList addObject:word];
} NSLog(#"dic %#",dict);
yes you can
see this example:
NSDictionary *responseDictionary = [[request responseString] JSONValue];
NSMutableArray *dict = [responseDictionary objectForKey:#"data"];
NSDictionary *entry = [dict objectAtIndex:0];
NSString *num = [entry objectForKey:#"num"];
NSString *name = [entry objectForKey:#"name"];
NSString *score = [entry objectForKey:#"score"];
im sorry if i can't elaborate much because i am also working on something
but i hope that can help you. :)
No, guys.... the problem is that you are stepping on the KeyValue Mechanism in cocoa.
KeyValueCoding specifies that the #count symbol can be used in a keyPath....
myArray.#count
SOOOOOO.... just switch to the ObjectForKey and your ok!
NSMutableDictionary *myDictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:#"theValue", #"#name", nil];
id kvoReturnedObject = [myDictionary valueForKey:#"#name"]; //WON'T WORK, the # symbol is special in the valueForKey
id dictionaryReturnedObject = [myDictionary objectForKey:#"#name"];
NSLog(#"object = %#", dictionaryReturnedObject);

Weird bug while adding a NSDictionary to an NSArray

I got a really weird bug in my app today:
NSMutableDictionary *testLocal = [[NSMutableDictionary alloc] init];
[testLocal setObject:#"Test" forKey:#"title"];
[testLocal setObject:#"test notification" forKey:#"body"];
[testLocal setObject:#"1" forKey:#"repeat"];
[testLocal setObject:#"26.04.2011 - 12:53" forKey:#"start"];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:[saver read]];
[[dict objectForKey:#"content"] addObject:testLocal]; //Crashes here! (SIGABRT)
The method [saver read] returns this:
{
content = (
{
body = "test notification";
repeat = 1;
start = "26.04.2011 - 13.06";
title = Test;
}
);
}
So I don't see the error because the dict I write to is mutable and the key "content" is an array.
Thanks in advance.
mavrick3.
[saver read]:
- (NSDictionary *)read {
return [[NSDictionary alloc] initWithContentsOfFile:[self filePath]];
}
Try checking out what class the object returned by [dict objectForKey:#"content"] is. Then things will be much clearer to you. I suspect it is not returning an NSMutableArray instance but something else, most likely NSArray which doesn't respond to method addObject:
From apple Documentation for objectForKey :
The value associated with aKey, or nil if no value is associated with aKey.
So your code could be like below
if([dict objectForKey:#"content"] != nil && [[dict objectForKey:#"content"] isKindOfClass:[NSMutableArray class]] )
{
[[dict objectForKey:#"content"] addObject:testLocal];
}
else
{
[dict setObject: textLocal forKey: #"content"];
}
Is the array to which you want to add a dictionary mutable?

key values from an NSDictionary formatting with "()"

I'm trying to pull two values from this Dictionary, But the values I'm getting have "()" around them. Any Ideas what is causing this?
Here is the ServerOutput:
{"Rows":[{"userid":"1","location":"beach"}]}
Dictionary after JSON:
{
Rows = (
{
location = beach;
userid = 1;
}
);
}
This is what I'm getting:
location : (
beach
)
user Id : (
1
)
Both the userid and the location key values have the "()". Here is the code. Thanks a lot.
NSString *serverOutput= [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
if(serverOutput > 1){
SBJSON *jsonFF = [[SBJSON new] autorelease];
NSError *error3 = nil;
NSDictionary *useridDict= [jsonFF objectWithString:serverOutput error:&error3];
NSLog(#"useridDict: %#",useridDict);
idreturn = [[useridDict valueForKey:#"Rows"] valueForKey:#"userid"];
locationreturn = [[useridDict valueForKey:#"Rows"] valueForKey:#"location"];
NSLog(#" user Id : %#", idreturn);
NSLog(#" location : %#", locationreturn);
Just to clarify what is going on. When parsing JSON {} gets returned as a dictionary and [] gets retured as an array. So we have useridDict an NSDictionary containing the parsed data.
'useridDict' has one key Rows which returns an NSArray.
NSArray *useridArray = [useridDict objectForKey:#"Rows"];
Our useridArray has one element, an NSDictionary
NSDictionary *dict = [useridArray objectAtIndex:0];
This dict contains the two keys: location and userid
NSString *location = [dict objectForKey:#"location"];
NSInteger userid = [[dict objectForKey:#"userid"] intValue];
You can use like this.
idreturn = [[[useridDict valueForKey:#"Rows"] objectAtIndex:0]valueForKey:#"userid"];
locationreturn = [[[useridDict valueForKey:#"Rows"] objectAtIndex:0] valueForKey:#"location"];