我正在尝试初始化NSDictionary,但它给了我以下错误:
Program received signal: “EXC_BAD_ACCESS”.
这是我有问题的代码[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
这是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
我该如何解决,请帮助我,我是客观的新手,这让我疯狂。 NSDictionary initWithObjectsAndKeys是否处理除string和null对象以外的对象?
答案 0 :(得分:40)
NSDictionary
无法存储标量值(如BOOL,NSInteger等),它只能存储对象。您必须将标量值包装到NSNumber
中以存储它们:
NSDictionary *qDictionary = [[NSDictionary alloc]
initWithObjectsAndKeys:question,@"questionText",
[NSNumber numberWithInteger:questionId],@"questionId",
[NSNumber numberWithBool:userAnswer],@"userAnswer",
[NSNumber numberWithBool:correctAnswer],@"correctAnswer",
nil];