iPhone: how to NSArray content to NSDictionary - iphone

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!

Related

How to join an NSArray output to an NSString separated with commas

I'm using the following code to try to join the array output into an NSString.
NSArray *array1 = [NSArray arrayWithObjects:[item objectForKey:#"id"], nil];
NSString *joinedString = [array1 componentsJoinedByString:#","];
NSLog(#"joinedString is %#", joinedString);
I would like this to output the joined string as: joined string is 55,56,57,66,88... etc... at the moment the output is:
2013-03-05 13:13:17.052 [63705:907] joinedString is 55
2013-03-05 13:13:17.056 [63705:907] joinedString is 56
2013-03-05 13:13:17.060 [63705:907] joinedString is 57
2013-03-05 13:13:17.064 [63705:907] joinedString is 66
You are probably running the join method inside a loop.
I suppose this is what you want.
NSMutableArray * array1 = [NSMutableArray array]; // create a Mutable array
for(id item in items){
[array1 addObject:[item objectForKey:#"id"]]; // Add the values to this created mutable array
}
NSString *joinedString = [array1 componentsJoinedByString:#","];
NSLog(#"joinedString is %#", joinedString);
You can do it as,
take for example
NSArray *array=#[#"A",#"B",#"C"];
NSString *string=[array componentsJoinedByString:#","];
NSLog(#"%#",string);
Output is :
A,B,C
What ever you are writing that one correct may be problem in [item objectForKey:#"id"] once check this one other all are fine.
NSMutableArray *array = [[NSMutableArray alloc]
initWithObjects:#"55",#"56",#"57",#"58", nil];
NSString *joinedString = [array componentsJoinedByString:#","];
NSLog(#"%#",joinedString);
I have been commenting on a couple of the answers here and found that most of the answers are just giving the code provided as the answer to solve this code, and the reason for that is because the code provided (See Provided code) works perfectly fine.
(Provide by question asker)
NSArray *array1 = [NSArray arrayWithObjects:[item objectForKey:#"id"], nil];
NSString *joinedString = [array1 componentsJoinedByString:#","];
NSLog(#"joinedString is %#", joinedString);
As the user hasn't provided how the item NSDictionary is created I am assuming that an NSArray has been created which contains some NSDictionaries
NSArray *array = [[NSArray alloc] initWithObjects:[NSDictionary dictionaryWithObjectsAndKeys:#"55", #"id", nil],
[NSDictionary dictionaryWithObjectsAndKeys:#"65", #"id", nil],
[NSDictionary dictionaryWithObjectsAndKeys:#"75", #"id", nil],
[NSDictionary dictionaryWithObjectsAndKeys:#"65", #"id", nil],
nil];
The problem is with the code that hasn't been provide, because we know that item is an NSDictionary we know that [item objectForKey:#"id"] doesn't return an individual items it returns an NSArray of ids. So based on if it was an NSArray it would log something like joinedString is (55, 56, 57...)". We also know that it can't just be a string as we would also only have one value than so it would log some thing like this joinedString is 55, and again this isn't what is wanted so. the only way to get what has been provided would be to have something like this
for(NSDictionary *item in array) {
NSArray *array1 = [NSArray arrayWithObjects:[item objectForKey:#"id"], nil];
NSString *joinedString = [array1 componentsJoinedByString:#","];
NSLog(#"joinedString is %#", joinedString);
}
So if this is the case than the way to resolve this would be to do
NSMutableArray *array1 = [NSMutableArray array];
for(NSDictionary *item in array) {
[array1 addObject:[item objectForKey:#"id"]];
}
// Note that this doesn't need to be in a for loop `componentsJoinedByString:` only needs to run once.
NSString *joinedString = [array1 componentsJoinedByString:#","];
NSLog(#"joinedString is %#", joinedString);
The output of this would be (As user wants)
joinedString is 55,65,75,65
Once the question asker provides the missing code I will correct his to answer based on there code but until then I am assuming.
EDIT:
First Check [item objectForKey:#"id"] it is proper or not ??
And Then use following code :
NSArray *array1 = [NSArray arrayWithObjects:[item objectForKey:#"id"], nil];
NSString *commaSpStr;
commaSpStr = [array1 componentsJoinedByString:#", "];
NSLog(#"%#", commaSpStr);
You are recreating array1 everytime. Create an instance variable of array1, insert [item objectForKey:#"id"] value to it and you will see joinedString will be updated.
NSMutableArray *arr = [[NSMutableArray alloc] init];
for (NSDictionary *item in array) {
[arr addObject:[item objectForKey:#"id"]];
}
NSString *joinedStr = [arr componentsJoinedByString:#","];

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

NSDictionary within NSArray

A quick question about NSArrays and NDictionarys.
I have and NSArray containing NSDictionarys.
The NSDictionary contain a date and a string.
What I would like to do is end up with an NSDictionary with keys dates and values arrays of strings that are on that date.
What would be the best way to do this
NSMutableDictionary *result = [NSMutableDictionary dictionary];
for (NSDictionary *dict in array) {
NSDate *date = [dict objectForKey:#"dateKey"];
NSString *string = [dict objectForKey:#"stringKey"];
NSMutableArray *stringsWithDate = [result objectForKey:date];
if (!stringsWithDate) {
stringsWithDate = [NSMutableArray array];
[result setObject:stringsWithDate forKey:date];
}
[stringsWithDate addObject:string];
}
Note that NSDate is not a "calendar date", so the same day with a different time will be considered as a distinct date in your result dictionary.
As I do not see any reasonable motivation for doing this, let's call it code golf.
NSMutableArray *dates = [NSMutableArray array];
NSMutableArray *strings = [NSMutableArray array];
for (NSDictionary *dict in dictArray) {
[dates addObject:[dict objectForKey:#"date"]];
[strings addObject:[dict objectForKey:#"string"]];
}
NSArray *datesArray = [[NSArray alloc] initWithArray:dates];
NSArray *stringsArray = [[NSArray alloc] initWithArray:strings];

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;
}

Values not appending to my NSMutableDictionary

I'm trying to add some vales to a NSMutableDictionary dynamically. However, using the following code, I'm adding values using the first letter as the key to a temporary dictionary and then finally adding it to my names dictionary but it just overwrites each value for it's corresponding key
NSMutableDictionary *dictionary = [[[NSMutableDictionary alloc] init] autorelease];
for (NSString *drugStr in listContents) {
NSString *substring = [drugStr substringToIndex:1];
[dictionary setValue:drugStr forKey:substring];
}
names = [[NSDictionary alloc] initWithDictionary:dictionary];
[dictionary release];
What am I doing wrong?
You should define your NSDictionary to use NSString as a key, and NSArray as a value.
Then you should just retrieve your value according to the given key. If the result is nil, then you need to create a new NSMutableArray, to which you add the value above. IF the result is not-nil, add the value to the array.
NSMutableDictionary *dictionary = [[[NSMutableDictionary alloc] init] autorelease];
for (NSString *drugStr in listContents) {
NSString *substring = [drugStr substringToIndex:1];
NSMutableArray *valueArray = (NSMutableArray*)[dictionary objectForKey:substring];
if(valueArray==nil){
NSMutableArray *newArray = [NSMutableArray arrayWithCapacity:5];
[newArray addObject:drugStr];
[dictionary setObject:newArray forKey:substring];
}else{
[valueArray addObject:drugStr];
}
}
names = [[NSDictionary alloc] initWithDictionary:dictionary];
[dictionary release];