在類別層級直接定義 Block 並引用 self 會導致「use of undeclared identifier self」編譯錯誤。需在 @interface 宣告屬性,在實例方法中賦值。
// .h
@interface MyClass : NSObject
@property (nonatomic, copy) void (^myBlock)(void);
@end
// .m
@implementation MyClass
- (void)setupBlock {
self.myBlock = ^{
[self doSomething]; // 此處可正常捕獲 self
};
}
- (void)doSomething { /* ... */ }
@end
copy,確保從堆區複製,避免棧區銷毀。self 已存在且可被捕獲。__block 變數,加上關鍵字。self 且 self 持有 Block,需用 __weak typeof(self) weakSelf = self; 在 Block 內使用 weakSelf。