当我在NSMutableArray上调用一个方法时,我收到错误“无法识别的选择器发送到实例”

时间:2012-06-08 18:08:16

标签: objective-c nsmutablearray shuffle

我有一个可变数组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; // " "
}

1 个答案:

答案 0 :(得分:3)

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

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

但如果你想把它拿出去,你可能会更好地放入NSMutableArrays。