iOS setters and getters

作者: jProvim | 来源:发表于2015-01-25 07:04 被阅读314次

iOS

今天來談一談Objective-C裡面的Setters/Getters.

Date: Sat Jan 24 15:02:06 PST 2015

Setters/Getters

例子

@property (strong, nonatomic) NSString *name;

Xcode會幫你自動生成

-(NSString) name{
    return _name;
}
-(void) setName: (NSString*)name {
    _name = name;
}

因為是Xcode, 所以有的時候我們會習慣用bracket notation來表示,
雖然這兩個方法都是正確的.

NSLog(@"%@", [self name]);
NSLog(@"%@", self.name);

我推薦大家用dot notation: self.name, 因為這樣很簡單
但是用bracket notation的話更不容易出錯.

當然了, 如果是團隊合作的話, 大家怎麼寫你就怎麼寫.

TA人看法

Google: Dot notation is allowed only for access to a declared @property.

這幾個StackOverflow帖子的看法是不要用dot

  1. Dot notation vs square brackets and casting in Objective-C
  2. With and Without Dot Notation

Reference

StackOverflow

iPhoneDevSDK

相关文章

网友评论

  • jProvim:@Foryoujust 你說的不錯, 這個是ARC的寫法, 不過現在寫iOS應該都這樣寫了. 至少我在github上面看到的一些代碼都是用@property的.
    @property會根據attributes: strong, weak, readonly等, 來自動生成對應的代碼. 不過這些就不要我們來擔心了, 我們更應該把時間放到實現上去.
  • Foryoujust:你这应该是在ARC下,还有会根据所用的是strong还是copy内部的实现也是不一样的。个人理解,有偏差请指正!

本文标题:iOS setters and getters

本文链接:https://www.haomeiwen.com/subject/dmkkxttx.html