I’m looking for the best way to store data like this...
Value 1
-item 1
-item 2
-item 3
...
-item 9
Value 2
-item 1
...
-item 9
Value 3
etc...
Then I want to pick a subset of the items for a given “value”
Is NSMutableDictionary the way to go for this? I’m getting a little confused in setting this up.
I’ve been trying this... but its not quite right apparently. Thanks for the help.
NSMutableDictionary *dictionary;
[dictionary setObject:#"Entry1" forKey:#"1"];
[dictionary setObject:#"1-Entry2" forKey:#"1"];
[dictionary setObject:#"Entry2" forKey:#"2"];
[dictionary setObject:#"Entry3" forKey:#"3"];
NSLog(#"1: %#", [dictionary objectForKey:#"1"]);
NSLog(#"/n 2: %#", [dictionary objectForKey:#"1"]);
If you want multiple objects under a single key, you need to use arrays inside the dictionary:
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:[NSArray arrayWithObjects:#"item1", #"item2", nil] forKey:#"Key1"];
and so on.
Related
I have a JSON array being pulled into XCode with a key and value. I can get the keys. I can get the values. But is there an easy way to combine them into a single array?
The following code works, but I end up with two separate arrays (channels and channelKeys).
This seems like an inelegant way to create a single array which contains both the key and its value.
-(void) convertArray : (NSMutableArray *)data{
// Set data
NSMutableDictionary *dic = [data objectAtIndex:0];
for (NSString *key in [dic allKeys]) {
[channels addObject:[dic objectForKey:key]];
}
// Set Key Array
NSMutableDictionary *dic3 = [data objectAtIndex:0];
NSArray *keys = [dic3 allKeys];
[channelKeys addObjectsFromArray: keys];
}
If you are trying to create an array of the form [key1, value1, key2, value2, key3, value3...] then try something like the following (recall that keys are not restricted to NSStrings)
for (id key in [dic allKeys]) {
[resultArray addObject:key];
[resultArray addObject:[dic objectForKey:key]];
}
I am new to objective c. I am interesting in having something like this:
- for each key I want to store multiple values like:
2 holds a,b,c
3 holds d,e,f
When pressing 2 3 or 2 3 3, I want to have at output all the combinations from these 6 values. Should I use a NSMutableDictionary for this? I need some advices!
You can store arrays in dictionaries. For example
NSDictionary *mapping = #{#"2": #[#"a", #"b", #"c"]};
and you could for each key press add the objects from the array in the dictionary to an intermediate array
NSMutableArray *values = [NSMutableArray array];
...
// For each time a key is pressed
[values addObjectsFromArray:#[mapping[keyPressed]]];
...
When you want to display the output you calculate all combinations for all values in the values array.
For store multiple value of single key, you need to add array as value of dictionary key, such like,
NSArray *temArray1 = ...// which has value a,b,c
NSArray *temArray2 = ...// which has value d,e,f
Add this array as value of specific key, such like
NSMutableDictionary *temDic = [[NSMutableDictionary alloc] init];
[temDic setValue:temArray1 forKey#"2"];
[temDic setValue:temArray1 forKey#"3"];
NSLog(#"%#", temDic)
Above code describe simple logic as per your requirement change it as you need.
Please Try this..
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
NSArray *aryFlashCardRed=[[NSArray alloc]initWithObjects:#"f1",#"f2",#"f3", nil];
NSArray *aryFlashCardYellow=[[NSArray alloc]initWithObjects:#"f4",#"f5",#"f6", nil];
NSArray *aryFlashCardGreen=[[NSArray alloc]initWithObjects:#"f7",#"f8",#"f9", nil];
NSArray *aryScore=[[NSArray alloc]initWithObjects:#"10",#"20",#"30", nil];
[dictionary setObject:aryFlashCardRed forKey:#"red"];
[dictionary setObject:aryFlashCardYellow forKey:#"yellow"];
[dictionary setObject:aryFlashCardGreen forKey:#"green"];
[dictionary setObject:aryScore forKey:#"score"];
Display dictionary like this
{
green = (
f7,
f8,
f9
);
red = (
f1,
f2,
f3
);
score = (
10,
20,
30
);
yellow = (
f4,
f5,
f6
);
}
Objective-c has 3 types of collections: NSArray, NSSet, NSDictionary (and their mutable equivalents). All this collections can store only objects. This collections uses for different cases, so try to find case which is appropriate to You and use appropriate collection.
P.S. My first wish was to write RTFM
Try like below :-
NSDictionary *yourDict=[NSDictionary dictionaryWithObjects:
[NSArray arrayWithObjects:#"a", #"b", #"c",nil]
forKeys:[NSArray arrayWithObjects:#"2",nil]];
This question already has answers here:
NSDictionary with ordered keys
(9 answers)
Closed 9 years ago.
Hi i have an dictionary which is been set by me and am accessing it
the code is as follows.
NSMutableDictionary* filteredDictionary = [NSMutableDictionary dictionary];
[filteredDictionary setObject:#"xcode" forKey:#"1"];
[filteredDictionary setObject:#"ios" forKey:#"3"];
[filteredDictionary setObject:#"ipad" forKey:#"2"];
[filteredDictionary setObject:#"iphone" forKey:#"5"];
[filteredDictionary setObject:#"simulator" forKey:#"4"];
NSLog(#"%#",filteredDictionary);
current output:
{
1 = xcode;
2 = ipad;
3 = ios;
4 = simulator;
5 = iphone;
}
but i want
{
1 = xcode;
3 = ios;
2 = ipad;
5 = iphone;
4 = simulator;
}
i want the dictionary as i set the object in it
i dont want to make the dictionary to sort according to it
Pls Help
Thanks in advance.....
You can't sort the keys in-place, as dictionaries are hash-tables.
You can get the key/value pairs as an array, and sort the array before showing it though:
See https://stackoverflow.com/a/4558777/15721
The NSDictionary doesn't remember the order in which you add the keys. You'll have to do it yourself. I would suggest using an NSMutableOrderedSet.
NSMutableDictionary* filteredDictionary = [NSMutableDictionary dictionary];
NSMutableOrderedSet* keyOrder = [[NSMutableOrderedSet alloc] init];
[filteredDictionary setObject:#"xcode" forKey:#"1"];
[keyOrder addObject: #"1"];
[filteredDictionary setObject:#"ios" forKey:#"3"];
[keyOrder addObject: #"3"];
// etc
Obviously this is a pain in the neck, so create yourself a new collection class
#implementation MyMutableOrderedDictionary
{
NSMutableDictionary* filteredDictionary = [NSMutableDictionary dictionary];
NSMutableOrderedSet* keyOrder = [[NSMutableOrderedSet alloc] init];
}
-(void) setObject: (id) object forKey: (id <NSCopying>) key
{
[filteredDictionary setObject: object forKey: key];
[keyOrder addObject: key];
}
-(NSOrderedSet*) keys
{
return keyOrder;
}
// Some other methods
#end
You can implement some enumeration methods by iterating over keyOrder internally or over the keys property externally.
Note I'm not subclassing NSMutableDictionary, because that can be a pain in the arse as it is a class cluster.
NSDictonary doesn't guarantee order when you access it. You have to use NSArray if you want to keep order of elements.
There few ideas like OrderedDictionary (http://www.cocoawithlove.com/2008/12/ordereddictionary-subclassing-cocoa.html) but it's better to just use right objects for right purposes.
NSDictonary is not mean to sort the objects and it is absolutely unimportant to consider the order of the elements.
NSdictonary is a set of key-value pair where it is expected to access the value using the respective key and so the concept of index is not useful in it.
Still if you want to play on indexes you should use NSArray.
I have a fixed data which will be used in a UITableView later and the user will not update/add on this data.
This data looks like a table with 4 column:
Name (String) | Tel (INT) | Logo (URL) | PDF File (URL)
The UITableView will be fill with this data and if the user select a row he will navigate to another pages which show the PDF file.
The question is should I use the core data or Array, if the answer is Array how can I have column in the Array?
Thanx,
You can easily use an array with a NSDictionary inside. Both structures might be mutable and you can use the dictionary to simulate what you call columns.
Example:
[myMutDict setObject:name forKey:#"name"];
[myMutDict setObject:[NSNumber numberWithInt:n] forKey:#"number"];
[myMutArray addObject:myMutDict];
I'd not go for coredata
In your didSelectRowAtIndexPath you'll select your data like this:
NSDictionary *dict = [myMutArray objectAtIndex:indexPath.row];
NSString *name = [dict objectForKey:#"name"];
int tel = [[dict objectForKey:#"number"] intValue];
For this it is better to use NSMutable Array.
For this data to save in NSArray Initially you need to save every row in a NSMutableDictionary like
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc]initWithCapacity:4];
[dictionary setObject:value forKey:#"Name"];
[dictionary setObject:value forKey:#"Tel"];
[dictionary setObject:value forKey:#"Logo"];
[dictionary setObject:value forKey:#"PDF File"];
so add this dictionary to a NSMutableArray like this
[array addObject:dictionary];
You can easily retrive the data from array
I have a
NSDictionary* dict = [[NSDictionary alloc]initWithObjectsAndKeys::arrayOne,#"Plants",arrayTwo,#"Animals"),arrayThree,#"Birds",nil];`
self.displayArray =[[dict allKeys] sortedArrayUsingSelector:#selector(compare:)];
Everything works fine, I am able to see all the key value/pair in the table but they are in sorted order. i.e Animals,Birds,Plants.
But I want to display as Plants,Animals,Birds.
Can anyone tell me how to sort the array in my customized order?
I have googled and found that we can use NSSortDescriptor for sorting. But I am not very clear with that. Can anyone help me ?
As your ordering doesnt follow any natural order, a simple solution could be to keep track of the order with another array
NSArray *array1 = [NSArray arrayWithObjects:#"rose",#"orchid",#"sunflower",nil];
NSArray *array2 = [NSArray arrayWithObjects:#"dog", #"cat",#"ogre",#"wookie", nil];
NSArray *array3 = [NSArray arrayWithObjects:#"parrot",#"canary bird",#"tweety",#"bibo",nil];
NSArray *keys = [NSArray arrayWithObjects:#"Plants",#"Animals",#"Birds", nil];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
array1,[keys objectAtIndex:0],
array2,[keys objectAtIndex:1],
array3,[keys objectAtIndex:2],
nil];
for (NSString *key in keys) {
NSLog(#"%# %#", key, [dict objectForKey:key]);
}
Matt shows in his fantastic blog, how to create a ordered dictionary, that essentially uses another array to keep the order just as I showed here: OrderedDictionary: Subclassing a Cocoa class cluster
You're on the right track, Cyril.
Here is some Apple documentation on "Creating and using Sort Descriptors"
Basically you need to subclass NSSortDescriptor and in your subclass, implement your own "compare:" method (you can actually name it anything you want; it needs to return a "NSComparisonResult") that somehow logically returns "Plants" before "Animals".