Get back value of Object key'ed NSMutableDictionary - ios

I have a case where I need to have NSMutableDictionary with NSManagedObject as the key.
Based on this post, I can set NSManagedObject as key in dictionary by:
[NSValue valueWithNonretainedObject:]
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:product forKey:[NSValue valueWithNonretainedObject:category]];
How can I get back the value of dict? I've tried using NSValue again but it crash with no description.

Try using [theValue nonretainedObjectValue]
But if you want to access the keys frequently, a dictionary might not be the right data structure for you. Especially if you want some kind of inverse relationship with objects and keys (if that is what you mean with get back the value of dict).

Related

NSMutableDictionary key value shuffled

I am facing very strange problem in NSMutableDictionary. Please see the below code.
NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];
[dict setValue:#"India" forKey:(#"Title")];
[dict setValue:#"Done" forKey:(#"Status")];
When I had printed this dictionary object, It shows like below.
{
Status =Done,
Title=India;
}
This keys getting shuffled, actually Title key should come first.
So, How can I resolve this issue.
That's not an issue.
You have mis understood or you'r getting wrong the NSDictionary. NSDictionary is a container to store values base on the keys.
So, there is no need of any order or indexing.
Reason behind is that you can only access container value if you know the key. So it is meaning less to check order of that keys. Because any how you have to use that key to access related value.
Now about order - Use NSArray instead and more of that use NSArray with object of NSDictionary. So that you have order with dictionary support.
Still the way to sort dictionary keys is below:
NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];
[dict setValue:#"India" forKey:(#"Title")];
[dict setValue:#"Done" forKey:(#"Status")];
NSArray *keys = [dict allKeys];
keys = [keys sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
NSLog(#"%#",keys);
NSDictionary or NSMutableDictionary does not guarantee any ordering of it's key/value pairs. There's no way to keep your keys/values in a set order and it doesn't make sense for NSDictionary or NSMutableDictionary to work like this. (You use keys not indexes to retrieve values).
If you want your values or keys in a certain order for display purposes you can sort them after retrieving them:
NSArray * sortedKeys = [ [ myDictionary allKeys ] sortedArrayUsingSelector:... ] ;
or
NSArray * sortedKeys = [ [ myDictionary allKeys ] sortedArrayUsingComparator:... ] ;
You could then retrieve the associated objects for the sorted keys if you wanted.
Another option is to maintain 2 separate arrays, one for keys and one for values and keep them in order.

NSDictionary objectForkey and accessing the key directly

I have a simple question about accessing different ways of accessing values stored in NSDictionary. so if i have a dictionary like
NSDictionary *dict =#{#"Mammal" : #"Cow", #"Bird" : #"Eagle"};
Now what is the difference if i access the elements like dict[#"Mammal"] and [dict objectForKey:#"Mammal"] what if there is no object with key #"Mammal" in this case. Does it crash with dict[#"Mammal"] or dict[#"Mammal"] calls [dict objectForKey:#"Mammal"] under the hood.
Is it the similar case with NSArray, NSMutableArray & NSMutableDictionary
Using dict[#"Mammal"] actually calls - (id)objectForKeyedSubscript:(id)keyunder the hood.
The behaviour is the same as calling [dict objectForKey:#"Mammal"] according to the documentation:
Return Value
The value associated with aKey, or nil if no value is associated with aKey.
Discussion
This method behaves the same as objectForKey:.

Adding arrays as keys and values in NSDictionary/NSMutableDictionary

I have already initialized two arrays named - questionArray and correctAnswerArray.
I want to add these two arrays in a NSDictionary/ NSMutableDictionary (the one more appropriate) such that the questionArray will be the value (each index of it) and the correctAnswerArray will be the key.
Whether you chose NSMutableDictionary or not depends on if you want to change the data later on. Either way you can just change the following if you want a standard dictionary.
NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithObjects:questionArray forKeys:correctAnswerArray];
** EDIT **
To retrive a value just do:
NSString *value = [dict valueForKey:#"KEY"];
or
NSString *value = dict[#"KEY"];

Which is the best way to save data (numbers) in a plist file

Initially I had an object made of three properties (numbers 0 to 12). NSCoder and related issues made me avoid using an object and now I store three NSNumbers directly instead. I save a NSMutableArray with the three values in this way
NSMutableArray *data=[[NSMutableArray alloc] initWithObjects: cardSign, cardNumber, cardColor, nil];
I save and check if data are saved
NSLog(#"wrote %hhd", [data writeToFile:path atomically:YES]);
I try to retrieve the data:
NSArray *dataRead = [[NSArray alloc] initWithContentsOfFile:path];
if (dataRead)
{
cardSign = [dataRead objectAtIndex:0];
cardNumber = [dataRead objectAtIndex:1];
cardColor = [dataRead objectAtIndex:2];
}
Before saving the variable values are correct.
When I try to retrieve the values I get all 0 or (null).
Which is the best way to store three numbers in a plist file and how do I retrieve it?
Most likely your objects "cardSign", "cardNumber", and "cardColor", are not actual objects. When storing array contents or NSArray contents to a file all objects must be Apple recognized objects, NSString, NSNumber, etc...
If for instance cardNumber is defined as follows:
int cardNumber;
Then when "data" is initialized if should be something like (pay only attention to cardNumber)
NSMutableArray *data=[[NSMutableArray alloc] initWithObjects: cardSign, [NSNumber numberWithInt:cardNumber], cardColor, nil];
This line is taken directly from discussion section of the Apple API description of the "initWithContentsOfFile" call.
"The array representation in the file identified by aPath must contain only property list objects (NSString, NSData, NSArray, or NSDictionary objects). The objects contained by this array are immutable, even if the array is mutable.

Keep NSArray original order in NSCountedSet

I have an NSArray and I need to get data from two keys and put together in a NSMutableDictionary. One key has stringvalues and the other NSNumbervalues. When I try to create NSCountedSetwithout adding the keys I want to use to separate arrays, it doesn't work, because the objects are not identical, basically, I need to check if objectId is identical, don't matter if the other keys are different.
Here is the initial code:
for (PFObject *objeto in objects) {
PFObject *exercicio = objeto[#"exercicio"];
NSString *string = exercicio.objectId;
NSNumber *nota = objeto[#"nota"];
[exercicios addObject:string];
[notas addObject:nota];
So I create two NSMutableArraysand store the values I need. When I logthe arrays after this, they are perfectly ordered, meaning the NSStringis in the same indexof the NSNumberit belongs to in the other array. So far, so good.
Now, when I create the NSCountedSetwith the strings, it changes the order.
NSCountedSet *countedExercicios = [[NSCountedSet alloc] initWithArray:exercicios];.
My goal is to sum the NSNumbers pertaining to an specific object, therefore, when the order changes, I lose the connection between the two arrays.
I'm not sure what I could do to solve this problem, or even if there's a different approach to achieve the result I need.
You can create NSDictionary and add it to array. You will have just one array and you won't lose the connection, you can use objectId as a key and NSNumber as a value:
for (PFObject *objeto in objects) {
PFObject *exercicio = objeto[#"exercicio"];
NSString *string = exercicio.objectId;
NSNumber *nota = objeto[#"nota"];
NSDictionary *dict = #{string: nota};
[newArray addObject: dict];
}
When you need get all key (objectId) you can use NSPredictate.
Hope this help

Resources