2016-07-27 82 views
1

我有NSMutableArray void(^)()塊,我想調試這個集合裏面發生了什麼。現在,如果我嘗試打印我得到:Obj C:如何將描述添加到塊對象?

(lldb) po self.blockArray 
<__NSArrayM 0x1712f090>(
<__NSMallocBlock__: 0x19d64e30>, 
<__NSMallocBlock__: 0x19d60b50>, 
<__NSMallocBlock__: 0x19cbb2b0>, 
<__NSMallocBlock__: 0x19cbaa30>, 
<__NSMallocBlock__: 0x19c83100>, 
<__NSMallocBlock__: 0x170cbef0> 
) 

我想描述字符串添加到每個塊,看到它,而不是地址(塊的順序很重要)。由於obj c塊也是對象,所以我有一種感覺它可能..任何人都可以分享一個想法如何做到這一點?

回答

0

想法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運行時,但我想我明白我在做什麼。