Insert NSArray into an NSDictionary - iphone

If I have a NSArray, can I put this into a NSDictionary?
If so, how can I do this?

An NSDictionary can use any objects as values, and any objects that conforms to NSCopyingas keys. So in your case:
NSArray * myArray = [NSArray arrayWithObjects:#"a", #"b", #"c"];
NSDictionary * dict = [NSDictionary dictionaryWithObject:myArray forKey:#"threeLetters"];
NSMutableDictionary * mutableDict = [NSMutableDictionary dictionaryWithCapacity:10];
[mutableDict setObject:myArray forKey:#"threeLetters"];

If you start with myArray:
NSArray *myArray = [NSArray arrayWithObjects:...];
If you want a mutable dictionary:
NSMutableDictionary *myMutableDictionary = [NSMutableDictionary dictionary];
[myMutableDictionary setObject:myArray forKey:#"myArray"];
If you just want a dictionary:
NSDictionary *myDictionary = [NSDictionary dictionaryWithObject:myArray forKey:#"myArray"];

Maybe you should read this:
http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/Collections/Collections.html#//apple_ref/doc/uid/10000034i

Related

Getting strange error in NSDictionary

I am getting strange exception when calling the NSDictionary in the following example:
NSInteger userId = 1;
NSDictionary *postData = [NSDictionary dictionaryWithObjectsAndKeys:
#"3", #"a",
#"0", #"b",
userId, #"c",
nil];
Can someone see what's the problem above?
NSDictionary, as most collections, just accepts real Obj-C objects (id type), but you are passing a NSInteger which is a normal C typedef.
Try with NSNumber userId = [NSNumber numberWithInt:1];

Using a nested NSMutableDictionary

simple question, I need to structure data in the following format:
UserID:
1 {
Name = Bob
Surname = Hope
}
2 {
...
I can used an NSMutableDictionary to add a single layer with keys, but I am unable to create a child associate with a certain key.
I have tried creating a mutable dictionary and assigning that to a key:
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
NSArray *keys = [[NSArray alloc] initWithObjects:#"Name", #"Surname", nil];
NSArray *details = [[NSArray alloc] initWithObjects:#"Bob",#"Hope", nil];
NSDictionary *person = [[NSMutableDictionary alloc] initWithObjects:details forKeys:keys];
[dic setValue:#"1" forKey:#"id"];
[[dic objectForKey:#"id"] setDictionary: person];
I think it is better to use an array of dictionaries, each dictionary representing a user.
NSMutableArray *users= [[NSMutableArray alloc] init];
NSArray *keys = [[NSArray alloc] initWithObjects:#"Name", #"Surname", nil];
NSArray *details = [[NSArray alloc] initWithObjects:#"Bob",#"Hope", nil];
NSDictionary *person = [[NSMutableDictionary alloc] initWithObjects:details forKeys:keys];
[users addObject:person];
u can also set the objects for dictionary in this way
[dic setObject:person forKey:#"id"];

returning 8 closest cgfloat from a table lookup based on a cgfloat

I am trying to create this method. Let's call this
-(NSMutableArray*) getEightClosestSwatchesFor:(CGFloat)hue
{
NSString *myFile = [[NSBundle mainBundle] pathForResource:#"festival101" ofType:#"plist"];
NSMutableArray* myArray = [NSArray arrayWithContentsOfFile:myFile];
for (NSDictionary *dict in myArray)
{
NSLog(#"[plistData valueForKey:aKey] string] is %f", [[dict valueForKey:#"hue"] floatValue]) ;
}
return myArray;
}
pretty much, I am passing a cgfloat to this method which then needs to check a plist file which have hue key for 100 elements. I need to compare my hue with all of the hues and get 8 most closest hue and finally wrap these into an array and return this.
What would be most efficient way of doing this? Thanks in advance.
Here's my method if anyone is interested. Feel free to comment on it.
-(NSArray*)eightClosestSwatchesForHue:(CGFloat)hue
{
NSMutableArray *updatedArray = [[NSMutableArray alloc] initWithCapacity:100];
NSString *myFile = [[NSBundle mainBundle] pathForResource:#"festival101" ofType:#"plist"];
NSMutableArray* myArray = [NSArray arrayWithContentsOfFile:myFile];
for (NSDictionary *dict in myArray)
{
CGFloat differenceHue = fabs(hue - [[dict valueForKey:#"hue"] floatValue]);
//create a KVA for the differenceHue here and then add it to the dictionary and add this dictionary to the array.
NSDictionary* tempDict = [NSDictionary dictionaryWithObjectsAndKeys:
[dict valueForKey:#"id"], #"id",
[NSNumber numberWithFloat:differenceHue], #"differenceHue",
[dict valueForKey:#"color"], #"color",
nil];
[updatedArray addObject:tempDict];
}
//now we have an array of dictioneries with values we want. we need to sort this from little to big now.
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:#"differenceHue" ascending:YES];
[updatedArray sortUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
[descriptor release];
//now get the first 8 elements and get rid of the remaining.
NSArray *finalArray = [updatedArray subarrayWithRange:NSMakeRange(0,8)];
[updatedArray release];
return finalArray;
}

iPhone: how to NSArray content to NSDictionary

I want to add content of NSArray's to NSDictionary r NSMultDictionary.
I have NSDictionary(empty), and I have NSArray with content and I have to store NSArray content in NSDictionary.
How can I do this?
You can add content of NSArray to NSDictionary by using following code.
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
for(int i=0; i<[Array count]; i++){
[dic setObject:[Array objectAtIndex:i] forKey:[NSString stringWithFormat:#"%d",i]];
}
The dic is the dictionary, you can use that.
Or else you can add whole array as one object in the dictionary as
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
[dic setObject:Array forKey:#"array"];
#Nandakishore suppose you have an array eg:-myArray
NSDictionary *A = [NSDictionary dictionaryWithObject:myArray forKey:#"Key"];
Now this dictionary object(A) has all the content of the myArray......now do what u wanna do with your dictionary
I hope this may help you!

How can we store into an NSDictionary? What is the difference between NSDictionary and NSMutableDictionary?

I am developing an application in which I want to use an NSDictionary. Can anyone please send me a sample code explaining the procedure how to use an NSDictionary to store Data with a perfect example?
The NSDictionary and NSMutableDictionary docs are probably your best bet. They even have some great examples on how to do various things, like...
...create an NSDictionary
NSArray *keys = [NSArray arrayWithObjects:#"key1", #"key2", nil];
NSArray *objects = [NSArray arrayWithObjects:#"value1", #"value2", nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects
forKeys:keys];
...iterate over it
for (id key in dictionary) {
NSLog(#"key: %#, value: %#", key, [dictionary objectForKey:key]);
}
...make it mutable
NSMutableDictionary *mutableDict = [dictionary mutableCopy];
Note: historic version before 2010: [[dictionary mutableCopy] autorelease]
...and alter it
[mutableDict setObject:#"value3" forKey:#"key3"];
...then store it to a file
[mutableDict writeToFile:#"path/to/file" atomically:YES];
...and read it back again
NSMutableDictionary *anotherDict = [NSMutableDictionary dictionaryWithContentsOfFile:#"path/to/file"];
...read a value
NSString *x = [anotherDict objectForKey:#"key1"];
...check if a key exists
if ( [anotherDict objectForKey:#"key999"] == nil ) NSLog(#"that key is not there");
...use scary futuristic syntax
From 2014 you can actually just type dict[#"key"] rather than [dict objectForKey:#"key"]
NSDictionary *dict = [NSDictionary dictionaryWithObject: #"String" forKey: #"Test"];
NSMutableDictionary *anotherDict = [NSMutableDictionary dictionary];
[anotherDict setObject: dict forKey: "sub-dictionary-key"];
[anotherDict setObject: #"Another String" forKey: #"another test"];
NSLog(#"Dictionary: %#, Mutable Dictionary: %#", dict, anotherDict);
// now we can save these to a file
NSString *savePath = [#"~/Documents/Saved.data" stringByExpandingTildeInPath];
[anotherDict writeToFile: savePath atomically: YES];
//and restore them
NSMutableDictionary *restored = [NSDictionary dictionaryWithContentsOfFile: savePath];
The key difference: NSMutableDictionary can be modified in place, NSDictionary cannot. This is true for all the other NSMutable* classes in Cocoa. NSMutableDictionary is a subclass of NSDictionary, so everything you can do with NSDictionary you can do with both. However, NSMutableDictionary also adds complementary methods to modify things in place, such as the method setObject:forKey:.
You can convert between the two like this:
NSMutableDictionary *mutable = [[dict mutableCopy] autorelease];
NSDictionary *dict = [[mutable copy] autorelease];
Presumably you want to store data by writing it to a file. NSDictionary has a method to do this (which also works with NSMutableDictionary):
BOOL success = [dict writeToFile:#"/file/path" atomically:YES];
To read a dictionary from a file, there's a corresponding method:
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:#"/file/path"];
If you want to read the file as an NSMutableDictionary, simply use:
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:#"/file/path"];