您的位置:首页 > 移动开发 > IOS开发

ios developer tiny share-20160830

2016-09-01 16:21 197 查看
今天讲Objective的Accessor方法,即相当于java的getter和setter方法。

Use Accessor Methods to Get or Set Property Values

You access or set an object’s properties via accessor methods:

NSString *firstName = [somePerson firstName];
[somePerson setFirstName:@"Johnny"];


By default, these accessor methods are synthesized automatically for you by the compiler, so you don’t need to do anything other than declare the property using @property in the class interface.

The synthesized methods follow specific naming conventions:

The method used to access the value (the getter method) has the same name as the property. The getter method for a property called firstName will also be called firstName.
The method used to set the value (the setter method) starts with the word “set” and then uses the capitalized property name. The setter method for a property called firstName will be called setFirstName:.

If you don’t want to allow a property to be changed via a setter method, you can add an attribute to a property declaration to specify that it should be readonly:

@property (readonly) NSString *fullName;

As well as showing other objects how they are supposed to interact with the property, attributes also tell the compiler how to synthesize the relevant accessor methods.

In this case, the compiler will synthesize a fullName getter method, but not a setFullName: method.

Note: The opposite of readonly is readwrite. There’s no need to specify the readwrite attribute explicitly, because it is the default.

If you want to use a different name for an accessor method, it’s possible to specify a custom name by adding attributes to the property. In the case of Boolean properties (properties that have a YES or NO value), it’s customary for the getter method to start
with the word “is.” The getter method for a property called finished, for example, should be called isFinished.

Again, it’s possible to add an attribute on the property:
@property (getter=isFinished) BOOL finished;

If you need to specify multiple attributes, simply include them as a comma-separated list, like this:
@property (readonly, getter=isFinished) BOOL finished;

In this case, the compiler will synthesize only an isFinished method, but not a setFinished: method.

Note: In general, property accessor methods should be Key-Value Coding (KVC) compliant, which means that they follow explicit naming conventions.

See Key-Value Coding Programming Guide for more information.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息