vale
vale

Reputation: 1426

Crash iterating through an array

I'm trying to simply print out the contents of an array.

//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]);

Upvotes: 0

Views: 69

Answers (3)

msmq
msmq

Reputation: 1328

You are using array within array; Parent Array has one object and child array has three stock objects. If you will get [parentArray objectAtIndex:0]; it will work OK; But if you will do [parentArray objectAtIndex:1]; App will crash because, parent array just have one object. It may help you to investigate problem.

Upvotes: 0

Pawan Sharma
Pawan Sharma

Reputation: 3334

You are creating here an array of array with your code code:

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

You can simply write :

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

Upvotes: 0

mixel
mixel

Reputation: 25846

When you do:

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];

So, you're basically creating an array whose 0th element is an array because @[stock1,stock2,stock3] itself creates an array.


Instead do:

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

or

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

Upvotes: 3

Related Questions