0

我有一个可变数组, allRows. 在一个循环中,我将allRows(也包含数组)的每个索引分配给另一个数组。但是,当shuffle对该数组调用该方法时,程序会崩溃。该方法是一个类别,适用于其他数组;只是没有row

- (void)selectQuestions {

self.quizQuestions = [[NSMutableArray alloc] init];

for (int j = 0; j<self.maxRowNumber; j++) {
    //shuffle each row
    NSMutableArray *row = [allRows objectAtIndex:j];
    [row shuffle];

}

@implementation NSMutableArray (shuffle)

-(void) shuffle {

NSUInteger count = [self count];
for (NSUInteger i = 0; i< count; ++i) {

    int nElements = count - i;
    int randomIndex = arc4random() % (nElements) + i ;
    [self exchangeObjectAtIndex:i withObjectAtIndex:randomIndex];
}
}

编辑

allRows在类的 init 方法中实例化。我添加了整个方法,以防您需要查看其他任何内容。

- (id)init {
self = [super init];
if (self) {

    // Question, Reactants, Products, Elements
    NSArray *R1Q1 = [[NSArray alloc] initWithObjects:@"Methanol is burned completely in air", @"2CH₃OH(l) + 3O₂(g)", @"2CO₂(g) + 4H₂O", @"C,H,O", nil];
    NSArray *R1Q2 = [[NSArray alloc] initWithObjects:@"Ammonia is burned in excess oxygen gas", @"4NH₃(g) + 7H₂O(l)", @"4NO₂(g) + 6H₂O(l)", @"N,H,O", nil];
    NSArray *R1Q3 = [[NSArray alloc] initWithObjects:@"Hydrogen sulfide gas is burned in excess oxygen gas", @"2H₂S(g) + 3O₂(g)", @"CO₂(g) + 2SO₂(g)", @"H,S,O", nil];

    NSArray *R2Q1 = [[NSArray alloc] initWithObjects:@"Solid potassium is added to a flask of oxygen gas", @"K(s) + O₂(g)", @"KO₂(s)", @"K,O", nil];
    NSArray *R2Q2 = [[NSArray alloc] initWithObjects:@"Sodium metal is dropped into a flask of pure water", @"2Na(s) + H₂O(l)", @"2Na⁺(aq) + 2OH⁻(aq) + H₂(g)", @"Na,H,O", nil];
    NSArray *R2Q3 = [[NSArray alloc] initWithObjects:@"A piece of lithium is heated strongly in oxygen", @"4Li(s) + O₂(g)", @"2Li₂O(s)", @"Li,O", nil];

    NSArray *R3Q1 = [[NSArray alloc] initWithObjects:@"Solutions of potassium chloride and silver nitrate are mixed", @"Ag⁺(aq) + Cl⁻(aq)", @"AgCl(s)", @"K,Cl,Ag,N,O", nil];
    NSArray *R3Q2 = [[NSArray alloc] initWithObjects:@"Solutions of iron(III) nitrate and sodium hydroxide are mixed", @"Fe³⁺(aq) + 3OH⁻(aq)", @"Fe(OH)₃(s)", @"Fe,N,O,Na,H", nil];
    NSArray *R3Q3 = [[NSArray alloc] initWithObjects:@"Solutions of nickel iodide and barium hydroxide are mixed", @"Ni²⁺(aq) + 2OH⁻(aq)", @"Ni(OH)₂(s)", @"Ni,I,Ba,OH", nil];

    row1 = [[NSArray alloc] initWithObjects:R1Q1, R1Q2, R1Q3, nil];
    row2 = [[NSArray alloc] initWithObjects:R2Q1, R2Q2, R2Q3, nil];
    row3 = [[NSArray alloc] initWithObjects:R3Q1, R3Q2, R3Q3, nil];
    //add rest

    allRows = [[NSMutableArray alloc] initWithObjects:row1, row2, row3, nil];
    self.maxRowNumber = 3; //hypothetical
    self.questionsPerRow = 2; // " "
}
4

1 回答 1

3

根据您发布的错误,它看起来[allRows objectAtIndex:j]返回的是 NSArray 而不是 NSMutableArray。快速修复是这样的。

NSMutableArray *row = [NSMutableArray arrayWithArray:[allRows objectAtIndex:j]];

但是如果你想拿出一个 NSMutableArrays 可能会更好。

于 2012-06-08T18:15:18.333 回答