pub struct AutoreleasePool<'pool> { /* private fields */ }Expand description
An Objective-C autorelease pool.
Autorelease pools are a way to store objects in a certain thread-local scope, such that they are only released at the end of said scope.
See autoreleasepool and autoreleasepool_leaking for how to create
this.
This is not Send nor Sync, since you can only autorelease a
reference to a pool on the current thread.
§Example
Use the pool as a bound on a function, and release an object to that pool.
use objc2::rc::{autoreleasepool, AutoreleasePool};
use objc2::runtime::NSObject;
use objc2::msg_send;
unsafe fn needs_lifetime_from_pool<'p>(pool: AutoreleasePool<'p>) -> &'p NSObject {
let obj = NSObject::new();
// Do action that returns an autoreleased object
let description: *mut NSObject = unsafe { msg_send![&obj, description] };
// Bound the lifetime of the reference to that of the pool.
//
// Note that this only helps ensuring soundness, our function is still
// unsafe because the pool cannot be guaranteed to be the innermost
// pool.
unsafe { pool.ptr_as_ref(description) }
}
autoreleasepool(|pool| {
// SAFETY: The given pool is the innermost pool.
let obj = unsafe { needs_lifetime_from_pool(pool) };
println!("{obj:?}");
});Implementations§
Source§impl<'pool> AutoreleasePool<'pool>
impl<'pool> AutoreleasePool<'pool>
Sourcepub unsafe fn ptr_as_ref<T: ?Sized>(self, ptr: *const T) -> &'pool T
pub unsafe fn ptr_as_ref<T: ?Sized>(self, ptr: *const T) -> &'pool T
Returns a shared reference to the given autoreleased pointer object.
This is the preferred way to make references from autoreleased objects, since it binds the lifetime of the reference to the pool, and does some extra checks when debug assertions are enabled.
Note that this is helpful, but not sufficient, for ensuring that the lifetime of the reference does not exceed the lifetime of the autorelease pool. When calling this, you must also ensure that the pool is actually the current innermost pool.
§Panics
If the pool is not the innermost pool, this function may panic when
the "std" Cargo feature and debug assertions are enabled.
§Safety
This is equivalent to &*ptr, and shares the unsafety of that, except
the lifetime is bound to the pool instead of being unbounded.
The pool must be the innermost pool for the lifetime to be correct.
Trait Implementations§
Source§impl<'pool> Clone for AutoreleasePool<'pool>
impl<'pool> Clone for AutoreleasePool<'pool>
Source§fn clone(&self) -> AutoreleasePool<'pool>
fn clone(&self) -> AutoreleasePool<'pool>
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read more