Programming with Objective-C ----------Encapsulating Data

Most Properties Are Backed by Instance Variables

By default, a readwrite property will be backed by an instance variable, which will again be synthesized automatically by the compiler.

An instance variable is a variable that exists and holds its value for the life of the object. The memory used for instance variables is allocated when the object is first created (through alloc), and freed when the object is deallocated.

Unless you specify otherwise, the synthesized instance variable has the same name as the property, but with an underscore prefix. For a property called firstName, for example, the synthesized instance variable will be called _firstName.

Although it’s best practice for an object to access its own properties using accessor methods or dot syntax, it’s possible to access the instance variable directly from any of the instance methods in a class implementation. The underscore prefix makes it clear that you’re accessing an instance variable rather than, for example, a local variable:

- (void)someMethod {
    NSString *myString = @"An interesting string";
 
    _someString = myString;
}

In this example, it’s clear that myString is a local variable and _someString is an instance variable.

In general, you should use accessor methods or dot syntax for property access even if you’re accessing an object’s properties from within its own implementation, in which case you should use self:

一般来说,你应该使用访问器方法或者点语法来存取属性,即使你在一个对象自己的声明部分访问某个属性也应该遵循这个原则,当然这时你应该用self:

- (void)someMethod {
    NSString *myString = @"An interesting string";
 
    self.someString = myString;
  // or
    [self setSomeString:myString];
}

The exception to this rule is when writing initialization, deallocation or custom accessor methods, as described later in this section.

 

 

posted @ 2016-03-24 13:58  EricSun  阅读(151)  评论(0编辑  收藏  举报