docs

你正在阅读 v0.1.2 的文档。Nabi 0.1.2 已不再提供支持。 最新版本:v0.1.3 →

本页尚未翻译,以下为英文原文。

#Objective-C and Apple Frameworks

本页内容

On macOS the system's own libraries, Foundation, AppKit, Metal and the rest, are Objective-C classes. Nabi calls them directly: you declare the classes and methods you use in an extern "objc" block, and each method becomes an ordinary Nabi method that sends the Objective-C message. No C compiler or glue code is involved. For Apple's frameworks you rarely write those blocks yourself: ffi::objc::import reads the SDK's headers and writes them (Importing the SDK's headers). The first sections declare by hand, which shows what an import gives you.

Everything in this chapter works only on Apple targets (aarch64-apple-darwin). Its code blocks are not run when the site is built; each was compiled and run on a Mac, with the output shown.

#Declaring a class

An extern "objc" block declares one class. #[objc::class(NSArray)] makes the type NSArray; its methods are written like extern "C" functions, with self for instance methods:

  • A method without self is a class method, called on the type: NSMutableArray::array().
  • extends(NSArray) makes NSArray the superclass, and NSMutableArray gets its methods: count and componentsJoinedByString work on fruit. A class's methods are traits implemented for it and its subclasses, so in another module they need use of that module's items. Without extends the superclass is NSObject, whose methods (description, isEqual, hash, ..) every object has.
  • Id<Self> is the class the method is called on, Objective-C's instancetype.
  • Objects are Id<T>. A parameter declared Id<NSObject> takes any object, so ns(f), an Id<NSString>, goes straight in.
  • {x} prints an object's description, as NSLog would.

#Method names are selectors

The name of a method is its Objective-C selector, with _ where the selector has a : between parts: componentsJoinedByString(sep) sends componentsJoinedByString:, and initWithBytes_length_encoding(b, n, e) would send initWithBytes:length:encoding:. So Apple's documentation reads one to one. When the Nabi name should differ, give the selector:

nabi
use bare::ffi::objc::{Id, NSString, ns};

#[link(name = "Foundation", kind = "framework")]
#[objc::category(NSString)]
extern "objc" {
    fn length(self) -> usize;
    fn uppercaseString(self) -> Id<NSString>;
    #[selector("isEqualToString:")]
    fn same_text(self, other: Id<NSString>) -> bool;
}

let s = ns("héllo");
println(f"{s.length()} {s.uppercaseString()} {s.same_text(ns("héllo"))}");
println(s.uppercaseString().to_str());
5 HÉLLO true
HÉLLO

NSString is already declared by bare::ffi::objc, so this block is a category: #[objc::category(NSString)] adds methods to a class declared elsewhere. ns("text") makes an NSString from a str and to_str() copies one back.

If a name's parts do not match its parameters, the compiler says so and shows both ways to write it:

error[E0084]: `initWithBytes_length` has 3 parameter(s), so its selector has 3 part(s): name it after the selector with `_` between the parts (`initWithBytes_length` for `initWithBytes:length:`), or give it with `#[selector("..")]`

#nil, none and errors

A method declared to return Id<T> panics if it gets nil, naming the method. When nil is a normal answer, declare Id<T> | none:

Cocoa reports errors through a last NSError ** parameter. Leave it out and write throws (objc::Error): the call then needs try, and the error is caught like any other (chapter 10). The name keeps the _error part, because the selector does.

#Blocks are closures

A parameter of a closure type passes an Objective-C block. Pass a closure as you would to any Nabi function:

The closure lives as long as Objective-C keeps the block. A completion handler may run on another thread; share only thread-safe values with it, such as an Atomic, a Mutex or a channel.

#Who frees an object

An Id<T> holds one retain of its object, and copies of the Id share it. Nabi follows Cocoa's naming rule: what alloc, new, copy, mutableCopy and init return is yours already, everything else is retained for you. Either way the Id ends up with exactly one retain.

When no copy of an Id is left, the garbage collector releases its object, like any other value it frees. release_now() releases it at once, for an object that holds something scarce (a file, a window); using any copy afterwards panics with a message instead of touching freed memory. Objects Objective-C autoreleases are released by an autorelease pool; wrap loops that make many of them in objc::autoreleasepool:

objc::WeakId::new(id) refers to an object without keeping it alive; load() gives none once it is gone. Use it to break a cycle, such as a delegate that holds the window holding it.

#A Metal compute kernel

Metal objects are known by protocols (MTLDevice, MTLBuffer, ..) rather than classes: declare them with #[objc::protocol(..)]. This program compiles a kernel from source, runs it on the GPU over 1024 numbers and checks the result:

MTLCreateSystemDefaultDevice is a C function, declared in an extern "C" block; its result is a +1 object, which Id::from_retained takes over. MTLSize is a plain #[repr(C)] struct, passed by value as C passes it.

#Importing the SDK's headers

Declaring every method by hand is how the blocks above work, but Apple's frameworks have thousands of them. ffi::objc::import reads the SDK's own headers and writes those blocks for you:

nabi
mod ns {
    ffi::objc::import { "Foundation/Foundation.h" }
}
use ns::*;
use bare::ffi::objc;
use bare::ffi::objc::ns;

