use std::cell::RefCell;
use std::rc::Rc;
use objc::runtime::Object;
use objc_id::Id;
use crate::foundation::id;
#[derive(Clone, Debug)]
pub struct ObjcProperty(Rc<RefCell<Id<Object>>>);
impl ObjcProperty {
pub fn retain(obj: id) -> Self {
ObjcProperty(Rc::new(RefCell::new(unsafe { Id::from_ptr(obj) })))
}
pub fn from_retained(obj: id) -> Self {
ObjcProperty(Rc::new(RefCell::new(unsafe { Id::from_retained_ptr(obj) })))
}
pub fn with_mut<F: Fn(id)>(&self, handler: F) {
let mut obj = self.0.borrow_mut();
handler(&mut **obj);
}
pub fn get<R, F: Fn(&Object) -> R>(&self, handler: F) -> R {
let obj = self.0.borrow();
handler(&**obj)
}
}
#[derive(Debug, Default)]
pub struct PropertyNullable<T>(Rc<RefCell<Option<T>>>);
impl<T> PropertyNullable<T> {
pub fn new(obj: T) -> Self {
Self(Rc::new(RefCell::new(Some(obj))))
}
pub fn clone(&self) -> Self {
Self(Rc::clone(&self.0))
}
pub fn with<F>(&self, handler: F)
where
F: Fn(&T)
{
let borrow = self.0.borrow();
if let Some(s) = &*borrow {
handler(s);
}
}
pub fn set(&self, obj: T) {
let mut borrow = self.0.borrow_mut();
*borrow = Some(obj);
}
}