views:

373

answers:

3

ok. I have a really odd and mind boggling problem. I have two class files, both of which are NSObject inheritors. The series of code is as follows

CustomClass *obj;
obj = [[CustomClass alloc] init];
[myArray addObject:obj]; <--------Immediately after this line if I hover over the array it shows it as having 1 object that is out of scope.

If I hover over both objects they both have what look to be initialized memory locations so I really have no idea what is going on here. Thanks in advance.

UPDATE: There is a place in the code where I call a function repeatedly with a timer. Inside of the timer I do the following.

CustomClass *obj = [CustomClass alloc];
obj = [myArray objectAtIndex:0];
obj.var += 10; [obj release];

On the line obj.var I get a EXC_BAD_ACCESS error. I am probably doing the alloc and releases incorrectly considering it is called repeatedly but I have tried everything I can think of.

A: 

I think you are referring to the XCode debugging feature which shows you the content of variables.

I did encounter the same issue as well, and what I'm sure of is that this is generally not a problem with your code.

Now what I'm not sure of is why this happens, but I believe that the variable obj in your example is not used after the call anymore. This means the compiler reuses the place where this reference was stored, thus the debugger could "lose" the pointer to your variable and it will appear as out of scope (but I am no expert in the ways of gcc or the debugger, so I could be wrong here).

frenetisch applaudierend
A: 

This code is wrong:

CustomClass *obj = [CustomClass alloc];
obj = [myArray objectAtIndex:0];
obj.var += 10; [obj release];

What you are doing is allocing a new CustomClass (without initializing it, which should never be done), then replacing it with the object from the array (leaking the old one), and then afterwards releasing the object from the array. This will cause a crash the next time the object in the array is accessed. Instead, just say:

CustomClass *obj = [myArray objectAtIndex:0];
obj.var += 10;

Don't release unless you retain in advance. (See the Cocoa memory management guide for more information).

eman
A: 

This isn't the problem you are referring to, but please don't do this:

CustomClass *obj = [CustomClass alloc];

Never issue an alloc without an init of some sort. Also, in the context of the code you posted it isn't required, as you assign a value to obj on the next line.

Then [obj release]; isn't required, as you haven't retained the obj value you obtain from myArray. You are probably doing it because of the preceding alloc, which as I have said isn't required.

if a reference to obj.var is causing a BAD_ACCESS, then either obj or var has been dealloced by code elsewhere, almost certainly var.

Paul Lynch