let s = ns("hello, objc");
let parts = s.componentsSeparatedByString(ns(", "));
let last = parts.lastObject() ?? panic("empty");
println(f"{s.length()} {s.uppercaseString().to_str()} {parts.count()} {last}");

let flags = NSCaseInsensitiveSearch | NSLiteralSearch;
println(f"options {flags.contains(NSLiteralSearch)} {flags.contains(NSBackwardsSearch)}");

try NSString::stringWithContentsOfFile_encoding_error(ns("/nonexistent/nabi"), NSUTF8StringEncoding)
    catch e: objc::Error { println(f"error {e.domain()} {e.code()}"); ns("") };
println(f"domain {NSCocoaErrorDomain().to_str()}");
11 HELLO, OBJC 2 objc
options true false
error NSCocoaErrorDomain 260
domain NSCocoaErrorDomain
  • Name each header as Framework/Header.h. Put every framework whose methods you call in one import: { "Foundation/Foundation.h", "AppKit/AppKit.h", "Metal/Metal.h" }.
  • The bindings go into the module that holds the import. A class's methods are traits there, so bring them into scope with use ns::*;, which also brings Id, NSString and the rest.
  • The headers say what may be nil: lastObject returns Id<NSObject> | none, uppercaseString an Id<NSString>. A last NSError ** becomes throws (objc::Error), NS_OPTIONS types take |, & and contains, and constants such as NSCocoaErrorDomain are functions.
  • The first build reads the headers; it writes the bindings into the toolchain's cache, and later builds read that one file. nabi bindgen -x objective-c <header> prints the same bindings, to read what an import gives you.

#Newer APIs

A program runs on every macOS from its deployment target on, 11.0 unless the manifest says deployment_target: "13.0". The headers mark APIs that came later, and the compiler refuses a call that might run on a macOS without it:

error[E0084]: `maximumConcurrentCompilationTaskCount` needs macOS 13.3, the deployment target is 11.0: wrap it in `if objc::available(macos: "13.3") { .. }`, or raise the deployment target (`deployment_target: "13.3"` in nabi.nabion, or `MACOSX_DEPLOYMENT_TARGET=13.3`)

Inside if objc::available(macos: "13.3") { .. } the call is allowed, and on an older macOS the block is skipped:

nabi
mod mtl {
    ffi::objc::import { "Metal/Metal.h" }
}
use mtl::*;
use bare::ffi::objc;

let d = MTLCreateSystemDefaultDevice() ?? panic("no Metal device");
if objc::available(macos: "13.3") {
    println(f"compile tasks {d.maximumConcurrentCompilationTaskCount()}");
}
compile tasks 6

#A window with a delegate

An AppKit app hands events to a delegate, an object of a class you provide. ClassBuilder makes such a class at run time from extern "C" functions; each takes the receiver and the selector first, then the method's arguments, and the type encoding ("v@:@": returns nothing, takes an object) tells Objective-C its signature. This program opens a window, closes it from the run loop as a click would, and ends with its last window:

  • setDelegate takes an Id<NSApplicationDelegate>: the class made here conforms to the protocol, which cast tells Nabi.
  • Block::new_main_thread makes a block from a closure that is not Send, for the main queue; dispatch_async runs it from the run loop. Block::new takes a Send closure for any queue.
  • Window objects are released on the main thread, as AppKit requires, even when the collector finds them dead on another.

#A Metal triangle

With the generated bindings Metal needs no declarations of its own. This program compiles two shaders, draws one red triangle into a 64x64 texture and reads the pixels back:

MTLCreateSystemDefaultDevice returns Id<MTLDevice> | none: the header marks it nullable, and its NS_RETURNS_RETAINED tells Nabi the result is already owned. Structs such as MTLRegion and MTLClearColor are plain #[repr(C)] structs, passed by value.

#Blocks of your own

A C function that takes a block, such as dispatch_async, gets a Block. bare::ffi::objc has the dispatch queues:

nabi
use bare::ffi::objc::{Block, Queue, dispatch_async};

let total = Atomic::new(0);
for i in 1..=8 {
    dispatch_async(Queue::global(), Block::new(|| { total.fetch_add(i); }));
}

Block::new needs a Send closure, since the queue runs it on another thread. A block Objective-C passes in arrives as a BlockRef, valid during the call; copy() keeps it.

#Summary

  • #[objc::class(C)] / #[objc::class(C, extends(S))] on an extern "objc" block declares a class; #[objc::protocol(P)] a type for objects known by a protocol; #[objc::category(C)] adds methods to a declared class.
  • Methods with self are on Id<C>, those without on C; a subclass gets its superclass's methods.
  • A method's name is its selector with _ for the inner :s, or #[selector("..")] gives it.
  • Results: Id<T> (nil panics), Id<T> | none; throws (objc::Error) replaces a last NSError **.
  • A closure parameter is a block.
  • An Id holds one retain, which the collector gives back after the last copy; release_now() frees the object at once, objc::autoreleasepool drains what Objective-C autoreleased, WeakId breaks cycles.
  • ffi::objc::import { "Framework/Header.h", .. } writes the blocks from the SDK's headers; use the module's items to call them.
  • An API newer than the deployment target is called inside if objc::available(macos: "..") { .. }.
  • ClassBuilder makes a delegate class from extern "C" functions; Block and dispatch_async run closures on dispatch queues.

#Further reading

Found a mistake? Edit this page on GitHub. Last updated