我有NSMutableArray的void(^)()块,我想调试这个集合内部的内容。现在,如果我尝试打印它,我得到:
(lldb) po self.blockArray
<__NSArrayM 0x1712f090>(
<__NSMallocBlock__: 0x19d64e30>,
<__NSMallocBlock__: 0x19d60b50>,
<__NSMallocBlock__: 0x19cbb2b0>,
<__NSMallocBlock__: 0x19cbaa30>,
<__NSMallocBlock__: 0x19c83100>,
<__NSMallocBlock__: 0x170cbef0>
)
我想在每个块中添加一个描述字符串,然后查看它而不是地址(块的顺序很重要)。由于obj c块也是对象,我有可能感觉到它。有人可以分享一个想法怎么做吗?
答案 0 :(得分: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运行时,但我想我理解我在做什么。