should I always use self.classvariable?

When coding my iPhone app. Is it always a good practice when setting or getting values to use self? I seem to forget half of the time and recently have been tracking down a bug I believe is related to this.

Should I ALWAYS use self or are there cases when it's not necessary or would cause problems?

Edit: Here's an example of what I'm doing in the code

else if([CellIdentifier isEqualToString:@"Linked Item"]) {
        linkedItemLabel = [[UILabel alloc] initWithFrame:CGRectMake(120, 5, 160, 34)];
        linkedItemLabel.adjustsFontSizeToFitWidth = YES;
        linkedItemLabel.textColor = [UIColor blackColor];
        linkedItemLabel.font = [UIFont systemFontOfSize:17.0];
        linkedItemLabel.text = [storedValuesMutableArray objectAtIndex:7];
        linkedItemLabel.backgroundColor = [UIColor clearColor];
        linkedItemLabel.textAlignment = UITextAlignmentRight;
        [cell addSubview:linkedItemLabel];}

This is part of the code that sets up my tableviewcells for a form that needs to be filled. Should I be using self.linkedItemLabel or is this fine?

Answers


You have to understand that using self.property is a method call (getter or setter method), not a simple assignment.

You should use the ivar directly only inside the setter or getter body.

Reasons:

1/ Properties are meant to shield you from the retain-release hell. Let's imagine you have a "assign" property, you are using the ivar directly and then you decide changing it to "retain". What you get is a bug difficult to find.

2/ Setters and getters can do additional functionality (e.g. setter can add/remove observers to an object) or logging. If you are using the ivar directly you miss this special functionality.

3/ Setters and getters can be overriden in a subclass.

In small projects you can probably avoid most problems even if you are using ivars directly but on big projects, programmed by a team, you should use only self.property to reduce bugs and improve code maintainability. It's also a good idea to give your ivar a different name (like property_ or _property because you'll notice when you are using it without self..

If you are not writing a high performance game or mathematic algorithms, don't worry about worse performance when using self.property.


Need Your Help

While Loop Print List formatting

python string loops python-2.7 while-loop

I wanted to create a list of factors from any given number only using the formula below. I am not allowed to use list therefore, I have imitate using strings as follows:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.