iosnsautoreleasepoolrunloop

When autorelease pool release object in background thread?


I know autorelease pool will release objects when the runloop in the state kCFRunLoopBeforeWaiting.

So I create a background thread which runloop doesn't run by default.

If I use an autorelease pool in this background thread, when does it release objects.


Solution

  • https://developer.apple.com/documentation/foundation/nsautoreleasepool?language=objc

    autorelease pool is just a unlimited stack for keeping autorelease object. when you create a autorelease pool, pool stack push a watcher. when you call autorelease on object, the object is pushed into the pool stack. when you release autorelease pool, it release all pushed object after watcher, and then remove the watcher.

    @autorelease in objc or autorelease in swift, is just a wrapper for create a autorelease pool, call block and then release pool.

    runloop will automatically wrapper task into a autorelease pool.

    but when you use autorelease pool with a custom thread, which haven't a runloop, in my observe, object will release when thread exit..

    How to observe autorelease timeing

    you can create a custom watch class with deinit defined, and manual retain and autorelease it, to observe the deinit timeing. code as below

    class A {
        deinit {
            print("a dealloced")
        }
    }
    
    var p: pthread_t?
    _ = pthread_create(&p, nil, { (p) -> UnsafeMutableRawPointer? in
        do {
            let a = A()
            _ = Unmanaged.passRetained(a).autorelease()
        }
        print("will exit pthread")
        return nil
    }, nil)
    pthread_join(p!, nil)
    print("finish")
    

    this script will print

    will exit pthread
    a dealloced
    finish
    

    also you can breakpoint at deinit to see the backtrace of autorelease