Weak method argument semantics

9.7k views Asked by At

Is there any way to specify that a particular method argument has weak semantics?

To elaborate, this is an Objective-C sample code that works as expected:

- (void)runTest {  
    __block NSObject *object = [NSObject new];  
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{  
        [self myMethod:object];  
    });  
    // to make sure it happens after `myMethod:` call  
    dispatch_async(dispatch_get_main_queue(), ^{  
        object = nil;  
    });  
}  
- (void)myMethod:(__weak id)arg0 {  
    NSLog(@"%@", arg0); // <NSObject: 0x7fb0bdb1eaa0>  
    sleep(1);  
    NSLog(@"%@", arg0); // nil  
}  

This is the Swift version, that doesn't

public func runTest() {  
    var object: NSObject? = NSObject()  
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {  
        self.myMethod(object)  
    }  
    dispatch_async(dispatch_get_main_queue()) {  
        object = nil  
    }  
}  
private func myMethod(arg0: AnyObject?) {  
    println("\(arg0)") //Optional(<NSObject: 0x7fc778f26cf0>)  
    sleep(1)  
    println("\(arg0)") //Optional(<NSObject: 0x7fc778f26cf0>)  
}  

Am I correct in ym assumption that there is no way for the arg0 to become nil between the method calls in Swift version? Thank you!

Update a user from Apple Dev.Forums pointed out that sleep is not a good function to use and consecutive dispatches might cause race conditions. While those might be reasonable concerns, this is just a sample code, the focus of the question is on passing weak arguments.

3

There are 3 answers

3
russbishop On

Is there any way to specify that a particular method argument has weak semantics?

That isn't what your Objective-C code example is doing. You're getting accidentally almost-weak semantics and you have undefined behavior (race condition) that real weak references don't have.

myMethod can send a message into la-la-land at any sequence point (the first NSLog statement or second, or even in the middle of NSLog somewhere... even if ARC doesn't elide the retain of arg0 you're still racing the main queue release or worse - retaining a zombie object).

Declaring something as __block just means allocate a slot in the heap environment for the block (because dispatch_async is guaranteed to let the block escape it will promote from a stack-allocated block to a heap block, and one of the storage slots in that heap block environment will be for your __block variable. Under ARC the block will automatically have Block_copy called, perhaps more aptly named Block_copy_to_heap).

This means both executing instances of the block will point to this same memory location.

If it helps, imagine this really silly code which has an obvious race condition. There are 1000 blocks queued concurrently all trying to modify unsafe. We're almost guaranteed to execute the nasty statements inside the if block because our assignment and comparison are not atomic and we're fighting over the same memory location.

    static volatile size_t unsafe = 0;

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    dispatch_apply(1000, queue, ^(size_t instance) {
        unsafe = instance;
        if (unsafe != instance) {
            FORMAT_ALL_STORAGE();
            SEND_RESIGNATION_EMAIL();
            WATCH_THE_WORLD_BURN();
        }
    });

Your Swift example doesn't have the same problem because the block that doesn't modify the value probably captures (and retains) the object so doesn't see the modification from the other block.

It is up to the creator of a closure to deal with the memory management consequences so you can't create an API contract that enforces no retain cycles in a closure, other than marking something as @noescape in which case Swift won't do any retain/release or other memory management because the block doesn't outlive the current stack frame. That precludes async dispatch for obvious reasons.

If you want to present an API contract that solves this you can have a type adopt a protocol protocol Consumer: class { func consume(thing: Type) } then inside your API keep a weak reference to the Consumer instances.

Another technique is to accept a curried version of an instance function and weakly capture self:

protocol Protocol: class { }
typealias FuncType = () -> Void
var _responders = [FuncType]()

func registerResponder<P: Protocol>(responder: P, usingHandler handler: (P) -> () -> Void) {
    _responders.append({ [weak responder] in
        guard let responder = responder else { return }
        handler(responder)()
    })
}

class Inst: Protocol {
    func myFunc() {

    }
}
let inst = Inst()
registerResponder(inst, usingHandler: Inst.myFunc)
4
Slipp D. Thompson On

Swift doesn't have “weak args”… but that's probably only because Swift (3.0) args are immutable (equivalent to lets) and weak things in Swift need to be both a var and an Optional.

That said, there is indeed a pretty-easy way to accomplish an equivalent to weak args— use a weak var local (which frees up the arg-var to be released).  This works because Swift doesn't hang onto vars until the end of the current scope (like C++ so strictly does); but rather it releases vars from the scope after the last usage of them (which makes lldb-ing a PitA sometimes, but whatever).

The following example works consistently in Swift 3.0.2 on Xcode 8.2.1 on macOS 10.11.6:

class Test
{
    func runTest() {
        var object:NSObject? = NSObject()
        myMethod(arg0: object)

        DispatchQueue.main.asyncAfter(
            deadline: DispatchTime.now() + 1.0,
            qos: .userInteractive,
            flags: DispatchWorkItemFlags.enforceQoS
        ){
            object = nil
        }
    }

    func myMethod(arg0:AnyObject?) {
        weak var arg0Weak = arg0
        // `arg0` get “released” at this point.  Note: It's essential that you 
        //   don't use `arg0` in the rest of this method; only use `arg0Weak`.

        NSLog("\(arg0Weak)"); // Optional(<NSObject: 0x600000000810>)

        DispatchQueue.main.asyncAfter(
            deadline: DispatchTime.now() + 2.0,
            qos: .userInteractive,
            flags: DispatchWorkItemFlags.enforceQoS
        ){
            NSLog("\(arg0Weak)"); // nil
        }
    }
}

Test().runTest()

Note that if you try this in a Playground, the playground will finish execution before the DispatchQueues fire.  The simplest way to get the executable to run indefinitely (what I did) is create a new Cocoa application and paste all the code above into the func applicationDidFinishLaunching(_:Notification) { … } (yes, verbatim— Swift allows class definitions nested inside of methods).


In response to the thread-safety-lecturing you've gotten over using dispatch_async & sleep in your example, to prove that weak args are indeed the real deal here's a complete-main.m-source variant of your test that's single-threaded and queue-free:

#import <Foundation/Foundation.h>


@interface Test : NSObject 
- (void)runTest;
- (void)myMethod:(__weak id)arg0 callback:(void (^)())callback;
@end


int main(int argc, const char * argv[]) {
    @autoreleasepool {
        [[Test new] runTest];
    }
    return 0;
}


@implementation Test

- (void)runTest {
    __block NSObject *object = [NSObject new];
    [self myMethod:object callback:^{
        object = nil;
    }];
}

- (void)myMethod:(__weak id)arg0 callback:(void (^)())callback {
    NSLog(@"%@", arg0); // <NSObject: 0x100400bc0>
    callback();
    NSLog(@"%@", arg0); // (null)
}

@end
0
eonil On

No way with language syntax for now.

I think this workaround is closest one for now.

public struct Weak<T> where T: AnyObject {
    public weak var object: T?

    public init(_ object: T?) {
        self.object = object
    }
}

func run<T>(_ a: Weak<T>) {
    guard let a = a.object else { return }
}