IOS app sometimes crashes when dereferencing a weak link

I have a very simple class:

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

Instances are stored in NSArray and from time to time (only in the main thread) this array is iterated, and I refer to the "object" property.

Everything works fine when testing or debugging, but in the production version of my application in the repository I sometimes get crash reports when dereferencing the object property (the stack trace actually shows the line number of the property definition).

Here is an example of such a call stack:

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)

Does anyone know what could be causing this?

+4
source share
1 answer
// 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 
 }
0
source

All Articles