ios developer tiny share-20160901

来源:互联网 发布:js validate 验证 编辑:程序博客网 时间:2024/04/30 04:33

今天讲Objective-C的synthesized,以及下划线的用法。

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:

- (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.

0 0