Macro objc2_foundation::extern_class
source · [−]macro_rules! extern_class {
(
$(#[$m:meta])*
unsafe $v:vis struct $name:ident: $($inheritance_chain:ty),+;
) => { ... };
}
Expand description
Create a new type to represent an Objective-C class.
The given name should correspond to a valid Objective-C class, whose
instances have the encoding Encoding::Object
(as an example:
NSAutoreleasePool
does not have this).
Specification
This creates an opaque struct, and implements traits for it to allow easier usage as an Objective-C object.
The traits objc2::RefEncode
and objc2::Message
are implemented to
allow sending messages to the object and using it in objc2::rc::Id
.
An associated function class
is created on the object as a convenient
shorthand so that you can do MyObject::class()
instead of
class!(MyObject)
.
Deref
and DerefMut
are implemented and delegate to the first
superclass (direct parent). Auto traits are inherited from this superclass
as well (this macro effectively just creates a newtype wrapper around the
superclass).
Finally, AsRef
, AsMut
, Borrow
and BorrowMut
are
implemented to allow conversion to an arbitary superclasses in the
inheritance chain (since an instance of a class can always be interpreted
as its superclasses).
Safety
The specified inheritance chain must be correct, including in the correct order, and the types in said chain must be valid as Objective-C objects (this is easy to ensure by also creating those using this macro).
The object must respond to standard memory management messages (this is
upheld if NSObject
is part of its inheritance chain).
Example
Create a new type to represent the NSFormatter
class.
use objc2::msg_send_id;
use objc2::rc::{Id, Shared};
use objc2_foundation::{extern_class, NSObject};
extern_class! {
/// An example description.
#[derive(PartialEq, Eq, Hash)] // Uses `NSObject`'s implementation
// Specify class and superclass
// In this case the class `NSFormatter`, which subclasses `NSObject`
unsafe pub struct NSFormatter: NSObject;
}
// Provided by the macro
let cls = NSFormatter::class();
// `NSFormatter` implements `Message`:
let obj: Id<NSFormatter, Shared> = unsafe { msg_send_id![cls, new].unwrap() };
Represent the NSDateFormatter
class, using the NSFormatter
type we
declared previously to specify as its superclass.
use objc2_foundation::{extern_class, NSObject};
extern_class! {
#[derive(PartialEq, Eq, Hash)]
// Specify the correct inheritance chain
// `NSDateFormatter` subclasses `NSFormatter` which subclasses `NSObject`
unsafe pub struct NSDateFormatter: NSFormatter, NSObject;
}
See the source code of objc2_foundation
in general for more examples.