1

I have NSMutableArray of void(^)() blocks and I'd like to debug what's going on inside of this collection. Right now if I try to print it I get:

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

I want to add a description string to a each block and see it instead of address (order of blocks is important). Since obj c blocks are objects too I have a felling its possible.. Can anyone share an idea how to do it?

gheni4
  • 273
  • 3
  • 16

1 Answers1

0

Idea 1: Log the blocks and description when they are created and identify manually.

Idea 2: Only for debugging and experimenting, use at your own risk. Add a description method to NSBlock and an associated description object to each block. My test app:

@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. Maybe idea 2 isn't a good idea. I'm not familiar with the Objective-C runtime but I think I understand what I'm doing.

Willeke
  • 14,578
  • 4
  • 19
  • 47