iOS开发知识ios知识积累iOS Developer

iOS setters and getters

2015-01-25  本文已影响314人  jProvim

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

上一篇 下一篇

猜你喜欢

热点阅读