Can anyone tell me the functional difference between this code…
for (int i = 0; i < productsJSON.count; i++)
{
prod = [[Product alloc] init];prod.ItemID = [[productsJSON valueForKey:@"ItemID"] objectAtIndex:i]; prod.Name = [[productsJSON valueForKey:@"Name"] objectAtIndex:i]; [self.products addObject:prod];}
[super viewDidLoad];
… and this code…
prod = [[Product alloc] init];
prod.ItemID = @”SB4UL”;
prod.Name = @”#4 Split Bolt- UL Approved”;
[self.products addObject:prod];prod = [[Product alloc] init];
prod.ItemID = @”PVSC07GGUL”;
prod.Name = @”I Beam Grounding Clamp, UL”;
[self.products addObject:prod];[super viewDidLoad];
… when prod.ItemID and prod.Name are NSString properties, and the values assigned in the “for” loop have — after exiting the loop — been visually confirmed to be the same as values assigned by the other block of code?
For all I can tell, both behave exactly the same until the moment I actually try to put the results to practical use in my app. The code appears in the viewDidLoad method of a UITableViewController. It gets passed to the cellForRowAtIndexPath method, where I can confirm that the values arrive intact. Then we step straight into the code block…
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@”ProductCell”];
Product *product = [self.products objectAtIndex:indexPath.row];
cell.textLabel.text = product.Name;
If I’ve commented out the first block and run the second, the view displays flawlessly.
If I’ve commented out the second block and run the first, the program dies every time at “cell.textLabel.text = product.Name”, and it displays a seemingly random error message (e.g.: “Thread 1: EXEC_BAD_INSTRUCTION (code=EXC_1386_INVOP, subcode=0x0)” or “Thread 1: signal SIGABRT” or “Thread 1:EXC_BAD_ACCESS(code=1, adress=0xf069996f”).
@Joe was right — I just had to dig deeper to find it. The array is persistent, but the properties on the Product class were not.
The productsJSON code is a variable specific to viewDidLoad. It died between methods, and the reference in the Product objects went bad.