Objective-C 在 C 語言之上加了物件導向,但語法特性相對精簡。搞懂類定義、成員變數、屬性、self、構造方法與繼承這幾件事,就能讀懂絕大多數的 OC 程式碼。
在 Xcode 新增 Cocoa Touch Class,選擇父類為 NSObject,會產生 .h 與 .m 兩個檔案:
// Person.h
#import <Foundation/Foundation.h>
// @interface 宣告類,必須以 @end 結束
@interface Person : NSObject
@end
// Person.m
#import "Person.h"
@implementation Person
@end
分工很明確:.h 放宣告(成員變數、屬性、方法),.m 放實作。所有類最終都繼承自 NSObject,因此必須匯入 Foundation。
@interface Person : NSObject {
@private
NSString *_name; // 只有當前類可存取
int _age;
@protected
NSString *_nation; // 當前類與子類可存取(未標註時的預設值)
@public
float height; // 任何地方都可存取
}
@end
OC 只有這三種修飾符,沒有 C# 的 internal。成員變數必須寫在類後方的 `{}` 內,且慣例上以底線開頭。
存取 public 成員的方式是直接指定:
Person *p = [[Person alloc] init];
p->height = 1.72;
NSLog(@"height=%.2f", p->height);
這裡有幾個 OC 的基本規則:
*,因為物件本身就是指標;基本型別(int、float)不加。[] 呼叫方法,本質是「向該物件或類別發送一個訊息」。[Person new]。-> 而非 .。// Person.h
@interface Person : NSObject {
@private
NSString *_name;
int _age;
@protected
NSString *_nation;
@public
float height;
}
- (void)setName:(NSString *)name; // 動態方法(實例方法)
+ (void)showMessage:(NSString *)info; // 靜態方法(類方法)
@end
// Person.m
@implementation Person
- (void)setName:(NSString *)name {
_name = name;
}
+ (void)showMessage:(NSString *)info {
NSLog(@"%@", info);
}
@end
用 - 定義動態方法,+ 定義靜態方法。寫在 .h 中是公開方法,只在 .m 中實作則是私有方法。
參數與回傳型別放在 () 中,每個參數前的冒號都是方法名稱的一部分。因此下面這個方法完整名稱是 setAge:andHeight::
- (void)setAge:(int)age andHeight:(NSString *)nation {
_age = age;
_nation = nation;
}
OC 的屬性其實就是 getter 與 setter 的包裝。setter 命名為 setXxx:,getter 直接用變數名稱(不加 get)。手寫如下:
- (int)age { return _age; }
- (void)setAge:(int)age { _age = age; }
呼叫時可以用點語法糖:
p.age = 28; // 等價於 [p setAge:28];
int age = p.age; // 等價於 [p age];
既然每次都要寫這兩個方法,語言提供了自動合成:
@interface Person : NSObject {
@public
NSString *birthday;
NSString *_position;
NSString *_degress;
}
@property NSString *birthday;
@property NSString *position;
@property NSString *degress;
@property NSString *education;
@property float weight;
@end
@implementation Person
@synthesize birthday;
@synthesize position;
@synthesize degress = _degress;
@synthesize education;
@end
@property NSString *a; 不加 synthesize:編譯器使用 _a 作為備份變數,不存在時自動產生。@synthesize a; 但未指定變數:使用 a(同樣會自動產生)。@synthesize a = _a;:明確使用 _a。實務上兩種寫法都常見,但團隊內要統一。若在 .m 中自行實作了 getter 或 setter,編譯器就不會再合成該方法。
類似 C#、Java 的 this,但 self 在動態方法中代表「當前物件」,在靜態方法中代表「當前類別」:
- (void)setName:(NSString *)name andAge:(int)age {
self.name = name; // self 是物件
self.age = age;
}
+ (void)printInfo { NSLog(@"Hello, World!"); }
+ (void)showMessage {
[self printInfo]; // self 是類別
}
覆寫 setter 時若寫成 self.name = name;,會再次呼叫自己,形成無限遞迴而崩潰。正確做法是在自訂 setter 中直接操作備份變數:
- (void)setName:(NSString *)name {
_name = name; // 不要寫成 self.name = name;
}
這也是為什麼成員變數慣例上加底線——一眼就能分辨這是備份變數還是屬性。
- (id)initWithName:(NSString *)name andAge:(int)age {
// super 代表父類,必須先呼叫父類的初始化
if (self = [super init]) {
self.name = name;
self.age = age;
}
return self;
}
使用時:Person *p = [[Person alloc] initWithName:@"Kenshin" andAge:28];
OC 另外慣例提供一個靜態的便利構造器,讓呼叫端不必自己 alloc:
+ (id)personWithName:(NSString *)name andAge:(int)age {
Person *p = [[Person alloc] initWithName:name andAge:age];
return p;
}
對應 C# 的 ToString()、Java 的 toString():
- (NSString *)description {
return [NSString stringWithFormat:@"{name:%@,age:%ld}", self.name, (long)self.age];
}
用 NSLog(@"%@", p); 輸出物件時,會呼叫這個方法。未覆寫時,輸出的是類名與記憶體位址,例如 <Person: 0x100202310>。
千萬不要在 description 中輸出 self,那會再次呼叫 description,造成遞迴。
// Student.h
#import "Person.h"
@interface Student : Person
@property (nonatomic, assign) float score;
- (id)initWithName:(NSString *)name andAge:(int)age andScore:(float)score;
+ (id)studentWithName:(NSString *)name andAge:(int)age andScore:(float)score;
@end
// Student.m
@implementation Student
- (id)initWithName:(NSString *)name andAge:(int)age andScore:(float)score {
// 先讓父類處理它負責的部分
if (self = [super initWithName:name andAge:age]) {
self.score = score;
}
return self;
}
+ (id)studentWithName:(NSString *)name andAge:(int)age andScore:(float)score {
return [[Student alloc] initWithName:name andAge:age andScore:score];
}
// 覆寫父類方法,並可讀取 @protected 成員
- (NSString *)description {
return [NSString stringWithFormat:@"{name:%@,age:%ld,nation:%@,score:%.2f}",
self.name, (long)self.age, self->_nation, self.score];
}
@end
呼叫端:
Person *p = [Person personWithName:@"Kenshin" andAge:28];
Student *s = [Student studentWithName:@"Kaoru" andAge:27 andScore:100];
s.nation = @"henan";
NSLog(@"s=%@", s);
上面這套寫法(尤其 MRC 時代的 alloc/init 細節)在今日仍完全有效,但新專案通常還會搭配:
strong,字串與 block 用 copy,delegate 與避免循環參照用 weak,基本型別用 assign。_Nullable 標註,讓編譯器協助檢查空值。id 作為構造方法的回傳型別,能保留型別推斷,並在子類繼承時給出正確警告。