views:

34

answers:

1

I have been having some problems with some variables inside a class being deleted lately. Here is how I declare:

MyClass *myClass;
-(void)viewDidLoad {
myClass = [MyClass new];
//something using my class

then when I call a function later that uses an array and a dictionary inside the class.

[myClass doSomething];

Here is the code I get in the console.

-[CFArray objectAtIndex:]: message sent to deallocated instance 0x5d1f370

Here is how I declare the area in the Class

NSArray *myArray;
-(void)doSomething{
myArray = [NSArray array];

Then later I just perform a valid objectAtIndex on the array. Someone please help me.

+1  A: 

Looks like you aren't retaining the objects, so by the time you actually use them they are deallocated, since they are auto-released. Either use synthesized properties or add a retain message to each initialization, i.e., [[NSArray array] retain] and [[MyClass new] retain], be sure to release when appropriate. I recommend using properties instead though, it's cleaner.

EDIT: Thanks to imaginaryboy: the [NSArray array] call releases an autoreleased object, so you have to retain that, by changing it to [NSArray new] for example. Leave [MyClass new] as it already returns a retained object.

Jorge Israel Peña
The array is the only thing that is the problem. [NSArray array] returns an autoreleased object. [MyClass new] returns an object that has already been retained. So leave the [MyClass new] alone, and swap the [NSArray array] for either @Blaenk's suggestion of [[NSArray array] retain] or more usually [NSArray new] or [NSArray alloc] init].
imaginaryboy
thanks for the clarification imaginaryboy, I'll add it into my response
Jorge Israel Peña
I do this in my interface.@property (nonatomic, retain) NSArray *myArray;
pki
I think it could also be a about where and how I am defining a variable. How would you guys define a variable that you needed for the lifetime of a class. In what blocks would decelerations and initialization be in?
pki
Thanks both of you for helping.
pki
for the lifetime of the object (I assume you mean object and not class, since a class does not 'live' like an object does), you are doing it correctly. an instance variable in other words, in the interface.
Jorge Israel Peña