3

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.

dowZhang
  • 470
  • 1
  • 3
  • 18

1 Answers1

5

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

SolaWing
  • 1,652
  • 12
  • 14
  • In your observe, object will release when thread exit with a custom thread. Could you tell me how to verify it. – dowZhang Jun 03 '20 at 01:17
  • 1. create thread. 2. create a custom object with dealloc define, and manual retain and autorelease it. 3. thread exit 4. check if the custom object dealloc method called – SolaWing Jun 03 '20 at 04:45