How to set array value and key in NSDictionary in iphone? - iphone

Here i am using NSMutableArray to store date, then i tried to set key and assign ArrayValue in dictionary but the app crashed, please help me
Thanks in ADvance
Here i tried the code for your reference:
[DateArray addObject:dateString]; //NSMutablArray
NSMutableDictionary *myDictionary =[[NSMutableDictionary alloc]init];
[myDictionary setObject:DateArray forKey:#"Date"]; //put array value and set key in NSDictionary.

NSDictionary Class is immutable. You must convert to NSMutableDictionary.

If you are using XCode version 4.4 or later you can jus do this:
[dateArray addObject:dateString]; //NSMutablArray
NSDictionary *myDictionary = #{ #"Date", dateArray };

You are using NSDictionary. You should use NSMutableDictionary.
NSDictionary is immutable. If you want to use NSDictionary then use below method:
- (id)initWithObjects:(NSArray *)objects forKeys:(NSArray *)keys;

You're using an NSDictionary when you should be using NSMutableDictionary
Try this line :
NSMutableDictionary *myDictionary = [[NSMutableDictionary alloc] init];
Most of the collection classes in iOS have a mutable and nonmutable version (i.e.
NSArray -> NSMutableArray
NSSet -> NSMutableSet
NSDictionary -> NSMutableDictionary
(and others)
A mutable version will let you modify the contents. However, if you know you're not going to change it then a non mutable version will be slightly faster to use.
You can (usually) get a mutable class from a nonmutable one by using the mutableCopy method i.e.
// This array can't be changed
NSArray *myArray = #[ #"A", #"B", #"C" ];
// This array contains everything from the previous array but can now be modified
MSMutableArray myArray2 = [myArray mutableCopy];
NB : There are also other classes that have mutable subclasses i.e. NSURL -> NSMutableURL

Do it like this:
for(int i=0;i<[DateArray count]; i++)
{
[myDictionary addObject:[DateArray objectAtIndex:i] forKey:#"Date"];
}

Related

Moving through a NSDictionary getting objects that you do not know the 'Key' for? IOS

I have a NSDictionary that I get from a webservice. Each object in this dictionary contains an array. I do not know how many objects there are going to be in the NSDictionary, or what the 'Key' for each object is going to be beforehand. I only know that it will be a Dictionary of arrays.
How can I enumerate through the dictionary reading out the name of the Object and its content into arrays?
All my dealings with Dictionaries so far I could use
[anotherDict objectForKey:#"accounts"]
because I know the 'Keys; to expect beforehand.
Many Thanks,
-Code
NSDictionary has the method: enumerateKeysAndObjectsUsingBlock: since iOS 4.0. It's very straightforward, it receives a block object to operate on entries in the dictionary.
An example:
[anotherDict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSArray *arr = obj;
//Do something
}
NSDictionary class has an instance method -allKeys which returns an NSArray with NSStrings for all the keys.
Simplest Way WOuld be to fetch allKeys via the allKeys instance method
NSArray *keys = [myDictionary allKeys];
then iterating over dictionary with for each key.
for (NSString *k in keys)
{
id object = [myDictionary objectForKey:k];
}
You can also get keys in order as if values were sorted using
NSArray *sortedKeys = [myDictionary keysSortedByValueUsingSelector:#selector(compare:)];
you can do this :
NSArray * keys = [dictionnary allKeys];
for (NSString *key in keys) {
NSArray *tmp = [dictionnary objectForKey:key];
}
i am not a pro but i know that you can get all the keys of an dictionary
NSLog(#"%#",[Your_Dictionary allKeys]);
This will give an array of keys in that dictionary.

How to use setValue:forKey: function with NSArray

I'm try to use the functions -setValue:forKey: and get the value using -valueForKey:
Example:
NSArray *rootarr = [[NSArray alloc] init];
NSArray *array = [[NSArray alloc] initWithObjects:#"name", #"address", #"title", nil];
[rootarr setValue:array forKey:#"n"];
NSArray *getArr = [rootarr valueForKey:#"n"];
But the getArr array I got is not equal the array I set (array).
Could you please tell me what's wrong I met. And what's the way to use these functions?
NSArray's setValue:forKey: method is used for Key Value Coding, not for using an array as an associative container. You need to use NSMutableDictionary.
NSMutableDictionary *rootDict = [NSMutableDictionary dictionary];
NSArray *array = [[NSArray alloc] initWithObjects:#"name", #"address", #"title", nil];
[rootDict setValue:array forKey:#"n"];
NSArray *getArr = [rootDict valueForKey:#"n"];
An array isn't a key-value store, which you appear to want to use it as. I think you want an NSDictionary instead (or more precisely NSMutableDictionary if you want to modify it after its created).
According to the Apple documentation setValue:forKey:
Invokes setValue:forKey: on each of the array's items using the specified value and key.
Practical uses are when you want to set the same value to each element of the array
UILabel *label1 = [[UILabel alloc]init];
UILabel *label2 = [[UILabel alloc]init];
NSArray *arr = #[label1, label2];
[arr setValue:#"bye" forKey:#"text"];
NSLog(#"%# %#",label1.text, label2.text); // bye bye
in your example "getArr" is an empty array because your "rootarr" doesn't have elements, otherwise you receive a setValue:forUndefinedKey: into the contained objects that are not compliant for the assigned key
You can't add objects to an NSArray after it is created. You have to use NSMutableArray in order to do that.

Creating a Two-Dimensional Array with Concrete Positions

I need to create a custom array:
In php I would define as follows:
$myarray[100][80] = 1;
But I don't know how to do it in objective-c...
I don't need an array [0][0],[0][1],[0][2], ... I only need concrete positions in this array [80][12], [147][444], [46][9823746],...
The content of these positions always will be = 1;
for this you would use a dictionary rather than an array as they are always 0,1,2 keyed so something along the lines of:
NSNumber *one = [NSNumber numberWithInt:1];
NSString *key = #"80,12";
NSDictionary *items = [NSDictionary dictionaryWithObject:one forKey:key];
Then to pull them out again you would use the objectForKey: method.
You cannot put ints directly into arrays or dictionaries that's why it is wrapped in the NSNumber object. To access the int after getting the NSNumber out of the dictionary you would use something like:
NSNumber tempNum = [items objectForKey:key];
int i = tempNum.intValue;
See the docs here for a full explanation of the NSDictionary class. Hope this helps...
I an not a PHP master but I believe in php arrays are not real arrays they are hash tables right?
Anyway, I think you are looking for NSDictionary or NSMutableDictionary class.
That looks more like a bitset than an array.
Allocating so many cells for that seems useless, so maybe you could revert the problem, and store the positions in an array.
Well in objective c we can use NSMutableArray to define 2-D arrays.
See the following code, it might help you
NSMutableArray *row = [[NSMutableArray alloc] initWithObjects:#"1", #"2", nil];
NSMutableArray *col = [[NSMutableArray alloc] init];
[col addObject:row];
NSString *obj = [[col objectAtIndex:0] objectAtIndex:0];
NSLog(#"%#", obj);

Replace a value in NSDictionary in iPhone

I have a array (dataArray) of NSDictionary "item". It has datas like "david" for key "name" and "85" for key "marks" etc for 5 students. I want to replace the mark of david to 90 with respect to the array index value (ie 0 for dictionary containing david and 85). How can I do it?
The code for content in array is
[item setobject:name forkey:#"Name"];
[item setobject:mark forkey:#"Marks"];
[dataArray addOject:item]
The above code goes inside parsing, so i have array with 5 objects (students), their name and marks, now I want to replace the mark of the first object in the dataArray.
Here's what you can do:
NSMutableDictionary *newDict = [[NSMutableDictionary alloc] init];
NSDictionary *oldDict = (NSDictionary *)[dataArray objectAtIndex:0];
[newDict addEntriesFromDictionary:oldDict];
[newDict setObject:#"Don" forKey:#"Name"];
[dataArray replaceObjectAtIndex:0 withObject:newDict];
[newDict release];
Hope this helps!
You first need an NSMutableDictionary with it you can change the key and value.
It would be like this:
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:#"david", #"name", "85", #"marks", nil];
[dict setObject:#"90" forKey:#"david"];
// NSDictionary *dict = ...
NSMutableDictionary *mutableDict = [dict mutableCopy];
[mutableDict setObject:#"myObject" forKey:#"myKey"];
dict = [mutableDict mutableCopy];
I hope it helps
If you want to update an object in a NSDictionary you should use NSMutableDictionary instead.
NSMutableDictionary has the following EXTRA methods
Adding Entries
setObject:forKey:
setValue:forKey:
addEntriesFromDictionary:
setDictionary:
Removing Entries
removeObjectForKey:
removeAllObjects
removeObjectsForKeys:
[davidsRecord setObject:#"100" forkey:#"mark"];

Mutable Object within an Immutable object

Is it acceptable to have a NSMutableArray within an NSDictionary? Or does the NSDictionary also have to be mutable?
The NSMutableArray will have values added to it at runtime, the NSDictionary will always have the same 2 NSMutableArrays.
Thanks,
Dan
Yes, it's perfectly acceptable. Keep in mind, the contents of the array are the pointers to your NSMutableArrays--those are what can't change in the immutable dictionary structure. What the pointers point to can change all you want. To wit:
NSMutableArray *arr = [[NSMutableArray alloc] init];
NSDictionary *dict = [NSDictionary dictionaryWithObject:arr forKey:#"test"];
[arr addObject:#"Hello"];
NSString *str = [[dict objectForKey:#"test"] objectAtIndex:0];
NSLog("%#", str);
It's quite acceptable. But, it's precisely the sort of setup that suggests you should seriously consider replacing the dictionary with an NSObject subclass that sports two properties for accessing the arrays.