2012年11月2日 星期五

[iOS] iOS: import, property, protocol


  • 用 #import來加入 package, import與 include最大的差異在於不用在人工加入 #ifndef 與 #endif, compiler已經幫我們做掉可能會發生重複 include的情形
  • access rules
    • public: @interface in .h
    • private: @interface in .m, 但是方法後面要加 (), e.g. @interface privateMethod()
  • @property
    • build-in getter and setter
    • private: -(double) value;
    • public: 
      • -(double) value {return value;}  
      • -(void)setValue: (double) val {value = val;}
    • 合成.h中: @property (nonatomic) double topSpeed;  而 .m中: @synthesize topSpeed =_ topSpeed;
      • nonatomic為 not thread-safe的 keyword
      • 上面其實就是實作了
        • -(void) setTopSpeed: (double) speed
        • {
          • _topSpeed = speed;
        • }
        • -(double) topSpeed
        • {
          • return _topSpeed;
        • }
      • 可清楚看到不用 @synthesize topSpeed; 而是 @synthesize topSpeed = _topSpeed; 主要怕第二個 getter方法名與 member實際名稱相同帶來的困擾
    • 另外也可以設定 pointer, 通常會搭配 strong的屬性, strong代表不會自動回收, 而 weak則是沒人用了就回收
  • static
    • return type前面 -為 non-static, +為 static
  • @protocol
    • non-class-specific methods
    • @interface 對應 Java的 @class, 而 @protocol對應 Java的 @interface
    • Ref: Protocol in Objective-C
  • @category
    • 擴充既存 class
    • 一般只用於加 method
    • 若擴充的 method檔名已存在, 則會以 category定義的為主
    • Ref: Category in Objective-C
  • 傳 message給 nil:
    • 不像 c++會 crash, 這會....nothing happened, 在 debug要特別注意
  • all objects in objective-C are in heap

沒有留言:

張貼留言