Does NSDictionary initWithObjectsAndKeys handles NULL/nil objects and other than NSString objects

user517491 picture user517491 · Mar 19, 2012 · Viewed 31.4k times · Source

I am trying to initialize NSDictionary but it gives me following error:

Program received signal:  “EXC_BAD_ACCESS”.

Here is my problematic code[Quiz.m]:

@implementation Quiz

@synthesize question;
@synthesize correctAnswer;
@synthesize userAnswer;
@synthesize questionId;

-(NSString*) getAsJsonString
{   
    // Following line gives the error
    NSDictionary *qDictionary=[[NSDictionary alloc] initWithObjectsAndKeys:question,@"questionText",questionId,@"questionId",userAnswer,@"userAnswer",correctAnswer,@"correctAnswer",nil];

    ..............
    .........
    ............
    return jsonString;
}
@end

And here is Quiz.h file for reference

@interface Quiz : NSObject {

@public
    NSString * question;
    BOOL correctAnswer;
    BOOL userAnswer;
    NSInteger questionId;
}

@property (nonatomic,retain) NSString * question;
@property (nonatomic, assign) NSInteger questionId;
@property (nonatomic,assign) BOOL correctAnswer;
@property (nonatomic,assign) BOOL userAnswer;

- (NSString*) getAsJsonString;
@end

How should I fix it, please help me, I am new to objective c and it is driving me nuts. Does the NSDictionary initWithObjectsAndKeys handle objects other than string and null objects?

Answer

Stanislav Yaglo picture Stanislav Yaglo · Mar 19, 2012

NSDictionary cannot store scalar values (like BOOL, NSInteger, etc.), it can store only objects. You must wrap your scalar values into NSNumber to store them:

NSDictionary *qDictionary = [[NSDictionary alloc]
    initWithObjectsAndKeys:question,@"questionText",
                           [NSNumber numberWithInteger:questionId],@"questionId",
                           [NSNumber numberWithBool:userAnswer],@"userAnswer",
                           [NSNumber numberWithBool:correctAnswer],@"correctAnswer",
                           nil];