Search code examples
objective-ccore-datansmanagedobjectcontext

NSManagedObjectContext nil when assigned within performBlock


I have being asked to repair this code which is not working, it is a common background task.

    __weak NSManagedObjectContext *weakCtx=[CDC privateManagedObjectContext]; // convenient class+macro for obtaining a private context queue
    __weak id weakSelf = self;
    [weakCtx performBlock:^{
        __strong id strongSelf = weakSelf;
        __strong NSManagedObjectContext *ctx = weakCtx; // <-- nil
        // more code following
    ];

The problem is caused later in the code by ctx being nil. However if I put a breakpoint within the block, I can see that while weakCtx is still valid, ctx get a nil value, which is causing the block to fail.

While on the opposite, weakSelf is being assigned correctly, and works trough the rest of the code.

What am I missing ?


Solution

  • You don't have to use __weak modifier for a context here, as it's not an ivar (so it isn't retained by self). This should work:

    NSManagedObjectContext *ctx=[CDC privateManagedObjectContext];
    __weak id weakSelf = self;
    [ctx performBlock:^{
        __strong id strongSelf = weakSelf;
        // use `ctx` here
    }];