Weak to Strong reference still crashes on lookup

Viewed 56

I'm getting EXC_BAD_ACCESS exceptions on the managedObject.objectRevision access in the following code:

-(void)increaseObjectRevision {
    __weak LibraryManagedObject* weakSelf = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        LibraryManagedObject* managedObject = weakSelf;
        if(managedObject) {
            managedObject.objectRevision = managedObject.objectRevision + 1;
        }
    });
}

I'm a little stumped as this code pattern seems to be the solution referred to in Strong reference to a weak references inside blocks

Here's the declaration for the objectRevision property:

@interface LibraryManagedObject : NSObject
@property (readonly, nonatomic) NSUInteger objectRevision;
...
@end

And re-defined within the LibraryManagedObject.m to:

@interface LibraryManagedObject()
@property (readwrite, nonatomic, assign) NSUInteger objectRevision;
@end

Anything I'm missing here?

Note: I could make the property atomic but seeing how this is not a pointer to a NSNumber but a value itself, it shouldn't be the cause for the EXC_BAD_ACCESS exception.

1 Answers

The code posted in the question is working as intended. After inspecting the memory address reported in the exception against the value of weakSelf, the addresses were different.

During our discussion (https://chat.stackoverflow.com/rooms/218530/discussion-between-ol-sen-and-ekscrypto) it became clear that KVO may actually be related to the crash. One of the KVO observers did not properly unregister its observer before being deallocated.

Related