Skip to main content

polyhorn_ios_sys/foundation/
array.rs

1use objc::runtime::*;
2use objc::*;
3
4use crate::{IntoRaw, Raw};
5
6/// Declares the programmatic interface to objects that manage a modifiable
7/// array of objects. This class adds insertion and deletion operations to the
8/// basic array-handling behavior inherited from `NSArray`.
9pub struct NSMutableArray {
10    object: *mut Object,
11}
12
13impl NSMutableArray {
14    /// Initializes a newly allocated array.
15    pub fn new() -> NSMutableArray {
16        unsafe {
17            let mut object: *mut Object = msg_send![class!(NSMutableArray), alloc];
18            object = msg_send![object, init];
19            NSMutableArray::from_raw(object)
20        }
21    }
22
23    /// Inserts a given object at the end of the array.
24    pub fn add_object(&mut self, object: &impl Raw) {
25        unsafe {
26            let _: () = msg_send![self.object, addObject: object.as_raw()];
27        }
28    }
29}
30
31impl Raw for NSMutableArray {
32    unsafe fn from_raw(object: *mut Object) -> Self {
33        NSMutableArray { object }
34    }
35
36    unsafe fn as_raw(&self) -> *mut Object {
37        self.object
38    }
39}
40
41impl Drop for NSMutableArray {
42    fn drop(&mut self) {
43        unsafe { objc_release(self.object) }
44    }
45}
46
47impl<T> IntoRaw for &[T]
48where
49    T: Copy + IntoRaw,
50{
51    type Raw = NSMutableArray;
52
53    fn into_raw(self) -> Self::Raw {
54        let mut result = NSMutableArray::new();
55
56        for element in self {
57            let element = element.into_raw();
58            result.add_object(&element)
59        }
60
61        result
62    }
63}