pub struct NSArray<ObjectType: ?Sized = AnyObject> { /* private fields */ }
NSArray
only.Expand description
************** Immutable Array ***************
See also Apple’s documentation
Implementations§
Source§impl<ObjectType: Message> NSArray<ObjectType>
Convenience creation methods.
impl<ObjectType: Message> NSArray<ObjectType>
Convenience creation methods.
Sourcepub fn from_slice(slice: &[&ObjectType]) -> Retained<Self>
pub fn from_slice(slice: &[&ObjectType]) -> Retained<Self>
Create a new array from a slice of objects.
This is a safe interface to initWithObjects:count:
.
§Examples
use objc2_foundation::{NSArray, ns_string};
let array = NSArray::from_slice(&[
ns_string!("abc"),
ns_string!("def"),
ns_string!("ghi"),
]);
Sourcepub fn from_retained_slice(slice: &[Retained<ObjectType>]) -> Retained<Self>
pub fn from_retained_slice(slice: &[Retained<ObjectType>]) -> Retained<Self>
Create a new array from a slice of retained objects.
This is a safe interface to initWithObjects:count:
.
§Examples
use objc2_foundation::{NSArray, NSObject};
let array = NSArray::from_retained_slice(&[
NSObject::new(),
NSObject::new(),
NSObject::new(),
]);
Source§impl<ObjectType: Message> NSArray<ObjectType>
Direct, unsafe object accessors.
impl<ObjectType: Message> NSArray<ObjectType>
Direct, unsafe object accessors.
Foundation’s collection types store their items in such a way that they can give out references to their data without having to autorelease it first, see the docs.
This means that we can more efficiently access the array’s objects, but
only if the array isn’t mutated via e.g. NSMutableArray
methods while
doing so - otherwise, we might end up accessing a deallocated object.
Sourcepub unsafe fn objectAtIndex_unchecked(&self, index: usize) -> &ObjectType
pub unsafe fn objectAtIndex_unchecked(&self, index: usize) -> &ObjectType
Get a direct reference to one of the array’s objects.
Throws an error if the object was not found.
Consider using the objectAtIndex
method
instead, unless you’re seeing performance issues from the retaining.
§Safety
The array must not be mutated while the reference is live.
Sourcepub unsafe fn firstObject_unchecked(&self) -> Option<&ObjectType>
pub unsafe fn firstObject_unchecked(&self) -> Option<&ObjectType>
A direct reference to the array’s first object, if any.
Consider using the firstObject
method instead,
unless you’re seeing performance issues from the retaining.
§Safety
The array must not be mutated while the reference is live.
Sourcepub unsafe fn lastObject_unchecked(&self) -> Option<&ObjectType>
pub unsafe fn lastObject_unchecked(&self) -> Option<&ObjectType>
A direct reference to the array’s last object, if any.
Consider using the lastObject
method instead,
unless you’re seeing performance issues from the retaining.
§Safety
The array must not be mutated while the reference is live.
Sourcepub unsafe fn to_vec_unchecked(&self) -> Vec<&ObjectType>
pub unsafe fn to_vec_unchecked(&self) -> Vec<&ObjectType>
Sourcepub unsafe fn iter_unchecked(&self) -> IterUnchecked<'_, ObjectType> ⓘ
Available on crate feature NSEnumerator
only.
pub unsafe fn iter_unchecked(&self) -> IterUnchecked<'_, ObjectType> ⓘ
NSEnumerator
only.Source§impl<ObjectType: Message> NSArray<ObjectType>
Various accessor methods.
impl<ObjectType: Message> NSArray<ObjectType>
Various accessor methods.
Source§impl<ObjectType: Message> NSArray<ObjectType>
impl<ObjectType: Message> NSArray<ObjectType>
pub fn count(&self) -> NSUInteger
pub fn objectAtIndex(&self, index: NSUInteger) -> Retained<ObjectType>
pub fn init(this: Allocated<Self>) -> Retained<Self>
Sourcepub unsafe fn initWithObjects_count(
this: Allocated<Self>,
objects: *mut NonNull<ObjectType>,
cnt: NSUInteger,
) -> Retained<Self>
pub unsafe fn initWithObjects_count( this: Allocated<Self>, objects: *mut NonNull<ObjectType>, cnt: NSUInteger, ) -> Retained<Self>
§Safety
objects
must be a valid pointer or null.
Source§impl<ObjectType: Message> NSArray<ObjectType>
NSExtendedArray.
impl<ObjectType: Message> NSArray<ObjectType>
NSExtendedArray.
pub fn arrayByAddingObject( &self, an_object: &ObjectType, ) -> Retained<NSArray<ObjectType>>
pub fn arrayByAddingObjectsFromArray( &self, other_array: &NSArray<ObjectType>, ) -> Retained<NSArray<ObjectType>>
pub fn componentsJoinedByString( &self, separator: &NSString, ) -> Retained<NSString>
NSString
only.pub fn containsObject(&self, an_object: &ObjectType) -> bool
pub fn description(&self) -> Retained<NSString>
NSString
only.Sourcepub unsafe fn descriptionWithLocale(
&self,
locale: Option<&AnyObject>,
) -> Retained<NSString>
Available on crate feature NSString
only.
pub unsafe fn descriptionWithLocale( &self, locale: Option<&AnyObject>, ) -> Retained<NSString>
NSString
only.§Safety
locale
should be of the correct type.
Sourcepub unsafe fn descriptionWithLocale_indent(
&self,
locale: Option<&AnyObject>,
level: NSUInteger,
) -> Retained<NSString>
Available on crate feature NSString
only.
pub unsafe fn descriptionWithLocale_indent( &self, locale: Option<&AnyObject>, level: NSUInteger, ) -> Retained<NSString>
NSString
only.§Safety
locale
should be of the correct type.
pub fn firstObjectCommonWithArray( &self, other_array: &NSArray<ObjectType>, ) -> Option<Retained<ObjectType>>
Sourcepub unsafe fn getObjects_range(
&self,
objects: NonNull<NonNull<ObjectType>>,
range: NSRange,
)
Available on crate feature NSRange
only.
pub unsafe fn getObjects_range( &self, objects: NonNull<NonNull<ObjectType>>, range: NSRange, )
NSRange
only.§Safety
objects
must be a valid pointer.
pub fn indexOfObject(&self, an_object: &ObjectType) -> NSUInteger
pub fn indexOfObject_inRange( &self, an_object: &ObjectType, range: NSRange, ) -> NSUInteger
NSRange
only.pub fn indexOfObjectIdenticalTo(&self, an_object: &ObjectType) -> NSUInteger
pub fn indexOfObjectIdenticalTo_inRange( &self, an_object: &ObjectType, range: NSRange, ) -> NSUInteger
NSRange
only.pub fn isEqualToArray(&self, other_array: &NSArray<ObjectType>) -> bool
pub fn firstObject(&self) -> Option<Retained<ObjectType>>
pub fn lastObject(&self) -> Option<Retained<ObjectType>>
Sourcepub unsafe fn objectEnumerator(&self) -> Retained<NSEnumerator<ObjectType>>
Available on crate feature NSEnumerator
only.
pub unsafe fn objectEnumerator(&self) -> Retained<NSEnumerator<ObjectType>>
NSEnumerator
only.§Safety
The returned enumerator’s underlying collection should not be mutated while in use.
Sourcepub unsafe fn reverseObjectEnumerator(
&self,
) -> Retained<NSEnumerator<ObjectType>>
Available on crate feature NSEnumerator
only.
pub unsafe fn reverseObjectEnumerator( &self, ) -> Retained<NSEnumerator<ObjectType>>
NSEnumerator
only.§Safety
The returned enumerator’s underlying collection should not be mutated while in use.
pub fn sortedArrayHint(&self) -> Retained<NSData>
NSData
only.Sourcepub unsafe fn sortedArrayUsingFunction_context(
&self,
comparator: unsafe extern "C-unwind" fn(NonNull<ObjectType>, NonNull<ObjectType>, *mut c_void) -> NSInteger,
context: *mut c_void,
) -> Retained<NSArray<ObjectType>>
pub unsafe fn sortedArrayUsingFunction_context( &self, comparator: unsafe extern "C-unwind" fn(NonNull<ObjectType>, NonNull<ObjectType>, *mut c_void) -> NSInteger, context: *mut c_void, ) -> Retained<NSArray<ObjectType>>
§Safety
comparator
must be implemented correctly.context
must be a valid pointer or null.
Sourcepub unsafe fn sortedArrayUsingFunction_context_hint(
&self,
comparator: unsafe extern "C-unwind" fn(NonNull<ObjectType>, NonNull<ObjectType>, *mut c_void) -> NSInteger,
context: *mut c_void,
hint: Option<&NSData>,
) -> Retained<NSArray<ObjectType>>
Available on crate feature NSData
only.
pub unsafe fn sortedArrayUsingFunction_context_hint( &self, comparator: unsafe extern "C-unwind" fn(NonNull<ObjectType>, NonNull<ObjectType>, *mut c_void) -> NSInteger, context: *mut c_void, hint: Option<&NSData>, ) -> Retained<NSArray<ObjectType>>
NSData
only.§Safety
comparator
must be implemented correctly.context
must be a valid pointer or null.
Sourcepub unsafe fn sortedArrayUsingSelector(
&self,
comparator: Sel,
) -> Retained<NSArray<ObjectType>>
pub unsafe fn sortedArrayUsingSelector( &self, comparator: Sel, ) -> Retained<NSArray<ObjectType>>
§Safety
comparator
must be a valid selector.
pub fn subarrayWithRange(&self, range: NSRange) -> Retained<NSArray<ObjectType>>
NSRange
only.pub unsafe fn writeToURL_error( &self, url: &NSURL, ) -> Result<(), Retained<NSError>>
NSError
and NSURL
only.Sourcepub unsafe fn makeObjectsPerformSelector(&self, a_selector: Sel)
pub unsafe fn makeObjectsPerformSelector(&self, a_selector: Sel)
§Safety
a_selector
must be a valid selector.
Sourcepub unsafe fn makeObjectsPerformSelector_withObject(
&self,
a_selector: Sel,
argument: Option<&AnyObject>,
)
pub unsafe fn makeObjectsPerformSelector_withObject( &self, a_selector: Sel, argument: Option<&AnyObject>, )
§Safety
a_selector
must be a valid selector.argument
should be of the correct type.
pub fn objectsAtIndexes( &self, indexes: &NSIndexSet, ) -> Retained<NSArray<ObjectType>>
NSIndexSet
only.pub fn objectAtIndexedSubscript(&self, idx: NSUInteger) -> Retained<ObjectType>
pub fn enumerateObjectsUsingBlock( &self, block: &DynBlock<dyn Fn(NonNull<ObjectType>, NSUInteger, NonNull<Bool>) + '_>, )
block2
only.pub fn enumerateObjectsWithOptions_usingBlock( &self, opts: NSEnumerationOptions, block: &DynBlock<dyn Fn(NonNull<ObjectType>, NSUInteger, NonNull<Bool>) + '_>, )
NSObjCRuntime
and block2
only.pub fn enumerateObjectsAtIndexes_options_usingBlock( &self, s: &NSIndexSet, opts: NSEnumerationOptions, block: &DynBlock<dyn Fn(NonNull<ObjectType>, NSUInteger, NonNull<Bool>) + '_>, )
NSIndexSet
and NSObjCRuntime
and block2
only.pub fn indexOfObjectPassingTest( &self, predicate: &DynBlock<dyn Fn(NonNull<ObjectType>, NSUInteger, NonNull<Bool>) -> Bool + '_>, ) -> NSUInteger
block2
only.pub fn indexOfObjectWithOptions_passingTest( &self, opts: NSEnumerationOptions, predicate: &DynBlock<dyn Fn(NonNull<ObjectType>, NSUInteger, NonNull<Bool>) -> Bool + '_>, ) -> NSUInteger
NSObjCRuntime
and block2
only.pub fn indexOfObjectAtIndexes_options_passingTest( &self, s: &NSIndexSet, opts: NSEnumerationOptions, predicate: &DynBlock<dyn Fn(NonNull<ObjectType>, NSUInteger, NonNull<Bool>) -> Bool + '_>, ) -> NSUInteger
NSIndexSet
and NSObjCRuntime
and block2
only.pub fn indexesOfObjectsPassingTest( &self, predicate: &DynBlock<dyn Fn(NonNull<ObjectType>, NSUInteger, NonNull<Bool>) -> Bool + '_>, ) -> Retained<NSIndexSet>
NSIndexSet
and block2
only.pub fn indexesOfObjectsWithOptions_passingTest( &self, opts: NSEnumerationOptions, predicate: &DynBlock<dyn Fn(NonNull<ObjectType>, NSUInteger, NonNull<Bool>) -> Bool + '_>, ) -> Retained<NSIndexSet>
NSIndexSet
and NSObjCRuntime
and block2
only.pub fn indexesOfObjectsAtIndexes_options_passingTest( &self, s: &NSIndexSet, opts: NSEnumerationOptions, predicate: &DynBlock<dyn Fn(NonNull<ObjectType>, NSUInteger, NonNull<Bool>) -> Bool + '_>, ) -> Retained<NSIndexSet>
NSIndexSet
and NSObjCRuntime
and block2
only.Sourcepub unsafe fn sortedArrayUsingComparator(
&self,
cmptr: NSComparator,
) -> Retained<NSArray<ObjectType>>
Available on crate features NSObjCRuntime
and block2
only.
pub unsafe fn sortedArrayUsingComparator( &self, cmptr: NSComparator, ) -> Retained<NSArray<ObjectType>>
NSObjCRuntime
and block2
only.§Safety
cmptr
must be a valid pointer.
Sourcepub unsafe fn sortedArrayWithOptions_usingComparator(
&self,
opts: NSSortOptions,
cmptr: NSComparator,
) -> Retained<NSArray<ObjectType>>
Available on crate features NSObjCRuntime
and block2
only.
pub unsafe fn sortedArrayWithOptions_usingComparator( &self, opts: NSSortOptions, cmptr: NSComparator, ) -> Retained<NSArray<ObjectType>>
NSObjCRuntime
and block2
only.§Safety
cmptr
must be a valid pointer.
Sourcepub unsafe fn indexOfObject_inSortedRange_options_usingComparator(
&self,
obj: &ObjectType,
r: NSRange,
opts: NSBinarySearchingOptions,
cmp: NSComparator,
) -> NSUInteger
Available on crate features NSObjCRuntime
and NSRange
and block2
only.
pub unsafe fn indexOfObject_inSortedRange_options_usingComparator( &self, obj: &ObjectType, r: NSRange, opts: NSBinarySearchingOptions, cmp: NSComparator, ) -> NSUInteger
NSObjCRuntime
and NSRange
and block2
only.§Safety
cmp
must be a valid pointer.
Source§impl<ObjectType: Message> NSArray<ObjectType>
NSArrayCreation.
impl<ObjectType: Message> NSArray<ObjectType>
NSArrayCreation.
pub fn array() -> Retained<Self>
pub fn arrayWithObject(an_object: &ObjectType) -> Retained<Self>
Sourcepub unsafe fn arrayWithObjects_count(
objects: NonNull<NonNull<ObjectType>>,
cnt: NSUInteger,
) -> Retained<Self>
pub unsafe fn arrayWithObjects_count( objects: NonNull<NonNull<ObjectType>>, cnt: NSUInteger, ) -> Retained<Self>
§Safety
objects
must be a valid pointer.
pub fn arrayWithArray(array: &NSArray<ObjectType>) -> Retained<Self>
pub fn initWithArray( this: Allocated<Self>, array: &NSArray<ObjectType>, ) -> Retained<Self>
pub unsafe fn initWithArray_copyItems( this: Allocated<Self>, array: &NSArray<ObjectType>, flag: bool, ) -> Retained<Self>
pub unsafe fn initWithContentsOfURL_error( this: Allocated<Self>, url: &NSURL, ) -> Result<Retained<NSArray<ObjectType>>, Retained<NSError>>
NSError
and NSURL
only.pub unsafe fn arrayWithContentsOfURL_error( url: &NSURL, ) -> Result<Retained<NSArray<ObjectType>>, Retained<NSError>>
NSError
and NSURL
only.Source§impl<ObjectType: Message> NSArray<ObjectType>
NSArrayDiffing.
impl<ObjectType: Message> NSArray<ObjectType>
NSArrayDiffing.
pub fn differenceFromArray_withOptions_usingEquivalenceTest( &self, other: &NSArray<ObjectType>, options: NSOrderedCollectionDifferenceCalculationOptions, block: &DynBlock<dyn Fn(NonNull<ObjectType>, NonNull<ObjectType>) -> Bool + '_>, ) -> Retained<NSOrderedCollectionDifference<ObjectType>>
NSOrderedCollectionDifference
and block2
only.pub fn differenceFromArray_withOptions( &self, other: &NSArray<ObjectType>, options: NSOrderedCollectionDifferenceCalculationOptions, ) -> Retained<NSOrderedCollectionDifference<ObjectType>>
NSOrderedCollectionDifference
only.pub fn differenceFromArray( &self, other: &NSArray<ObjectType>, ) -> Retained<NSOrderedCollectionDifference<ObjectType>>
NSOrderedCollectionDifference
only.pub fn arrayByApplyingDifference( &self, difference: &NSOrderedCollectionDifference<ObjectType>, ) -> Option<Retained<NSArray<ObjectType>>>
NSOrderedCollectionDifference
only.Source§impl<ObjectType: Message> NSArray<ObjectType>
NSDeprecated.
impl<ObjectType: Message> NSArray<ObjectType>
NSDeprecated.
Sourcepub unsafe fn getObjects(&self, objects: NonNull<NonNull<ObjectType>>)
👎Deprecated: Use -getObjects:range: instead
pub unsafe fn getObjects(&self, objects: NonNull<NonNull<ObjectType>>)
§Safety
objects
must be a valid pointer.
pub unsafe fn arrayWithContentsOfFile( path: &NSString, ) -> Option<Retained<NSArray<ObjectType>>>
NSString
only.pub unsafe fn arrayWithContentsOfURL( url: &NSURL, ) -> Option<Retained<NSArray<ObjectType>>>
NSURL
only.pub unsafe fn initWithContentsOfFile( this: Allocated<Self>, path: &NSString, ) -> Option<Retained<NSArray<ObjectType>>>
NSString
only.pub unsafe fn initWithContentsOfURL( this: Allocated<Self>, url: &NSURL, ) -> Option<Retained<NSArray<ObjectType>>>
NSURL
only.pub unsafe fn writeToFile_atomically( &self, path: &NSString, use_auxiliary_file: bool, ) -> bool
NSString
only.pub unsafe fn writeToURL_atomically( &self, url: &NSURL, atomically: bool, ) -> bool
NSURL
only.Source§impl<ObjectType: Message> NSArray<ObjectType>
NSKeyValueCoding.
impl<ObjectType: Message> NSArray<ObjectType>
NSKeyValueCoding.
pub fn valueForKey(&self, key: &NSString) -> Retained<AnyObject>
NSKeyValueCoding
and NSString
only.Source§impl<ObjectType: Message> NSArray<ObjectType>
NSKeyValueObserverRegistration.
impl<ObjectType: Message> NSArray<ObjectType>
NSKeyValueObserverRegistration.
Sourcepub unsafe fn addObserver_toObjectsAtIndexes_forKeyPath_options_context(
&self,
observer: &NSObject,
indexes: &NSIndexSet,
key_path: &NSString,
options: NSKeyValueObservingOptions,
context: *mut c_void,
)
Available on crate features NSKeyValueObserving
and NSIndexSet
and NSString
only.
pub unsafe fn addObserver_toObjectsAtIndexes_forKeyPath_options_context( &self, observer: &NSObject, indexes: &NSIndexSet, key_path: &NSString, options: NSKeyValueObservingOptions, context: *mut c_void, )
NSKeyValueObserving
and NSIndexSet
and NSString
only.§Safety
observer
should be of the correct type.context
must be a valid pointer or null.
Sourcepub unsafe fn removeObserver_fromObjectsAtIndexes_forKeyPath_context(
&self,
observer: &NSObject,
indexes: &NSIndexSet,
key_path: &NSString,
context: *mut c_void,
)
Available on crate features NSKeyValueObserving
and NSIndexSet
and NSString
only.
pub unsafe fn removeObserver_fromObjectsAtIndexes_forKeyPath_context( &self, observer: &NSObject, indexes: &NSIndexSet, key_path: &NSString, context: *mut c_void, )
NSKeyValueObserving
and NSIndexSet
and NSString
only.§Safety
observer
should be of the correct type.context
must be a valid pointer or null.
Sourcepub unsafe fn removeObserver_fromObjectsAtIndexes_forKeyPath(
&self,
observer: &NSObject,
indexes: &NSIndexSet,
key_path: &NSString,
)
Available on crate features NSKeyValueObserving
and NSIndexSet
and NSString
only.
pub unsafe fn removeObserver_fromObjectsAtIndexes_forKeyPath( &self, observer: &NSObject, indexes: &NSIndexSet, key_path: &NSString, )
NSKeyValueObserving
and NSIndexSet
and NSString
only.§Safety
observer
should be of the correct type.
Sourcepub unsafe fn addObserver_forKeyPath_options_context(
&self,
observer: &NSObject,
key_path: &NSString,
options: NSKeyValueObservingOptions,
context: *mut c_void,
)
Available on crate features NSKeyValueObserving
and NSString
only.
pub unsafe fn addObserver_forKeyPath_options_context( &self, observer: &NSObject, key_path: &NSString, options: NSKeyValueObservingOptions, context: *mut c_void, )
NSKeyValueObserving
and NSString
only.§Safety
observer
should be of the correct type.context
must be a valid pointer or null.
Sourcepub unsafe fn removeObserver_forKeyPath_context(
&self,
observer: &NSObject,
key_path: &NSString,
context: *mut c_void,
)
Available on crate features NSKeyValueObserving
and NSString
only.
pub unsafe fn removeObserver_forKeyPath_context( &self, observer: &NSObject, key_path: &NSString, context: *mut c_void, )
NSKeyValueObserving
and NSString
only.§Safety
observer
should be of the correct type.context
must be a valid pointer or null.
Sourcepub unsafe fn removeObserver_forKeyPath(
&self,
observer: &NSObject,
key_path: &NSString,
)
Available on crate features NSKeyValueObserving
and NSString
only.
pub unsafe fn removeObserver_forKeyPath( &self, observer: &NSObject, key_path: &NSString, )
NSKeyValueObserving
and NSString
only.§Safety
observer
should be of the correct type.
Source§impl<ObjectType: Message> NSArray<ObjectType>
NSPredicateSupport.
impl<ObjectType: Message> NSArray<ObjectType>
NSPredicateSupport.
pub fn filteredArrayUsingPredicate( &self, predicate: &NSPredicate, ) -> Retained<NSArray<ObjectType>>
NSPredicate
only.Source§impl<ObjectType: Message> NSArray<ObjectType>
NSSortDescriptorSorting.
impl<ObjectType: Message> NSArray<ObjectType>
NSSortDescriptorSorting.
pub fn sortedArrayUsingDescriptors( &self, sort_descriptors: &NSArray<NSSortDescriptor>, ) -> Retained<NSArray<ObjectType>>
NSSortDescriptor
only.Methods from Deref<Target = NSObject>§
Sourcepub fn doesNotRecognizeSelector(&self, sel: Sel) -> !
pub fn doesNotRecognizeSelector(&self, sel: Sel) -> !
Handle messages the object doesn’t recognize.
See Apple’s documentation for details.
Methods from Deref<Target = AnyObject>§
Sourcepub fn class(&self) -> &'static AnyClass
pub fn class(&self) -> &'static AnyClass
Dynamically find the class of this object.
§Panics
May panic if the object is invalid (which may be the case for objects
returned from unavailable init
/new
methods).
§Example
Check that an instance of NSObject
has the precise class NSObject
.
use objc2::ClassType;
use objc2::runtime::NSObject;
let obj = NSObject::new();
assert_eq!(obj.class(), NSObject::class());
Sourcepub unsafe fn get_ivar<T>(&self, name: &str) -> &Twhere
T: Encode,
👎Deprecated: this is difficult to use correctly, use Ivar::load
instead.
pub unsafe fn get_ivar<T>(&self, name: &str) -> &Twhere
T: Encode,
Ivar::load
instead.Use Ivar::load
instead.
§Safety
The object must have an instance variable with the given name, and it
must be of type T
.
See Ivar::load_ptr
for details surrounding this.
Sourcepub fn downcast_ref<T>(&self) -> Option<&T>where
T: DowncastTarget,
pub fn downcast_ref<T>(&self) -> Option<&T>where
T: DowncastTarget,
Attempt to downcast the object to a class of type T
.
This is the reference-variant. Use Retained::downcast
if you want
to convert a retained object to another type.
§Mutable classes
Some classes have immutable and mutable variants, such as NSString
and NSMutableString
.
When some Objective-C API signature says it gives you an immutable class, it generally expects you to not mutate that, even though it may technically be mutable “under the hood”.
So using this method to convert a NSString
to a NSMutableString
,
while not unsound, is generally frowned upon unless you created the
string yourself, or the API explicitly documents the string to be
mutable.
See Apple’s documentation on mutability and on
isKindOfClass:
for more details.
§Generic classes
Objective-C generics are called “lightweight generics”, and that’s because they aren’t exposed in the runtime. This makes it impossible to safely downcast to generic collections, so this is disallowed by this method.
You can, however, safely downcast to generic collections where all the
type-parameters are AnyObject
.
§Panics
This works internally by calling isKindOfClass:
. That means that the
object must have the instance method of that name, and an exception
will be thrown (if CoreFoundation is linked) or the process will abort
if that is not the case. In the vast majority of cases, you don’t need
to worry about this, since both root objects NSObject
and
NSProxy
implement this method.
§Examples
Cast an NSString
back and forth from NSObject
.
use objc2::rc::Retained;
use objc2_foundation::{NSObject, NSString};
let obj: Retained<NSObject> = NSString::new().into_super();
let string = obj.downcast_ref::<NSString>().unwrap();
// Or with `downcast`, if we do not need the object afterwards
let string = obj.downcast::<NSString>().unwrap();
Try (and fail) to cast an NSObject
to an NSString
.
use objc2_foundation::{NSObject, NSString};
let obj = NSObject::new();
assert!(obj.downcast_ref::<NSString>().is_none());
Try to cast to an array of strings.
use objc2_foundation::{NSArray, NSObject, NSString};
let arr = NSArray::from_retained_slice(&[NSObject::new()]);
// This is invalid and doesn't type check.
let arr = arr.downcast_ref::<NSArray<NSString>>();
This fails to compile, since it would require enumerating over the array to ensure that each element is of the desired type, which is a performance pitfall.
Downcast when processing each element instead.
use objc2_foundation::{NSArray, NSObject, NSString};
let arr = NSArray::from_retained_slice(&[NSObject::new()]);
for elem in arr {
if let Some(data) = elem.downcast_ref::<NSString>() {
// handle `data`
}
}
Trait Implementations§
Source§impl<ObjectType: ?Sized + Message> AsRef<CFArray<ObjectType>> for NSArray<ObjectType>
Available on crate feature objc2-core-foundation
only.
impl<ObjectType: ?Sized + Message> AsRef<CFArray<ObjectType>> for NSArray<ObjectType>
objc2-core-foundation
only.Source§impl<ObjectType: ?Sized + Message> AsRef<NSArray<ObjectType>> for CFArray<ObjectType>
Available on crate feature objc2-core-foundation
only.
impl<ObjectType: ?Sized + Message> AsRef<NSArray<ObjectType>> for CFArray<ObjectType>
objc2-core-foundation
only.Source§impl<ObjectType: ?Sized + Message> Borrow<NSArray<ObjectType>> for NSMutableArray<ObjectType>
impl<ObjectType: ?Sized + Message> Borrow<NSArray<ObjectType>> for NSMutableArray<ObjectType>
Source§impl<ObjectType: ?Sized + Message> ClassType for NSArray<ObjectType>
impl<ObjectType: ?Sized + Message> ClassType for NSArray<ObjectType>
Source§const NAME: &'static str = "NSArray"
const NAME: &'static str = "NSArray"
Source§type ThreadKind = <<NSArray<ObjectType> as ClassType>::Super as ClassType>::ThreadKind
type ThreadKind = <<NSArray<ObjectType> as ClassType>::Super as ClassType>::ThreadKind
Source§impl<ObjectType: ?Sized + Message> CopyingHelper for NSArray<ObjectType>
Available on crate feature NSObject
only.
impl<ObjectType: ?Sized + Message> CopyingHelper for NSArray<ObjectType>
NSObject
only.Source§impl<ObjectType: Debug + Message> Debug for NSArray<ObjectType>
Available on crate feature NSEnumerator
only.
impl<ObjectType: Debug + Message> Debug for NSArray<ObjectType>
NSEnumerator
only.Source§impl<ObjectType: Message> DefaultRetained for NSArray<ObjectType>
impl<ObjectType: Message> DefaultRetained for NSArray<ObjectType>
Source§impl<'a, ObjectType: Message> IntoIterator for &'a NSArray<ObjectType>
impl<'a, ObjectType: Message> IntoIterator for &'a NSArray<ObjectType>
Source§impl<ObjectType: ?Sized + Message> MutableCopyingHelper for NSArray<ObjectType>
Available on crate feature NSObject
only.
impl<ObjectType: ?Sized + Message> MutableCopyingHelper for NSArray<ObjectType>
NSObject
only.Source§type Result = NSMutableArray<ObjectType>
type Result = NSMutableArray<ObjectType>
Self
if the type has no
mutable counterpart. Read moreSource§impl<ObjectType: ?Sized + NSCoding> NSCoding for NSArray<ObjectType>
impl<ObjectType: ?Sized + NSCoding> NSCoding for NSArray<ObjectType>
Source§unsafe fn encodeWithCoder(&self, coder: &NSCoder)
unsafe fn encodeWithCoder(&self, coder: &NSCoder)
NSObject
and NSCoder
only.Source§impl<ObjectType: ?Sized> NSCopying for NSArray<ObjectType>
impl<ObjectType: ?Sized> NSCopying for NSArray<ObjectType>
Source§impl<ObjectType: ?Sized> NSFastEnumeration for NSArray<ObjectType>
impl<ObjectType: ?Sized> NSFastEnumeration for NSArray<ObjectType>
Source§unsafe fn countByEnumeratingWithState_objects_count(
&self,
state: NonNull<NSFastEnumerationState>,
buffer: NonNull<*mut AnyObject>,
len: NSUInteger,
) -> NSUInteger
unsafe fn countByEnumeratingWithState_objects_count( &self, state: NonNull<NSFastEnumerationState>, buffer: NonNull<*mut AnyObject>, len: NSUInteger, ) -> NSUInteger
NSEnumerator
only.Source§impl<ObjectType: ?Sized> NSMutableCopying for NSArray<ObjectType>
impl<ObjectType: ?Sized> NSMutableCopying for NSArray<ObjectType>
Source§impl<ObjectType: ?Sized> NSObjectProtocol for NSArray<ObjectType>
impl<ObjectType: ?Sized> NSObjectProtocol for NSArray<ObjectType>
Source§fn isEqual(&self, other: Option<&AnyObject>) -> bool
fn isEqual(&self, other: Option<&AnyObject>) -> bool
Source§fn hash(&self) -> usize
fn hash(&self) -> usize
Source§fn isKindOfClass(&self, cls: &AnyClass) -> bool
fn isKindOfClass(&self, cls: &AnyClass) -> bool
Source§fn is_kind_of<T>(&self) -> bool
fn is_kind_of<T>(&self) -> bool
isKindOfClass
directly, or cast your objects with AnyObject::downcast_ref
Source§fn isMemberOfClass(&self, cls: &AnyClass) -> bool
fn isMemberOfClass(&self, cls: &AnyClass) -> bool
Source§fn respondsToSelector(&self, aSelector: Sel) -> bool
fn respondsToSelector(&self, aSelector: Sel) -> bool
Source§fn conformsToProtocol(&self, aProtocol: &AnyProtocol) -> bool
fn conformsToProtocol(&self, aProtocol: &AnyProtocol) -> bool
Source§fn debugDescription(&self) -> Retained<NSObject>
fn debugDescription(&self) -> Retained<NSObject>
Source§impl<ObjectType: ?Sized + NSSecureCoding> NSSecureCoding for NSArray<ObjectType>
impl<ObjectType: ?Sized + NSSecureCoding> NSSecureCoding for NSArray<ObjectType>
Source§impl<ObjectType: ?Sized + Message> RefEncode for NSArray<ObjectType>
impl<ObjectType: ?Sized + Message> RefEncode for NSArray<ObjectType>
Source§const ENCODING_REF: Encoding = <NSObject as ::objc2::RefEncode>::ENCODING_REF
const ENCODING_REF: Encoding = <NSObject as ::objc2::RefEncode>::ENCODING_REF
Source§impl<'a, ObjectType: Message + 'a> RetainedFromIterator<&'a ObjectType> for NSArray<ObjectType>
impl<'a, ObjectType: Message + 'a> RetainedFromIterator<&'a ObjectType> for NSArray<ObjectType>
Source§fn retained_from_iter<I: IntoIterator<Item = &'a ObjectType>>(
iter: I,
) -> Retained<Self>
fn retained_from_iter<I: IntoIterator<Item = &'a ObjectType>>( iter: I, ) -> Retained<Self>
Retained
from an iterator.Source§impl<ObjectType: Message> RetainedFromIterator<Retained<ObjectType>> for NSArray<ObjectType>
impl<ObjectType: Message> RetainedFromIterator<Retained<ObjectType>> for NSArray<ObjectType>
Source§fn retained_from_iter<I: IntoIterator<Item = Retained<ObjectType>>>(
iter: I,
) -> Retained<Self>
fn retained_from_iter<I: IntoIterator<Item = Retained<ObjectType>>>( iter: I, ) -> Retained<Self>
Retained
from an iterator.Source§impl<ObjectType: Message> RetainedIntoIterator for NSArray<ObjectType>
impl<ObjectType: Message> RetainedIntoIterator for NSArray<ObjectType>
Source§impl<ObjectType: Message> ToOwned for NSArray<ObjectType>
Available on crate feature NSObject
only.
impl<ObjectType: Message> ToOwned for NSArray<ObjectType>
NSObject
only.