Nick Harris

Weak vs Unowned When Passing Data Between NSOperations

leave a comment »

I posted the fix for the NSOperation retain cycle earlier this afternoon right before heading out to run some errands. While driving around town it dawned on me that the reason my attempt at using a capture list didn’t work is because I had mistakenly assumed that the first weak would be carried on to other classes in the list until another memory management keyword was encountered. When I got home I reread the documentation and that was indeed the case and updated the post.

This evening I started fixing my proof of concept app using weak but continuously unwrapping my operations in each NSBlockOperation seemed wrong. Perhaps unowned would be more correct. Here’s the key part in the documentation about which to use:

Like weak references, an unowned reference does not keep a strong hold on the instance it refers to. Unlike a weak reference, however, an unowned reference is assumed to always have a value. Because of this, an unowned reference is always defined as a nonoptional type. You indicate an unowned reference by placing the unowned keyword before a property or variable declaration.

I know for a fact that both operations in the data transfer will always have a value. That’s exactly what the dependencies do! Its why adding a dependency between two operations creates a strong relationship between them.

So the correct fixed code for the retain cycle looks like:

let operationOne = OperationOne()

let operationTwo = OperationTwo()

        

let transferOperation = NSBlockOperation() {

    [unowned operationTwo, unowned operationOne] in

            

    print(“transferOperation”)

    if let createdStrings = operationOne.createdStrings {

        operationTwo.passedInStrings = createdStrings

    }

}

        

        

transferOperation.addDependency(operationOne)

operationTwo.addDependency(transferOperation)

        

operationQueue.addOperation(operationOne)

operationQueue.addOperation(transferOperation)

operationQueue.addOperation(operationTwo)

 

Fun afternoon! Glad I finally have a good grasp on what all is going on in this setup.

Advertisements

Written by Nick Harris

February 4, 2016 at 2:13 am

Posted in Uncategorized

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: