ios developer tiny share-20160830

今天讲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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值