Objective-C 的基礎語法與 Foundation 常用類別,是寫任何 iOS 應用都繞不開的部分。本篇整理協議的宣告與使用,以及字串、數字、集合的標準操作。
協議是一份方法的宣告清單,類似於「規範」:實踐該協議的類別必須遵守其中的約定。
Xcode → File → New → New File → Cocoa Touch → Objective-C Protocol → 命名(例如 PersonProtocol)→ Save。
#import <Foundation/Foundation.h>
@protocol PersonProtocol <NSObject>
@optional
@property(nonatomic, strong) NSString *firstName;
@property(nonatomic, strong) NSString *lastName;
@required // 必須實作的部分
@property(nonatomic, unsafe_unretained) NSUInteger age;
-(void)breathe;
@end
#import <Foundation/Foundation.h>
#import "PersonProtocol.h"
@interface Father : NSObject <PersonProtocol>
-(void)breathe;
@end
實作檔中必須提供 @required 區段宣告的方法本體。
@required 明確指定必須實作的屬性與方法;@optional 則可實作也可略過。
使用情境:你的 SDK 是新版,但需要相容舊版 iOS 的裝置。
用 NSObject 的 instancesRespondToSelector: 檢查某個 selector 是否存在於類別的實例中;要確認類別本身是否回應類別方法,則用 respondsToSelector:。
這裡有兩個重要概念:
編譯實際上是同時依據這兩者進行的,這也是「用新 SDK 編譯、跑舊系統」得以成立的原理。
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:
@"Item 1", @"Item 4", @"Item 2", @"Item 5", @"Item 3", nil];
NSLog(@"Array = %@", array);
if ([NSArray instancesRespondToSelector:@selector(sortUsingComparator:)]) {
// 用 sortUsingComparator: 排序
} else if ([NSArray instancesRespondToSelector:@selector(sortUsingFunction:context:)]) {
// 舊系統改用 sortUsingFunction:context:
} else {
// 其他處理
}
NSString 建立後內容不可變;NSMutableString 則可隨時修改。
NSString *string = @"hello world";
NSString *string2 = [NSString stringWithString:@"hello world"];
NSUInteger len = [string length]; // 長度
// 型別轉換
NSString *str = @"123.456";
NSInteger i = [str integerValue]; // 123
CGFloat f = [str floatValue]; // 123.456001
double d = [str doubleValue]; // 123.456
// 搜尋子字串
NSString *one = @"hello world";
NSString *two = @"hello";
NSRange range = [one rangeOfString:two];
if (range.location == NSNotFound) {
// 找不到
} else {
NSLog(@"%lu", (unsigned long)range.location);
}
NSInteger 為有號整數(可為負),NSUInteger 為無號(零與正數),CGFloat 與 double 用於浮點運算。
// 封裝
[NSNumber numberWithInteger:42];
[NSNumber numberWithUnsignedInteger:42];
[NSNumber numberWithFloat:3.14];
[NSNumber numberWithDouble:3.14];
// 取出純數字
[n unsignedIntegerValue];
[n integerValue];
[n floatValue];
[n doubleValue];
// 數字轉字串
NSNumber *unsignedNumber = [NSNumber numberWithUnsignedInteger:123456];
NSString *numberInString = [NSString stringWithFormat:@"%lu",
(unsigned long)[unsignedNumber unsignedIntegerValue]];
NSLog(@"%@", numberInString);
NSArray *array = [[NSArray alloc] initWithObjects:@"one", @"two", @"three", nil];
NSArray *autoReleased = [NSArray arrayWithObjects:@"one", @"two", @"three", nil];
NSUInteger count = [array count]; // 長度
NSString *first = [array objectAtIndex:0]; // 取值
[mutableArray addObject:@"four"]; // 新增
[mutableArray removeObject:@"four"]; // 刪除
Set 與 Array 很像,最大差異是同一個物件只能加入一次,重複加入會被忽略。
[setOfNames addObject:@"Kiyosaki"];
[setOfNames removeObject:@"Kiyosaki"];
// 快速遍歷
[setOfNames enumerateObjectsUsingBlock:^(__strong id obj, BOOL *stop) {
if ([obj isKindOfClass:[NSString class]]) {
NSString *string = (NSString *)obj;
if ([string isEqualToString:@"Kiyosaki"]) {
NSLog(@"Found %@ in the set", string);
*stop = YES; // 提前結束遍歷
}
}
}];
block 中的 *stop = YES 是提前跳出遍歷的關鍵,處理大集合時能省下不少時間。
[[NSNotificationCenter defaultCenter] postNotificationName:@"SomeEvent"
object:self
userInfo:@{@"key": @"value"}];
三個參數分別是通知名稱、觸發通知的物件(通常是自己),以及攜帶的 userInfo 字典。其他物件只要註冊觀察同名通知,就能收到並採取行動——這是 iOS 中最鬆耦合的物件溝通方式。
NSDictionary 與 NSMutableDictionary 的鍵必須遵循 NSCopying(通常用 NSString),且查值時若鍵不存在會回傳 nil 而非拋錯,因此取值後務必做 nil 判斷再使用。