Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert NSArray into an NSDictionary

If I have a NSArray, can I put this into a NSDictionary? If so, how can I do this?

like image 300
zp26 Avatar asked Jul 31 '10 09:07

zp26


People also ask

How do you declare NSArray in Objective C?

In Objective-C, the compiler generates code that makes an underlying call to the init(objects:count:) method. id objects[] = { someObject, @"Hello, World!", @42 }; NSUInteger count = sizeof(objects) / sizeof(id); NSArray *array = [NSArray arrayWithObjects:objects count:count];

How do you set a value in NSDictionary?

You have to convert NSDictionary to NSMutableDictionary . You have to user NSMutableDictionary in place of the NSDictionary . After that you can able to change value in NSMutableDictionary .

What is the difference between NSMapTable vs NSDictionary?

NSDictionary / NSMutableDictionary copies keys, and holds strong references to values. NSMapTable is mutable, without an immutable counterpart. NSMapTable can hold keys and values with weak references, in such a way that entries are removed when either the key or value is deallocated.

What is the difference between NSDictionary and NSMutableDictionary?

Main Difference is:NSMutableDictionary is derived from NSDictionary, it has all the methods of NSDictionary. NSMutableDictionary is mutable( can be modified) but NSDictionary is immutable (can not be modified).


2 Answers

An NSDictionary can use any objects as values, and any objects that conforms to NSCopyingas keys. So in your case:

NSArray * myArray = [NSArray arrayWithObjects:@"a", @"b", @"c"];

NSDictionary * dict = [NSDictionary dictionaryWithObject:myArray forKey:@"threeLetters"];

NSMutableDictionary * mutableDict = [NSMutableDictionary dictionaryWithCapacity:10];
[mutableDict setObject:myArray forKey:@"threeLetters"];
like image 117
Felixyz Avatar answered Nov 12 '22 11:11

Felixyz


If you start with myArray:

NSArray *myArray = [NSArray arrayWithObjects:...];

If you want a mutable dictionary:

NSMutableDictionary *myMutableDictionary = [NSMutableDictionary dictionary];
[myMutableDictionary setObject:myArray forKey:@"myArray"];

If you just want a dictionary:

NSDictionary *myDictionary = [NSDictionary dictionaryWithObject:myArray forKey:@"myArray"];
like image 20
Alex Reynolds Avatar answered Nov 12 '22 11:11

Alex Reynolds