Crate objc [] [src]

Objective-C Runtime bindings and wrapper for Rust.

Messaging objects

Objective-C objects can be messaged using the msg_send! macro:

let cls = Class::get("NSObject").unwrap();
let obj: *mut Object = msg_send![cls, new];
let hash: usize = msg_send![obj, hash];
let is_kind: BOOL = msg_send![obj, isKindOfClass:cls];
// Even void methods must have their return type annotated
let _: () = msg_send![obj, release];

Reference counting

Objective-C objects are reference counted; to ensure that they are retained and released at the proper times, we can use the Id struct.

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 downgraded to a ShareId which can be cloned to allow multiple references.

Weak references may be created using the WeakId struct.

let cls = Class::get("NSObject").unwrap();
let obj: Id<Object> = unsafe {
    Id::from_retained_ptr(msg_send![cls, new])
};
// obj will be released when it goes out of scope

// share the object so we can clone it
let obj = obj.share();
let another_ref = obj.clone();
// dropping our other reference will decrement the retain count
drop(another_ref);

let weak = WeakId::new(&obj);
assert!(weak.load().is_some());
// After the object is deallocated, our weak pointer returns none
drop(obj);
assert!(weak.load().is_none());

Declaring classes

Objective-C classes can even be declared from Rust using the functionality of the declare module.

Modules

declare

Functionality for declaring Objective-C classes.

runtime

A Rust interface for the functionality of the Objective-C runtime.

Macros

msg_send!

Sends a message to an object.

sel!

Registers a selector, returning a Sel.

Structs

Encoding

An Objective-C type encoding.

Id

A pointer type for Objective-C's reference counted objects.

WeakId

A pointer type for a weak reference to an Objective-C reference counted object.

Enums

Owned

A type used to mark that a struct owns the object(s) it contains, so it has the sole references to them.

Shared

A type used to mark that the object(s) a struct contains are shared, so there may be other references to them.

Traits

Encode

Types that have an Objective-C type encoding.

Message

Types that may be sent Objective-C messages. For example: objects, classes, and blocks.

MessageArguments

Types that may be used as the arguments of an Objective-C message.

Ownership

A type that marks what type of ownership a struct has over the object(s) it contains; specifically, either Owned or Shared.

Type Definitions

ShareId

A convenient alias for a shared Id.