[go: up one dir, main page]

Module rc

Module rc 

Source
Expand description

§Reference counting utilities.

The types in this module provide roughly the same benefits as ARC (Automatic Reference Counting) does to Objective-C.

Most importantly, a smart pointer Retained is provided to ensure that objects are correctly retained and released when created and dropped, respectively.

Weak references may be created using the Weak struct; these will not retain the object, but one can attempt to load them and obtain an Retained, 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::rc::{autoreleasepool, Retained, Weak};
use objc2::runtime::NSObject;

// Allocate and initialize a new `NSObject`.
// `Retained` will release the object when dropped.
let obj: Retained<NSObject> = NSObject::new();

// Cloning retains the object an additional time
let cloned = obj.clone();
autoreleasepool(|pool| {
    // Autorelease consumes the Retained, but won't actually
    // release it until the end of the autoreleasepool
    // SAFETY: The given is the innermost pool.
    let obj_ref: &NSObject = unsafe { Retained::autorelease(cloned, pool) };
});

// Weak references won't retain the object
let weak = Weak::from_retained(&obj);
drop(obj);
assert!(weak.load().is_none());

Structs§

Allocated
An Objective-C object that has been allocated, but not initialized.
AutoreleasePool
An Objective-C autorelease pool.
PartialInit
An Objective-C object that has been allocated and initialized in the current class, but not yet initialized in the superclass.
Retained
A reference counted pointer type for Objective-C objects.
Weak
A weak pointer to an Objective-C reference counted object.

Traits§

AutoreleaseSafe
Marks types that are safe to pass across the closure in an autoreleasepool.
DefaultRetained
Helper trait to implement Default on Retained.
RetainedFromIterator
Helper trait to implement FromIterator on Retained.
RetainedIntoIterator
Helper trait to implement IntoIterator on Retained.

Functions§

autoreleasepool
Execute f in the context of a new autorelease pool. The pool is drained after the execution of f completes.
autoreleasepool_leaking
Execute f in the context of a “fake” autorelease pool.

Type Aliases§

IdDeprecated
Short type-alias to Retained.
WeakIdDeprecated
Fully-deprecated type-alias to Weak.