想法1:記錄塊和描述,當它們被創建並手動識別時。
想法2:僅用於調試和試驗,使用時需自負風險。將description
方法添加到NSBlock
以及每個塊的關聯描述對象。我的測試應用程序:
@implementation AppDelegate
static char kAssociatedObjectKey;
typedef void (^MyBlockType)(void);
- (NSString *)myDescription {
NSString *description = [super description];
id object = objc_getAssociatedObject(self, &kAssociatedObjectKey);
if (object)
description = [description stringByAppendingFormat:@" %@", object];
return description;
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
Class blockClass = NSClassFromString(@"NSBlock");
Method descriptionMethod = class_getInstanceMethod([self class], @selector(myDescription));
BOOL didAddMethod = class_addMethod(blockClass, @selector(description),
method_getImplementation(descriptionMethod), method_getTypeEncoding(descriptionMethod));
MyBlockType a = ^{};
objc_setAssociatedObject(a, &kAssociatedObjectKey, @"block a", OBJC_ASSOCIATION_RETAIN_NONATOMIC);
MyBlockType b = ^{};
objc_setAssociatedObject(b, &kAssociatedObjectKey, @"block b", OBJC_ASSOCIATION_RETAIN_NONATOMIC);
MyBlockType c = ^{};
objc_setAssociatedObject(c, &kAssociatedObjectKey, @"block c", OBJC_ASSOCIATION_RETAIN_NONATOMIC);
NSArray *array = @[a, b, c];
NSLog(@"%@", array);
}
@end
PS。也許想法2不是一個好主意。我不熟悉Objective-C運行時,但我想我明白我在做什麼。