我看过很多帖子,其中介绍了从数组中正确删除对象的各种方法,但我不确定哪种方法最适合我的实例。我正在从一个 plist 中加载一个字典,这个字典包含许多数组,这些数组包含另一个字典。所以我有 3 个存储设备设置,1 个用于保存整个字典,另一个用于数组,最后一个字典用于保存数组中的对象:
标题:
NSMutableDictionary *questionsDictionary;
NSMutableArray *questionsArray;
NSDictionary *currentQuestion;
@property (nonatomic, retain) NSMutableDictionary *questionsDictionary;
@property (nonatomic, retain) NSMutableArray *questionsArray;
@property (nonatomic, retain) NSDictionary *currentQuestion;
所以我的第一个问题是关于上面的,(非原子的,保留的)正确的东西用于下面的代码。
接下来我从 plist 加载我的字典:
.m:
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:@"MultipleChoice.plist"];
self.questionsDictionary = [[NSDictionary dictionaryWithContentsOfFile:finalPath] retain];
然后我根据我的问题类型设置我的问题数组:
- (void)setupQuestionType : (NSString *)qType
{
if ([self.questionsDictionary objectForKey:qType])
{
self.questionsArray = [self.questionsDictionary objectForKey:qType];
[self pickRandomQuestion];
}
}
最后(这是我得到错误的地方),我想从这个问题类别中随机抓取一个问题:
// Pick a random question number based upon amount of questions
int randomQuestionNum = [[NSNumber numberWithInt:(arc4random() % [self.questionsArray count])] intValue];
// Grab the dictionary entry for that question
currentQuestion = [self.questionsArray objectAtIndex:randomQuestionNum];
// Remove the question from the available questions
[self.questionsArray removeObjectAtIndex:randomQuestionNum]; (Error here)
// Set the question text
self.question.text = [currentQuestion objectForKey:kQuestionkey];
现在,如果我注释掉 removeObjectAtIndex 行,那么代码可以正常运行,并且我的问题会显示在屏幕上。这让我相信它不是空指针。所以合乎逻辑的答案指向 self.questionsArray 不是 NSMutableArray 的事实。所以我在设置数组时尝试了以下操作:
- (void)setupQuestionType : (NSString *)qType
{
if ([self.questionsDictionary objectForKey:qType])
{
NSMutableArray *temp = (NSMutableArray *)[self.questionsDictionary objectForKey:qType];
self.questionsArray = (NSMutableArray *)temp;
[self pickRandomQuestion];
}
}
纯粹是为了看看我是否可以对其进行类型转换,但错误仍然存在。任何人都可以阐明我做错了什么,或者可以采取的最佳方法吗?
最佳答案
不要将 NSArray 类型转换为 NSMutableArray。相反:
NSArray *temp = [self.questionsDictionary objectForKey:qType];
self.questionsArray = [NSMutableArray arrayWithArray:temp];
// code not tested.
关于ios - NSMutableArray removeObjectAtIndex 导致意外的 SIGABRT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8448416/