chris
chris

Reputation: 4351

EXC_BAD_ACCESS when not using self

I got nabbed by the following bug again and would like some clarification to exactly why it is a bug.

I have a simple UITableView that loads some data:

// myclass.h
@property (nonatomic, retain) NSArray *myData

// myclass.m
@synthesize myData;

- (void) viewDidLoad {
  ...
  myData = someDataSource // note the lack of self
}

- (UITableViewCell *) cellForRowAtIndexPath ... {
   ...
   cell.textLabel.text = [self.myData objectAtIndex:indexPath.row];  // EXC_BAD_ACCESS
}

The table first loads fine, but when scrolling up enough that one of the cells is totally out of the view I then get the EXC_BAD_ACCESS error.

Am I missing something in regards to @property retain. My understanding is that it releases anything that the pointer was previously pointing to before the reassignment. If I am correct then why would not using self. cause any problems?

Thanks for the help.

**** Update

Why is is that in all the examples that I have checked with to the release of objects within the dealloc method without the self?

- (void) dealloc { 
  [someArray release]; 
  [someTableView release];
}

Upvotes: 0

Views: 264

Answers (2)

Madhup Singh Yadav
Madhup Singh Yadav

Reputation: 8114

In case of

myData = someDataSource;

you are giving the reference of someDataSource (a local variable or limited scope variable) to myData. Now as soon as someDataSource goes out of scope it gets released and as you have passed its reference to myData it also gets released.

now in the case of

self.myData = someDataSource;

the value of someDataSource is assigned to myData. Hence whatever happens to someDataSource myData will retain the value.

You can also do it otherwise:

myData = [someDataSource retain];

Hope this helps.

Thanks,

Madhup

Upvotes: 1

Grant Paul
Grant Paul

Reputation: 5902

If you don't use self., you are directly assigning to the instance variable myData, which has nothing to do with the property myData.

self.myData is just syntactic sugar for [self myData] or [self setMyData:newValue], and the synthesized property just creates the -myData and -setMyData: methods.

The instance variable is just a variable, nothing more. While it may have the same name, assigning to it or reading from it it is just like accessing any variable: nothing is retained, released, or in other ways modified besides the assignment.

Upvotes: 1

Related Questions