Method Swizzling 是 Objective-C Runtime 提供的能力,可以在執行期把兩個方法的實作互相替換。最常見的用途是替系統類別「打補丁」,例如替 NSArray 加上越界防護。
#import@implementation NSObject (Extension) // 交換類別方法 + (void)swizzleClassMethod:(Class)cls originSelector:(SEL)originSelector otherSelector:(SEL)otherSelector { Method otherMethod = class_getClassMethod(cls, otherSelector); Method originMethod = class_getClassMethod(cls, originSelector); method_exchangeImplementations(otherMethod, originMethod); } // 交換實例方法 + (void)swizzleInstanceMethod:(Class)cls originSelector:(SEL)originSelector otherSelector:(SEL)otherSelector { Method otherMethod = class_getInstanceMethod(cls, otherSelector); Method originMethod = class_getInstanceMethod(cls, originSelector); method_exchangeImplementations(otherMethod, originMethod); } @end
@implementation NSArray (Extension)
+ (void)load
{
[self swizzleInstanceMethod:NSClassFromString(@"__NSArrayI")
originSelector:@selector(objectAtIndex:)
otherSelector:@selector(hm_objectAtIndex:)];
}
- (id)hm_objectAtIndex:(NSUInteger)index
{
if (index < self.count)
{
// 交換之後,這裡呼叫的其實是原本系統的實作
return [self hm_objectAtIndex:index];
}
else
{
return nil;
}
}
@end
@implementation NSMutableArray (Extension)
+ (void)load
{
Class cls = NSClassFromString(@"__NSArrayM");
[self swizzleInstanceMethod:cls
originSelector:@selector(addObject:)
otherSelector:@selector(hm_addObject:)];
[self swizzleInstanceMethod:cls
originSelector:@selector(objectAtIndex:)
otherSelector:@selector(hm_objectAtIndex:)];
}
- (void)hm_addObject:(id)object
{
if (object != nil)
{
[self hm_addObject:object];
}
// 傳入 nil 時靜默忽略,避免原本的 exception
}
- (id)hm_objectAtIndex:(NSUInteger)index
{
if (index < self.count)
{
return [self hm_objectAtIndex:index];
}
else
{
return nil;
}
}
@end

命名慣例很重要。方法名前綴(這裡是 hm_)可以避免與系統或第三方庫的既有方法相撞。這不是風格問題,而是實際的 crash 風險。
為什麼要拆成 __NSArrayI 與 __NSArrayM?不可變陣列與可變陣列在底層是兩個不同的私有類別,各自實作了自己的 objectAtIndex:。只 swizzle 其中一個,另一個仍會 crash。
務必在 +load 中執行。+load 會在類別被載入時呼叫,此時 Runtime 已完成初始化,是最安全的時機。若在 +initialize 或其他時機執行,可能出現競爭條件。
回傳 nil 只是權宜之計。越界時回傳 nil 讓程式不會 crash,但呼叫端通常預期拿到有效物件,後續很可能在別處出問題,反而更難 debug。較穩妥的做法是回傳 nil 的同時印出完整呼叫堆疊,方便定位是哪裡寫錯了索引。
系統私有類別名稱不是穩定 API。__NSArrayI、__NSArrayM 屬於實作細節,蘋果有權在任何版本變更。這類 swizzle 上線前務必在每個支援的 iOS 版本上實測。