use std::ops::{Deref, DerefMut};
use objc::runtime::Object;
use objc::{class, msg_send, sel, sel_impl};
use objc_id::Id;
use crate::foundation::id;
#[derive(Debug)]
pub struct NSArray(pub Id<Object>);
impl NSArray {
pub fn new(objects: &[id]) -> Self {
NSArray(unsafe {
Id::from_ptr(msg_send![class!(NSArray),
arrayWithObjects:objects.as_ptr()
count:objects.len()
])
})
}
pub fn retain(array: id) -> Self {
NSArray(unsafe { Id::from_ptr(array) })
}
pub fn from_retained(array: id) -> Self {
NSArray(unsafe { Id::from_retained_ptr(array) })
}
pub fn count(&self) -> usize {
unsafe { msg_send![&*self.0, count] }
}
pub fn map<T, F: Fn(id) -> T>(&self, transform: F) -> Vec<T> {
let count = self.count();
let objc = &*self.0;
(0..count)
.map(|index| {
let item: id = unsafe { msg_send![objc, objectAtIndex: index] };
transform(item)
})
.collect()
}
}
impl From<Vec<&Object>> for NSArray {
fn from(objects: Vec<&Object>) -> Self {
NSArray(unsafe {
Id::from_ptr(msg_send![class!(NSArray),
arrayWithObjects:objects.as_ptr()
count:objects.len()
])
})
}
}
impl From<Vec<id>> for NSArray {
fn from(objects: Vec<id>) -> Self {
NSArray(unsafe {
Id::from_ptr(msg_send![class!(NSArray),
arrayWithObjects:objects.as_ptr()
count:objects.len()
])
})
}
}
impl From<NSArray> for id {
fn from(mut array: NSArray) -> Self {
&mut *array
}
}
impl Deref for NSArray {
type Target = Object;
fn deref(&self) -> &Object {
&*self.0
}
}
impl DerefMut for NSArray {
fn deref_mut(&mut self) -> &mut Object {
&mut *self.0
}
}