Module objc2::rc

source ·
Expand description

Reference counting utilities.

The types in this module provide roughly the same benefits as ARC does to Objective-C.

Most importantly, a smart pointer Id is provided to ensure that objects are correctly retained and released when created and dropped, respectively. This ties in strongly with the msg_send_id! macro.

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::rc::{autoreleasepool, Id, WeakId};
use objc2::runtime::NSObject;

// Id will release the object when dropped
let obj: Id<NSObject> = NSObject::new();

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

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

Structs

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

Traits

Functions

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