madsmtm / objc2

Bindings to Apple's frameworks in Rust
https://docs.rs/objc2/
MIT License
290 stars 35 forks source link

Redo instance variables #521

Closed madsmtm closed 6 months ago

madsmtm commented 8 months ago

Using a combination of what's described here and here, now we have:

#[derive(Debug, PartialEq, Eq, Hash, Clone)]
struct MyState {
    my_variable: CanBeAnything,
    // ...
}

declare_class!(
    struct MyClass;

    unsafe impl ClassType for MyClass {
        type Super = NSObject;
        type Mutability = InteriorMutable;
        const NAME: &'static str = "MyClass";
    }

    impl DeclaredClass for MyClass {
        type Ivars = MyState; // Or even `RefCell<MyState>`, depending on if you want fine-grained or coarse locking
    }

    unsafe impl MyClass {
        #[method_id(init)]
        fn init(this: Allocated<Self>) -> Option<Id<Self>> {
            let this = this.set_ivars(MyState {
                my_variable: Default::default(),
                // ...
            });
            unsafe { msg_send_id![super(this), init] }
        }

        #[method(doStuff)]
        fn do_stuff(&self) {
            self.ivars().my_variable.do_stuff();
        }
    }
);

Fixes https://github.com/madsmtm/objc2/issues/414. Fixes https://github.com/madsmtm/objc2/issues/438. Fixes https://github.com/madsmtm/objc2/issues/253. Fixes https://github.com/madsmtm/objc2/issues/513. Fixes https://github.com/madsmtm/objc2/issues/458. Replaces / fixes https://github.com/madsmtm/objc2/pull/288. Replaces / fixes https://github.com/madsmtm/objc2/pull/411. Replaces / fixes https://github.com/madsmtm/objc2/pull/173.

TODO: