bugfixr
bugfixr

Reputation: 8077

Why is my variable out of scope?

I have an NSMutableArray defined in my AppDelegate class:

NSMutableArray *devices;

I populate the array from a class in the didFinishLaunchingWIthOptions method:

Devices *devs = [[Devices alloc] init];
self.devices = [devs getDevices];

The getDevices method parses a json string and creates a Device object, adding it to the array:

NSMutableArray *retDevices = [[NSMutableArray alloc] initWithCapacity:[jsonDevices count]];

for (NSDiectionary *s in jsonDevices) {
    Device *newDevice = [[Device alloc] init];
    device.deviceName = [s objectForKey:@"name"];

    [retDevices addObject: newDevice];
}

return retDevices;

I then use the AppDelegate class's devices array to populate a tableView. As seen in the cellForRowAtIndexPath method:

AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
Device *d = (Device *)[appDelegate.devices objectAtIndex:indexPath.row];

cell.label.text = d.deviceName;

When the tableview is populated initially, it works. But when I scroll through the list, and the cellForRowAtIndexPath is executed again, d.deviceName throws an error because it has gone out of scope.

Can anyone help me understand why? I'm sure it has something to do with an item being released... but... ??

Thanks in advance.

Upvotes: 1

Views: 503

Answers (1)

Jeremy W. Sherman
Jeremy W. Sherman

Reputation: 36143

If it is indeed a problem with memory management, answering these questions should lead you to an answer:

  • Is deviceName declared as a retain or copy property by the Device interface declaration?
  • Is -deviceName synthesized? If not, how is it implemented?
  • Is devices declared as a retain property by the app delegate class's interface declaration?
  • Is devices synthesized? If not, how is it implemented?

Of course, it might not be a problem with memory management. It would help a lot if you were to provide the actual text of the error message and any provided backtrace.

Upvotes: 4

Related Questions