Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

App crashes when I create a NSDictionary with integer as Object

Always when I try to set an integer as Object in a NSDictionary the program crashes without a message (nothing in the console). What is wrong in this code? :

NSString *string = @"foo";
int number = 1;

NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                        string, @"bla1", number, @"bla2",nil];
like image 958
Flocked Avatar asked Feb 23 '10 23:02

Flocked


2 Answers

Use NSNumber instead of raw int:

Modern Objective-C:

NSString *string = @"foo";
NSNumber *number = @1;

NSDictionary *params = @{@"bla1": string, @"bla2": number};

Old style:

NSString *string = @"foo";
NSNumber *number = [NSNumber numberWithInt:1];

NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                    string, @"bla1", number, @"bla2",nil];
like image 66
Aleksejs Mjaliks Avatar answered Nov 13 '22 04:11

Aleksejs Mjaliks


In a dictionary you have to store objects, not primary types like int, char etc..

like image 35
Nyx0uf Avatar answered Nov 13 '22 03:11

Nyx0uf