NSDictionary initWithObjectsAndKeys是否处理NULL/nil对象和NSString对象以外的对象

15 objective-c nsdictionary

我正在尝试初始化NSDictionary,但它给了我以下错误:

Program received signal:  “EXC_BAD_ACCESS”.
Run Code Online (Sandbox Code Playgroud)

这是我有问题的代码[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
Run Code Online (Sandbox Code Playgroud)

这里是Quiz.h文件供参考

@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
Run Code Online (Sandbox Code Playgroud)

我应该如何解决它,请帮助我,我是客观的新手,它让我疯狂.NSDictionary initWithObjectsAndKeys是否处理除string和null对象之外的对象?

Sta*_*glo 41

NSDictionary无法存储标量值(如BOOL,NSInteger等),它只能存储对象.您必须将标量值包装起来NSNumber以存储它们:

NSDictionary *qDictionary = [[NSDictionary alloc]
    initWithObjectsAndKeys:question,@"questionText",
                           [NSNumber numberWithInteger:questionId],@"questionId",
                           [NSNumber numberWithBool:userAnswer],@"userAnswer",
                           [NSNumber numberWithBool:correctAnswer],@"correctAnswer",
                           nil];
Run Code Online (Sandbox Code Playgroud)