-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathdeclare_class_delegate_not_mainthreadonly.rs
58 lines (47 loc) · 1.79 KB
/
declare_class_delegate_not_mainthreadonly.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
//! Test that implementing `NSApplicationDelegate` and similar requires
//! a `MainThreadOnly` class.
use objc2::rc::Retained;
use objc2::{
declare_class, extern_methods, extern_protocol, AllocAnyThread, ClassType, DeclaredClass,
MainThreadOnly, ProtocolType,
};
use objc2_foundation::{MainThreadMarker, NSNotification, NSObject, NSObjectProtocol};
// Use fake `NSApplicationDelegate` so that this works on iOS too.
extern_protocol!(
pub unsafe trait NSApplicationDelegate: NSObjectProtocol + MainThreadOnly {
#[optional]
#[method(applicationDidFinishLaunching:)]
unsafe fn applicationDidFinishLaunching(&self, notification: &NSNotification);
// snip
}
unsafe impl ProtocolType for dyn NSApplicationDelegate {}
);
declare_class!(
struct CustomObject;
unsafe impl ClassType for CustomObject {
type Super = NSObject;
type ThreadKind = dyn AllocAnyThread; // Not `MainThreadOnly`
const NAME: &'static str = "CustomObject";
}
impl DeclaredClass for CustomObject {}
unsafe impl NSObjectProtocol for CustomObject {}
unsafe impl NSApplicationDelegate for CustomObject {
#[method(applicationDidFinishLaunching:)]
unsafe fn application_did_finish_launching(&self, _notification: &NSNotification) {
// Unclear for the user how to get a main thread marker if `self` is not `MainThreadOnly`
let _mtm = MainThreadMarker::new().unwrap();
}
}
);
extern_methods!(
unsafe impl CustomObject {
#[method_id(new)]
fn new(mtm: MainThreadMarker) -> Retained<Self>;
}
);
fn main() {
let mtm = MainThreadMarker::new().unwrap();
let app = NSApplication::sharedApplication(mtm);
let delegate = CustomObject::new(mtm);
app.setDelegate(Some(&delegate));
}