14

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];
Flocked
  • 1,898
  • 2
  • 36
  • 57

2 Answers2

40

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];
Aleksejs Mjaliks
  • 8,647
  • 6
  • 38
  • 44
  • 2
    You can only store Objective-C objects in most of the Cocoa collection classes, you can't store primitive types. – Rob Keniger Feb 23 '10 at 23:55
4

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

Nyx0uf
  • 4,609
  • 1
  • 25
  • 26