tba
tba

Reputation: 6571

EXC_BAD_ACCESS with Objective-C Properties

In my iPhone application, I have the following line in a constructor:

self.myVar = myVar_in;

where myVar is a property and myVar_in is a parameter passed to the constructor.

When I run the code, I get an EXC_BAD_ACCESS error on this line. However, when I replace the line with:

[myVar release];
[myVar_in retain];
myVar = myVar_in;

the code runs fine. My property is declared like this: NSNumber *myVar; ... @property (retain) NSNumber *myVar;

The error is consistent and I'm positive it's not a variable scope issue. Can someone explain this behavior?

EDIT: I've confirmed that myVar_in is valid right before the line(s) are executed. Here's the actual code, although it won't help much:

-(GetAddressRequestHelper*)initWithRequest:(ClientRequest*)request delegate:(id<ServerResponseDelegate>)delegate number:(NSNumber*)myVar_in location:(CLLocation*)location {
    self = [super initWithRequest:request delegate:delegate];

    if( self ) {
        // same behavior even if this line is uncommented!!!
        myVar_in = [NSNumber numberWithInt:123];

        // prints "myVar_in is 123"
        NSLog(@"myVar_in is %@",myVar_in);          

        // doesn't throw exception
        /*[myVar release];
          [myVar_in retain];
          myVar = myVar_in;*/

        // throws exception
        self.myVar = myVar_in;

        self.location=location;
    }
    return self;
}

EDIT2: I've found I still get the behavior when I explicitly initialize the param with myVar_in = [NSNumber numberWithInt:123];!

Thanks

Upvotes: 2

Views: 2751

Answers (3)

Peter N Lewis
Peter N Lewis

Reputation: 17811

One critical difference between this code:

[myVar release];
[myVar_in retain];
myVar = myVar_in;

and this code:

self.myVar = myVar_in;

is the use of self to call the method (setMyVar).

Almost certainly your object has been incorrectly created/allocated and self is a random value (in which case the assignment of myVar = myVar_in is scribling over random memory).

Post the code showing your object creation/init call and for good how measure how myVar_in gets its value. Also post your init code (you can (very carefully) delete extraneous code, but since this is a weird case, any extraneous code might well be relevent...

Upvotes: 2

Jorge Israel Pe&#241;a
Jorge Israel Pe&#241;a

Reputation: 38626

Make sure myVar_in is actually initialized. Would you mind posting the code where you initialize myVar_in and call the initializer method?

Upvotes: 0

lostInTransit
lostInTransit

Reputation: 71047

Try using the auto-generated setter method if you have @property and @synthesize statements for your variable. That will make sure the value of myVar_in is retained when assigned to myVar ([self setMyVar:myVar_in])

The error that you see is probably because myVar_in is released by the time you use it.

Upvotes: 0

Related Questions