取消引用弱引用时,iOS应用有时会崩溃

时间:2014-12-03 22:32:40

标签: ios objective-c automatic-ref-counting

我有一个非常简单的课程:

@interface WORef : NSObject
@property(nonatomic,weak) NSObject * object;
@end

实例存储在NSArray中,并且不时(仅在主线程上)迭代此数组并访问"对象"属性。

在测试或调试时一切正常,但在商店的应用程序的生产版本中,我有时会在解除引用"对象" property(堆栈跟踪实际显示属性定义的行号)。

以下是此类调用堆栈的示例:

Thread : Crashed: com.apple.main-thread
0  libsystem_platform.dylib       0x35180518 _os_lock_recursive_abort + 18446744073709552000
1  libsystem_platform.dylib       0x3518050f _os_lock_handoff_lock_slow + 90
2  libobjc.A.dylib                0x34adac3f objc_object::sidetable_release_slow((anonymous namespace)::SideTable*, bool) + 22
3  libobjc.A.dylib                0x34adad2f objc_object::sidetable_release(bool) + 118
4  Foundation                     0x27f56f01 -[NSOperationQueue dealloc] + 72
5  libobjc.A.dylib                0x34adad5f objc_object::sidetable_release(bool) + 166
6  libobjc.A.dylib                0x34ac14d9 _class_initialize + 536
7  libobjc.A.dylib                0x34ac705f lookUpImpOrForward + 254
8  libobjc.A.dylib                0x34ac6f1b lookUpImpOrNil + 26
9  libobjc.A.dylib                0x34abfab3 class_getMethodImplementation + 34
10 libobjc.A.dylib                0x34ada583 weak_read_no_lock + 58
11 libobjc.A.dylib                0x34ada871 objc_loadWeakRetained + 92
12 MyApp                          0x000c5983 -[WORef object] (WeakRef.m:12)

任何人都知道可能导致这种情况的原因吗?

1 个答案:

答案 0 :(得分:0)

// consider this method
-(void)populateArray {
    WORef *ref = [WORef new];
    ref.object = [YourObject new];
    return @[ref];

    // once you get out of this scope, the memory space occupied by [YourObject new]
    // can be re-allocate to something else and your ref.object would still point at
    // that memory space. You would get random crashes depending on when this memory space get re-allocated.
    // The reason being is that ref.object hold a weak reference to [YourObject new]
    // so it reference count doesn't get incremented.
    // Change your property declaration to (nonatomic,strong) instead 
 }