我创建了一个数组,我存储了5个字符串和1个int,然后我将其存储到另一个数组中。
我正在尝试访问并打印出一个数组,但它只给了我这个:
2016-01-11 18:47:55.429 quizgame-chrjo564 [3378:145727](null)
我尝试过这些替代方案:
NSLog(@"%@", [dataArray objectAtIndex:0]);
NSLog(@"%@", dataArray[0]);
这是我的所有代码:
#import "ViewController.h"
@interface ViewController ()
{
NSMutableArray *_questions;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self quizStart];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)prepQuestions {
[self question:@"Vad heter jag?" answer1:@"Anton" answer2:@"Christian" answer3:@"Christoffer" answer4:@"Simon" correctAnswer:2];
}
- (void)question:(NSString *)q answer1:(NSString *)a1 answer2:(NSString *)a2 answer3:(NSString *)a3 answer4:(NSString *)a4 correctAnswer:(NSInteger)c {
NSArray *tmpArray = [NSArray arrayWithObjects:
[NSString stringWithString:q],
[NSString stringWithString:a1],
[NSString stringWithString:a2],
[NSString stringWithString:a3],
[NSString stringWithString:a4],
[NSNumber numberWithInteger:c],nil];
NSLog(@"%@", q);
[_questions addObject:tmpArray];
}
- (void)quizStart {
[self prepQuestions];
NSArray *dataArray = [_questions objectAtIndex:0];
NSLog(@"%@", [dataArray objectAtIndex:0]);
}
@end
提前致谢
*更改后更新错误:
2016-01-11 19:28:00.816 quizgame-chrjo564 [3901:202243] - [__ NSCFConstantString objectAtIndex:]:无法识别的选择器发送到实例0x75030
2016-01-11 19:28:00.822 quizgame-chrjo564 [3901:202243] ***由于未捕获的异常'NSInvalidArgumentException'终止应用程序,原因:' - [__ NSCFConstantString objectAtIndex:]:无法识别的选择器发送到实例0x75030'
答案 0 :(得分:2)
您永远不会初始化_questions
。
改变这个:
[_questions addObject:tmpArray];
为:
if (!_questions) {
_questions = [NSMutableArray array];
}
[_questions addObject:tmpArray];
此外,这里提出了使您的代码更清晰,更易于阅读的建议。
stringWithFormat:
。换句话说,您question:...
方法可以写成:
- (void)question:(NSString *)q answer1:(NSString *)a1 answer2:(NSString *)a2 answer3:(NSString *)a3 answer4:(NSString *)a4 correctAnswer:(NSInteger)c {
NSArray *tmpArray = @[ q, a1, a2, a3, a4, @(c) ];
NSLog(@"%@", q);
if (!_questions) {
_questions = [NSMutableArray array];
}
[_questions addObject:tmpArray];
}