崩溃迭代数组

时间:2014-05-31 10:30:44

标签: objective-c arrays

我试图简单地打印出数组的内容。

//initialization, ...

    NSArray *stockprices = [NSArray arrayWithObjects:@[stock1,stock2,stock3], nil];

    for (BNRStockHolding *stock in stockprices) {
//            says that there are 3 objects in stock and crashes.
//            tried to check -> isMemberOfClass:BNRStockHolding in an if before and got 'unexpected interface name'.
        NSLog(@"Purchase Price: %.02f \n Shares: %d \n Current Price: %.02f \n \n \n \n", [stock purchasePrice], [stock numberOfShares],[stock currentSharePrice]);

3 个答案:

答案 0 :(得分:3)

当你这样做时:

NSArray *stockprices = [NSArray arrayWithObjects:@[stock1, stock2, stock3], nil];
//is same as
NSArray *stockprices = [NSArray arrayWithObjects:[NSArray arrayWithObjects:stock1, stock2, stock3, nil], nil];
//or
NSArray *stockprices = [NSArray arrayWithObjects:[[NSArray alloc] initWithObjects:stock1, stock2, stock3, nil], nil];

因此,您基本上创建了一个数组,其第0个元素是一个数组,因为@[stock1,stock2,stock3]本身会创建一个数组。


取而代之的是:

NSArray *stockprices = [NSArray arrayWithObjects:stock1, stock2, stock3, nil];

NSArray *stockprices = @[stock1,stock2,stock3];

答案 1 :(得分:0)

您在这里创建一个包含代码的数组数组:

 NSArray *stockprices = [NSArray arrayWithObjects:@[stock1,stock2,stock3], nil];

您可以简单地写一下:

NSArray *stockprices = @[stock1,stock2,stock3];

答案 2 :(得分:0)

你在数组中使用数组; Parent Array有一个对象,子数组有三个stock对象。如果你得到[parentArray objectAtIndex:0];它会工作正常;但是如果你做[parentArray objectAtIndex:1];应用程序将崩溃,因为父数组只有一个对象。 它可以帮助您调查问题。