调试Objective C ++类中__weak变量的错误用法

时间:2016-05-26 22:51:46

标签: objective-c objective-c++

我的Objective-C ++类(MyObjectiveCppClass)中有以下-dealloc实现:

- (void)dealloc {
  if (_my_iVar) {
    [_my_iVar doSomeSlowishCleanUp];
  }
}

每当调用此-dealloc方法时,我会收到一堆警告:

objc[1254]: __weak variable at 0x1662a38c8 holds 0x19c70f408 instead of 0x160abe000. This is probably incorrect use of objc_storeWeak() and objc_loadWeak(). Break on objc_weak_error to debug.

当我打破objc_weak_error时,堆栈看起来像这样:

#0  0x0000000182395330 in objc_weak_error ()
#1  0x00000001823959d0 in weak_clear_no_lock ()
#2  0x000000018239f1e8 in objc_object::clearDeallocating_slow() ()
#3  0x000000018238e074 in objc_destructInstance ()
#4  0x0000000182d25fac in -[NSObject(NSObject) __dealloc_zombie] ()
----> #5    0x00000001000a6c30 in -[MyObjectiveCppClass .cxx_destruct]
#6  0x0000000182382b54 in object_cxxDestructFromClass(objc_object*, objc_class*) ()
#7  0x000000018238e040 in objc_destructInstance ()
#8  0x0000000182d25fac in -[NSObject(NSObject) __dealloc_zombie] ()
---->    #9 0x00000001000a691c in -[MyObjectiveCppClass dealloc] 
#10 0x0000000100611bc4 in -[SomeViewB .cxx_destruct]
#11 0x0000000182382b54 in object_cxxDestructFromClass(objc_object*, objc_class*) ()
#12 0x000000018238e040 in objc_destructInstance ()
#13 0x0000000182d25fac in -[NSObject(NSObject) __dealloc_zombie] ()
#14 0x0000000188233a90 in -[UIResponder dealloc] ()
#15 0x0000000187e78b08 in -[UIView dealloc] ()
#16 0x0000000187f60700 in -[UIScrollView dealloc] ()
#17 0x0000000182c049b4 in -[__NSArrayM dealloc] ()
#18 0x00000001006495cc in -[SomeViewA .cxx_destruct]

有没有人知道如何解决这些警告?

2 个答案:

答案 0 :(得分:1)

事实证明,_my_iVar对象对自身有一个__unsafe_unretain引用,并将其传递给一些子对象,其中一个子对象将其分配给weak局部变量。

答案 1 :(得分:1)

可能会帮助您,请按照以下步骤操作:

  1. 从班级中删除ARC(-fobjc-arc)。为此,请转到“项目设置” - >“构建阶段” - >“编译源”。现在选择你的类并删除-fobjc-arc。 现在构建它,如果你有任何自动释放,从.m文件中的声明中删除它。假设你有:

    UILabel *label = [[[UILabel alloc] initWithFrame:rect] autorelease];
    
  2. 请这样做:

        UILabel *label = [[UILabel alloc] initWithFrame:rect];
    

    你可能还有一个问题:

    Cannot synthesize weak property in file using manual reference counting.
    

    不要担心这个问题。

    如果您没有ARC,请转到下一步。

    1. 删除ARC后,再次转到项目设置。转到构建设置并在手动保留版本和#34;中搜索"弱引用。目前该值为NO。是的。
    2. 现在清洁,建造和运行。