user440096
user440096

Reputation:

Why use 'self.' when its not forced?

I noticed a difference between the way I code (badly ;) ) and the code I see from others.

Can anybody explain why I see some people using

self.varname.anotherpropertie

When

varname.anotherpropertie

Seems to work just as well. I dont use self. a lot in my code. I'm wondering is this very bad or is there something that I need to learn to understand why its used so much by most people?

Thanks again, -Code

Upvotes: 0

Views: 217

Answers (2)

slycrel
slycrel

Reputation: 4285

One gotcha that I've run into is the retain vs non-retain with properties.

So if you have a retained property like this:

@property (nonatomic, retain) NSString* myStr;
@synchronized myStr;

and you do something like this:

- (void) myMethod:(NSString*)inStr
{
    myStr = inStr;
}

In this example you will not actually retain the string as your property is not invoked. If you change the assignment line to use the property (by using "self.") then the string would be retained (and the previous string would be released if non-nil).

self.myStr = inStr;

It takes some getting used to that properties are method calls, but once you start seeing them as such then the "self." syntax becomes much more clear. Hope that helps some.

Upvotes: 2

Chuck
Chuck

Reputation: 237010

They are different things. In a class where you have an instance variable named foo with a declared property also named foo, writing simply foo accesses the instance variable while self.foo goes through the getter method for the property (which might just return the instance variable or it might do more).

I'd suggest taking a look at the Declared Properties chapter of Apple's The Objective-C Programming Language for a full explanation of how it works and when to choose which option.

Upvotes: 6

Related Questions