Expand description
Utilities for reference counting Objective-C objects.
These utilities in this module provide ARC-like semantics for working with Objective-C’s reference counted objects.
A smart pointer Id
is provided to ensure that Objective-C objects are
retained and released when created and dropped, respectively.
To enforce aliasing rules, an Id
can be either owned or shared; if it is
owned, meaning the Id
is the only reference to the object, it can be
mutably dereferenced. An owned Id
can be converted to a shared Id
,
which can be cloned to allow multiple references.
Weak references may be created using the WeakId
struct; these will not
retain the object, but one can attempt to load them and obtain an Id
, or
safely fail if the object has been deallocated.
See the clang documentation and the Apple article on memory management (similar document exists for Core Foundation) for more information on automatic and manual reference counting.
It can also be useful to enable Malloc Debugging if you’re trying to figure out if/where your application has memory errors and leaks.
Example
use objc2::{class, msg_send_id};
use objc2::rc::{autoreleasepool, Id, Shared, WeakId};
use objc2::runtime::Object;
// Id will release the object when dropped
let obj: Id<Object, Shared> = unsafe {
msg_send_id![class!(NSObject), new].unwrap()
};
// Cloning retains the object an additional time
let cloned = obj.clone();
autoreleasepool(|pool| {
// Autorelease consumes the Id, but won't
// actually release until the end of an autoreleasepool
let obj_ref: &Object = cloned.autorelease(pool);
});
// Weak references won't retain the object
let weak = WeakId::new(&obj);
drop(obj);
assert!(weak.load().is_none());
Structs
A marker type that can be used within Id
to indicate that the object
has been allocated but not initialized.
An Objective-C autorelease pool.
An pointer for Objective-C reference counted objects.
A pointer type for a weak reference to an Objective-C reference counted object.
Enums
A type used to mark that a struct owns the object(s) it contains, so it has the sole references to them.
A type used to mark that the object(s) a struct contains are shared, so there may be other references to them.
Traits
Marks types that are safe to pass across the closure in an
autoreleasepool
.
Helper trait for functionality on slices containing owned Id
s.
Functions
Execute f
in the context of a new autorelease pool. The pool is
drained after the execution of f
completes.