When to access properties with 'self'

有些话、适合烂在心里 提交于 2019-11-26 16:43:51

you almost always want to access variables using the synthesized setters/getters, even if you aren't doing anything special with them at the moment.

if as your application develops, you find that you need to be doing further validation/formatting of variables, then you can just implement the required setter/getter method, and if you have used the synthesised methods this code will get called.

this is generally a good habit to get into.

If you declare your property like so:

@property (nonatomic, retain) NSMutableArray *myArray;

The generated setter will automatically retain the value that gets passed in. That's why you'll see this sometimes in Apple sample code:

self.myArray= [[NSMutableArray alloc] init]:
[self.myArray release];

"[self.myArray release]" is required because the retain count is two after the first line. Releasing it insures that it is down to 1 (where it should be).

If I am just using the automatically generated setters, I will not use them when working from inside of the class. It is just much simpler for me to do:

myArray = [[NSMutableArray alloc] init];

vs. the example above.

My two cents.

Depends. If your instance variables are dumb, it's fine to access them directly. But the reason most of us like to access members through properties is that we can change something about the logic of that member, and things will still work.

For example, sometimes you'll want to change a class to load something lazily, as opposed to immediately. If you're already using properties to access your instance variable, then you can just edit the accessor method and everything should just work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!