iOS Dev (16) 一些 OC 的基礎知識點小節之一
- 作者:CSDN 大銳哥
- 部落格:http://blog.csdn.net/prevention1 靜態方法中的 self
在靜態方法(類方法)中使用 self ,self 表示這個類。比如以下兩個方法的意思是一樣的:
+ (void) wtf { [self alloc]; } + (void) wtf { [ClassName alloc]; }
2 點號的真正含義OC 中一個對象後面用“.”後面再帶一堆東西,表示 get 方法或 set 方法,而不是指成員變數。至於是 get 還是 set 取決於應用情境是需要返回值還是不需要返回值的 void 。所以有:
[[UIViewController alloc] init]; 其實可以寫成 UIViewController.alloc.init;
3 私人方法OC 在 .m 中實現的方法,而不在 .h 中使用的方法,都是私人方法。
4 成員變數的預設範圍與 C++ 一樣,有三種範圍:
- public
- protected
- private
OC 在 .h 中聲明的成員變數,預設都是 protected。比如:
@interface ClassName: NSObject{ int _age; int _sex;}@end
以上的 age 和 sex 都是 protected 的,即可以在該類和子類中訪問。
4 如何指定成員變數的範圍?直接上代碼吧:
@interface ClassName: NSObject{ @public int _age; @private int _sex; }@end
5 get 方法和 set 方法的正規寫法@interface ClassName: NSObject{ int _age; int _sex;}- (int) age;- (void) setAge:(int)age;@end
6 寫個構造方法有兩種寫法,注意第一種中是有 * 的,表示指標。
- (ClassName *)initWithArg:(int)arg{}
也可以用 id 哦~
- (id)initWithArg:(int)arg{}
7 繼承後調用父類的構造方法- (id)initWithArg:(int)arg{ if (self = [super init]) { _arg = arg; } return self;}
8 [[Blabla alloc] init] 的簡單寫法ClassName *cn = [[ClassName alloc] init];ClassName *bn = [ClassName new]; // 不建議使用
-
轉載請註明來自:http://blog.csdn.net/prevention