A question about NSDictionary initialization - nsdictionary

the result is 4 2 3, but what happened in the process of initialization of this NSDictionary?
it's because that its assignment just execute at first time and ignore the rest assignment to same key? Or it's because that its assigment execute with Reverse order?
NSDictionary *dic = #{
#"a":#"4",
#"b":#"2",
#"c":#"3",
#"a":#"1",
#"b":#"5",
#"c":#"6",
};
NSLog(#"luozhiyong,%#",dic[#"a"]);
NSLog(#"luozhiyong,%#",dic[#"b"]);
NSLog(#"luozhiyong,%#",dic[#"c"]);

From the documentation of NSDictionary:
NSDictionary A static collection of objects associated with unique keys.
In addition to the provided initializers, such as initWithObjects:forKeys:, you can create an NSDictionary object using a dictionary literal.
NSDictionary *dictionary = #{
#"anObject" : someObject,
#"helloString" : #"Hello, World!",
#"magicNumber" : #42,
#"aValue" : someValue
};
In Objective-C, the compiler generates code that makes an underlying call to the dictionaryWithObjects:forKeys:count: method.
From the documentation of dictionaryWithObjects:forKeys:count:
This method steps through the objects and keys arrays, creating entries in the new dictionary as it goes.
The result of
NSDictionary *dic = #{
#"a":#"4",
#"b":#"2",
#"c":#"3",
#"a":#"1",
#"b":#"5",
#"c":#"6",
};
is unpredictable and may be different in other versions of Foundation. On macOS 10.13.6 the duplicate keys are ignored.

Related

How to set Dictionary in NSUserDefault in swift?

I've a mutable dictionary (in form of [Int:Int]) and want that to save it. I would use NSUserDefaults like that:
var myDic: NSMutableDictionary = [:]
myDic = [1:2]
NSUserDefaults.standardUserDefaults().setObject(myDic, forKey: "myDic")
but with that I get an error:
Thread 1: signal SIGABRT
I have no idea why.
setObject(_:forKey:) can’t accept Dictionary with a key which is integer type. The method requires property-list objects, but myDic = [1:2] is not property-list object.
There are two documents about it.
setObject(_:forKey:) of NSUserDefaults
The value parameter can be only property list objects: NSData,
NSString, NSNumber, NSDate, NSArray, or NSDictionary. For
NSArray and NSDictionary objects, their contents must be property
list objects.
About Property Lists
And although NSDictionary and CFDictionary objects allow their keys to
be objects of any type, if the keys are not string objects, the
collections are not property-list objects.
If you set a integer-key to Dictionary, the Dictionary object cannot be used for a value of setObject. You have to use a string for the key like this:
myDic = ["1": 2]

adding Key values from NSDictionary to NSarray

I want to add all the keys from the dictionary to the array. This is what I am doing right now.As code below:
for (NSString * akey in _groups ) {
NSLog(#"%#",akey);
[_groupArray addObject:akey];
NSLog(#"%#",_groupArray);
}
The log is showing Null for _groupArray. I even tried using insertObjectAtIndex even that does not work.Not sure what I am doing wrong and yes I am getting the keys in the dictionary (_groups) nothing wrong with that.
You should initialize the array before starting to add values to it. Otherwise it is initially nil and will remain nil.
You can use allKeys to get all the keys of the array. But since _groupArray is an NSMutableArray, you have to do that like this:
_groupArray = [NSMutableArray arrayWithArray:[_groups allKeys]];
Or:
_groupArray = [[_groups allKeys] mutableCopy];
If _groupsArray is new or empty anyway then you can use
_gropusArray = [NSMutableArray arrayWithArray:[dict allKeys]];
That should release you from the compiler warning.
If _groupsArray was not empty before and you need to addValues then go for:
[_groupsArray addObjectsFromArray:[dict allKeys]];
this is how you should do it....
_groupsArray=[dict allKeys];
don't forget to allocate memory to your _groupsArray.. :)
Have you checked you've alloc'd and init'd your mutable array. Unless there's already stuff in it that you're adding to - and even then - consider using the NSDictiomary allKeys method rather than iterating through the dictionary.
From the docs
allKeys
Returns a new array containing the dictionary’s keys.
- (NSArray *) allKeys
Return Value
A new array containing the dictionary’s keys, or an empty array if the dictionary has no entries.
Discussion
The order of the elements in the array is not defined.

method with many parameters

i have a method with 20 parameters,( NSString, float,....), can i construct a type ( for example Enumerated, typdef) to invoque my method and not pass all my parameters ?
replace:
-(void)myMethodeParam1:...:param2:.... ;
with:
-(void)myMethode:MyNewTypeParam ;
tanks for your answers
You can use NSDictionary (NSMutableDictionary). You'll need to wrap primitive type (like float) to obj-c objects (e.g. NSNumber) for that though.
E.g. you have 10 NSString params named param0,...,param9 then you can place them in NSDictionary:
NSDictionary *paramDict = [NSDictionary dictionaryWithObjectsAndKeys:string0, #"param0", string1, #"param1", ..., string9, #"param9", nil];
[obj myMethod: paramDict];
or if you can enumerate your variables somehow you can use NSMutableDictionary and add them to it in a loop.
Then in your method you can get your parameters from dictionary you have:
-(void)myMethode: (NSDictionary*)dict{
NSString *string0 = [dict objectForKey:#"param0];
//Do something with it
...
}
If your parameters together are some logical entity and they're usually used together you also can also create a custom class that contains them as instance variables

NSDictionary with integer as number

I have a NSDictionary with the following layout:
{
1:{
... some data ...
}
...
}
I have a NSNumber object with a integer value of 1, but when I do
[my_dict objectForKey:my_number] it returns null.
If I try and convert NSNumber to a integer via [my dict objectForKey:[my_number intValue]] I get a warning and the program crashes when it reaches that part of the code.
Any help would be greatly appreciated.
Keys in a NSDictionary or NSMutableDictionary must be objects, like NSNumber. They cannot be primitive data types, like int.
http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSDictionary_Class/Reference/Reference.html
Looks like you're trying to use an integer as the key in your NSDictionary. This would be correct with an NSArray, with an NSDictionary actually needs a proper object as a key.
You might have more success in this particular case feeding that data into an NSArray, and accessing it with:
id *someData = [my_array objectAtIndex:1];

NSDictionary with key => String and Value => c-Style array

I need an NSDictionary which has key in the form of string (#"key1", #"key2") and value in the form of a C-style two-dimensional array (valueArray1,valueArray2) where valueArray1 is defined as :
int valueArray1[8][3] = { {25,10,65},{50,30,75},{60,45,80},{75,60,10},
{10,70,80},{90,30,80},{20,15,90},{20,20,15} };
And same for valueArray2.
My aim is given an NSString i need to fetch the corresponding two-dimensional array.
I guess using an NSArray, instead of c-style array, will work but then i cannot initialize the arrays as done above (i have many such arrays). If, however, that is doable please let me know how.
Currently the following is giving a warning "Passing argument 1 of 'dictionaryWithObjectsAndKeys:' from incompatible pointer type" :
NSDictionary *myDict = [NSDictionary dictionaryWithObjectsAndKeys:valueArray1,#"key1",
valueArray2,#"key2",nil];
Is valueArray2 also an int[][3]? If so, you could use
[NSValue valueWithPointer:valueArray1]
to convert the array into an ObjC value. To retrieve the content, you need to use
void* valuePtr = [[myDict objectForKey:#"key1"] pointerValue];
int(*valueArr)[3] = valuePtr;
// use valueArr as valueArrayX.
If there's just 2 keys, it is more efficient to use a function like
int(*getMyValueArr(NSString* key))[3] {
if ([key isEqualToString:#"key1"]) return valueArray1;
else return valueArray2;
}
Rather than Adding Array Directly as a value in NSDictionary make a custom class in which create variable of NSArray ... and set this class object as value like
NSDictionary *myDict = [NSDictionary dictionaryWithObjectsAndKeys:MyClassObj1,#"key1",
MyClassObj2,#"key2",nil];
where MyClassObj1 and MyClassObj2 are member of MyClass