Andrey Chernukha
Andrey Chernukha

Reputation: 21808

Difference between accessing class data members using self and not using it

if i have an outlet variable which i've declared as a property

@interface MyClass:UIViewController
{
IBOutlet UILabel *label;
}
@property (nonatomic,retain) IBOutlet UILabel *label;

is there a difference between doing this

[label release];

and this

[self.label release];

Upvotes: 0

Views: 171

Answers (2)

Jaffa
Jaffa

Reputation: 12719

Yes there is a difference, when you're using a property, you're implicitly using an accessors, that is to say :

- (UILabel*)label;

So some additional behavior could be implemented in the getter, such as sanity check and so on.

Here you declared your property as retain :

@property (nonatomic,retain) IBOutlet UILabel *label;

So the setter will automatically retain the value to set, and release the old one.

Using :

[self.label release];

You are doing something hazardous, as you release the object which is retained by the accessors. So when you do something like :

self.label = nil;

It calls the method - (void) setLabel:(UILabel*)label which will release the actual object! So the object will be released twice, leading to freed object access!

If you declare a property, try to only use your member through this property !

You can also use some implicit member declaration, such as :

@interface MyClass

@property (nonatomic, retain) UILabel* label;

@end

@synthesize label = _label;

A member UILabel* _label will be implicitly declared :)

Upvotes: 1

Jef
Jef

Reputation: 2134

Yes. in the second case you're using accessory methods. You should use either the first or self.label = nil; not [self.label release];

Why do you want to release an interface element?

Upvotes: 0

Related Questions