pub struct UIApplication { /* private fields */ }UIApplication and UIResponder only.Expand description
Implementations§
Source§impl UIApplication
impl UIApplication
Sourcepub fn main(
principal_class_name: Option<&NSString>,
delegate_class_name: Option<&NSString>,
mtm: MainThreadMarker,
) -> !
pub fn main( principal_class_name: Option<&NSString>, delegate_class_name: Option<&NSString>, mtm: MainThreadMarker, ) -> !
The entry point to UIKit applications.
Creates the application object and the application delegate and sets up the event cycle.
See Apple’s documentation for more details.
§Example
Create an application delegate and launch the application.
use objc2::MainThreadMarker;
use objc2::rc::{Allocated, Retained};
use objc2::{define_class, msg_send, ClassType, DefinedClass, MainThreadOnly};
use objc2_foundation::{NSNotification, NSObject, NSObjectProtocol, NSString};
use objc2_ui_kit::{UIApplication, UIApplicationDelegate};
#[derive(Default)]
struct AppState {
// Whatever state you want to store in your delegate.
}
define_class!(
// SAFETY:
// - `NSObject` does not have any subclassing requirements.
// - `AppDelegate` does not implement `Drop`.
#[unsafe(super(NSObject))]
#[thread_kind = MainThreadOnly]
#[ivars = AppState]
struct AppDelegate;
impl AppDelegate {
// Called by `UIApplication::main`.
#[unsafe(method_id(init))]
fn init(this: Allocated<Self>) -> Retained<Self> {
let this = this.set_ivars(AppState::default());
unsafe { msg_send![super(this), init] }
}
}
unsafe impl NSObjectProtocol for AppDelegate {}
unsafe impl UIApplicationDelegate for AppDelegate {
#[unsafe(method(applicationDidFinishLaunching:))]
fn did_finish_launching(&self, _notification: &NSNotification) {
println!("did finish launching!");
// Do UI initialization in here, such as creating windows, views, etc.
}
#[unsafe(method(applicationWillTerminate:))]
fn will_terminate(&self, _notification: &NSNotification) {
println!("will terminate!");
// Tear down your application state here.
}
}
);
fn main() {
let mtm = MainThreadMarker::new().unwrap();
let delegate_class = NSString::from_class(AppDelegate::class());
UIApplication::main(None, Some(&delegate_class), mtm);
}Source§impl UIApplication
impl UIApplication
Sourcepub unsafe fn delegate(
&self,
) -> Option<Retained<ProtocolObject<dyn UIApplicationDelegate>>>
pub unsafe fn delegate( &self, ) -> Option<Retained<ProtocolObject<dyn UIApplicationDelegate>>>
§Safety
This is not retained internally, you must ensure the object is still alive.
Sourcepub unsafe fn setDelegate(
&self,
delegate: Option<&ProtocolObject<dyn UIApplicationDelegate>>,
)
pub unsafe fn setDelegate( &self, delegate: Option<&ProtocolObject<dyn UIApplicationDelegate>>, )
pub fn beginIgnoringInteractionEvents(&self)
pub fn endIgnoringInteractionEvents(&self)
pub fn isIgnoringInteractionEvents(&self) -> bool
pub fn isIdleTimerDisabled(&self) -> bool
Sourcepub fn setIdleTimerDisabled(&self, idle_timer_disabled: bool)
pub fn setIdleTimerDisabled(&self, idle_timer_disabled: bool)
Setter for isIdleTimerDisabled.
pub fn openURL(&self, url: &NSURL) -> bool
pub fn canOpenURL(&self, url: &NSURL) -> bool
Sourcepub unsafe fn openURL_options_completionHandler(
&self,
url: &NSURL,
options: &NSDictionary<UIApplicationOpenExternalURLOptionsKey, AnyObject>,
completion: Option<&DynBlock<dyn Fn(Bool)>>,
)
Available on crate feature block2 only.
pub unsafe fn openURL_options_completionHandler( &self, url: &NSURL, options: &NSDictionary<UIApplicationOpenExternalURLOptionsKey, AnyObject>, completion: Option<&DynBlock<dyn Fn(Bool)>>, )
block2 only.§Safety
options generic should be of the correct type.
pub fn sendEvent(&self, event: &UIEvent)
UIEvent only.pub fn keyWindow(&self) -> Option<Retained<UIWindow>>
UIView and UIWindow only.pub fn windows(&self) -> Retained<NSArray<UIWindow>>
UIView and UIWindow only.Sourcepub unsafe fn sendAction_to_from_forEvent(
&self,
action: Sel,
target: Option<&AnyObject>,
sender: Option<&AnyObject>,
event: Option<&UIEvent>,
) -> bool
Available on crate feature UIEvent only.
pub unsafe fn sendAction_to_from_forEvent( &self, action: Sel, target: Option<&AnyObject>, sender: Option<&AnyObject>, event: Option<&UIEvent>, ) -> bool
UIEvent only.§Safety
actionmust be a valid selector.targetshould be of the correct type.sendershould be of the correct type.
pub fn isNetworkActivityIndicatorVisible(&self) -> bool
Sourcepub fn setNetworkActivityIndicatorVisible(
&self,
network_activity_indicator_visible: bool,
)
👎Deprecated: Provide a custom network activity UI in your app if desired.
pub fn setNetworkActivityIndicatorVisible( &self, network_activity_indicator_visible: bool, )
Setter for isNetworkActivityIndicatorVisible.
pub fn supportedInterfaceOrientationsForWindow( &self, window: Option<&UIWindow>, ) -> UIInterfaceOrientationMask
UIOrientation and UIView and UIWindow only.pub fn statusBarOrientationAnimationDuration(&self) -> NSTimeInterval
pub fn statusBarFrame(&self) -> CGRect
objc2-core-foundation only.pub fn applicationIconBadgeNumber(&self) -> NSInteger
Sourcepub fn setApplicationIconBadgeNumber(
&self,
application_icon_badge_number: NSInteger,
)
👎Deprecated: Use -[UNUserNotificationCenter setBadgeCount:withCompletionHandler:] instead.
pub fn setApplicationIconBadgeNumber( &self, application_icon_badge_number: NSInteger, )
Setter for applicationIconBadgeNumber.
pub fn applicationSupportsShakeToEdit(&self) -> bool
Sourcepub fn setApplicationSupportsShakeToEdit(
&self,
application_supports_shake_to_edit: bool,
)
pub fn setApplicationSupportsShakeToEdit( &self, application_supports_shake_to_edit: bool, )
Setter for applicationSupportsShakeToEdit.
pub fn applicationState(&self) -> UIApplicationState
pub fn backgroundTimeRemaining(&self) -> NSTimeInterval
pub fn beginBackgroundTaskWithExpirationHandler( &self, handler: Option<&DynBlock<dyn Fn()>>, ) -> UIBackgroundTaskIdentifier
block2 only.pub fn beginBackgroundTaskWithName_expirationHandler( &self, task_name: Option<&NSString>, handler: Option<&DynBlock<dyn Fn()>>, ) -> UIBackgroundTaskIdentifier
block2 only.pub fn endBackgroundTask(&self, identifier: UIBackgroundTaskIdentifier)
Sourcepub fn setMinimumBackgroundFetchInterval(
&self,
minimum_background_fetch_interval: NSTimeInterval,
)
👎Deprecated: Use a BGAppRefreshTask in the BackgroundTasks framework instead
pub fn setMinimumBackgroundFetchInterval( &self, minimum_background_fetch_interval: NSTimeInterval, )
The system guarantees that it will not wake up your application for a background fetch more frequently than the interval provided. Set to UIApplicationBackgroundFetchIntervalMinimum to be woken as frequently as the system desires, or to UIApplicationBackgroundFetchIntervalNever (the default) to never be woken for a background fetch.
This setter will have no effect unless your application has the “fetch”
UIBackgroundMode. See the UIApplicationDelegate method
application:performFetchWithCompletionHandler: for more.
Sourcepub fn backgroundRefreshStatus(&self) -> UIBackgroundRefreshStatus
pub fn backgroundRefreshStatus(&self) -> UIBackgroundRefreshStatus
When background refresh is available for an application, it may launched or resumed in the background to handle significant location changes, remote notifications, background fetches, etc. Observe UIApplicationBackgroundRefreshStatusDidChangeNotification to be notified of changes.
pub fn isProtectedDataAvailable(&self) -> bool
pub fn userInterfaceLayoutDirection(&self) -> UIUserInterfaceLayoutDirection
UIInterface only.pub fn preferredContentSizeCategory(&self) -> Retained<UIContentSizeCategory>
UIContentSizeCategory only.pub fn connectedScenes(&self) -> Retained<NSSet<UIScene>>
UIScene only.pub fn openSessions(&self) -> Retained<NSSet<UISceneSession>>
UISceneSession only.pub fn supportsMultipleScenes(&self) -> bool
Sourcepub fn activateSceneSessionForRequest_errorHandler(
&self,
request: &UISceneSessionActivationRequest,
error_handler: Option<&DynBlock<dyn Fn(NonNull<NSError>)>>,
)
Available on crate features UISceneSessionActivationRequest and block2 only.
pub fn activateSceneSessionForRequest_errorHandler( &self, request: &UISceneSessionActivationRequest, error_handler: Option<&DynBlock<dyn Fn(NonNull<NSError>)>>, )
UISceneSessionActivationRequest and block2 only.Asks the system to activate an existing scene, or create a new scene and associate it with your app.
- Parameters:
- request: The activation request.
- errorHandler: A handler to be called if the request fails.
pub fn requestSceneSessionActivation_userActivity_options_errorHandler( &self, scene_session: Option<&UISceneSession>, user_activity: Option<&NSUserActivity>, options: Option<&UISceneActivationRequestOptions>, error_handler: Option<&DynBlock<dyn Fn(NonNull<NSError>)>>, )
UISceneOptions and UISceneSession and block2 only.pub fn requestSceneSessionDestruction_options_errorHandler( &self, scene_session: &UISceneSession, options: Option<&UISceneDestructionRequestOptions>, error_handler: Option<&DynBlock<dyn Fn(NonNull<NSError>)>>, )
UISceneOptions and UISceneSession and block2 only.pub fn requestSceneSessionRefresh(&self, scene_session: &UISceneSession)
UISceneSession only.Source§impl UIApplication
Methods declared on superclass NSObject.
impl UIApplication
Methods declared on superclass NSObject.
Source§impl UIApplication
UIRemoteNotifications.
impl UIApplication
UIRemoteNotifications.
pub fn registerForRemoteNotifications(&self)
pub fn unregisterForRemoteNotifications(&self)
pub fn isRegisteredForRemoteNotifications(&self) -> bool
pub fn registerForRemoteNotificationTypes( &self, types: UIRemoteNotificationType, )
pub fn enabledRemoteNotificationTypes(&self) -> UIRemoteNotificationType
Source§impl UIApplication
UILocalNotifications.
impl UIApplication
UILocalNotifications.
pub fn presentLocalNotificationNow(&self, notification: &UILocalNotification)
UILocalNotification only.pub fn scheduleLocalNotification(&self, notification: &UILocalNotification)
UILocalNotification only.pub fn cancelLocalNotification(&self, notification: &UILocalNotification)
UILocalNotification only.pub fn cancelAllLocalNotifications(&self)
pub fn scheduledLocalNotifications( &self, ) -> Option<Retained<NSArray<UILocalNotification>>>
UILocalNotification only.Sourcepub fn setScheduledLocalNotifications(
&self,
scheduled_local_notifications: Option<&NSArray<UILocalNotification>>,
)
👎Deprecated: Use UserNotifications Framework’s -[UNUserNotificationCenter getPendingNotificationRequestsWithCompletionHandler:]Available on crate feature UILocalNotification only.
pub fn setScheduledLocalNotifications( &self, scheduled_local_notifications: Option<&NSArray<UILocalNotification>>, )
UILocalNotification only.Setter for scheduledLocalNotifications.
This is copied when set.
Source§impl UIApplication
UIUserNotificationSettings.
impl UIApplication
UIUserNotificationSettings.
pub fn registerUserNotificationSettings( &self, notification_settings: &UIUserNotificationSettings, )
UIUserNotificationSettings only.pub fn currentUserNotificationSettings( &self, ) -> Option<Retained<UIUserNotificationSettings>>
UIUserNotificationSettings only.Source§impl UIApplication
UIRemoteControlEvents.
impl UIApplication
UIRemoteControlEvents.
pub fn beginReceivingRemoteControlEvents(&self)
pub fn endReceivingRemoteControlEvents(&self)
Source§impl UIApplication
UINewsstand.
impl UIApplication
UINewsstand.
pub fn setNewsstandIconImage(&self, image: Option<&UIImage>)
UIImage only.Source§impl UIApplication
UIShortcutItems.
impl UIApplication
UIShortcutItems.
pub fn shortcutItems( &self, ) -> Option<Retained<NSArray<UIApplicationShortcutItem>>>
UIApplicationShortcutItem only.Sourcepub fn setShortcutItems(
&self,
shortcut_items: Option<&NSArray<UIApplicationShortcutItem>>,
)
Available on crate feature UIApplicationShortcutItem only.
pub fn setShortcutItems( &self, shortcut_items: Option<&NSArray<UIApplicationShortcutItem>>, )
UIApplicationShortcutItem only.Setter for shortcutItems.
This is copied when set.
Source§impl UIApplication
UIAlternateApplicationIcons.
impl UIApplication
UIAlternateApplicationIcons.
pub fn supportsAlternateIcons(&self) -> bool
pub fn setAlternateIconName_completionHandler( &self, alternate_icon_name: Option<&NSString>, completion_handler: Option<&DynBlock<dyn Fn(*mut NSError)>>, )
block2 only.pub fn alternateIconName(&self) -> Option<Retained<NSString>>
Source§impl UIApplication
UIStateRestoration.
impl UIApplication
UIStateRestoration.
pub unsafe fn extendStateRestoration(&self)
pub unsafe fn completeStateRestoration(&self)
pub fn ignoreSnapshotOnNextApplicationLaunch(&self)
pub fn registerObjectForStateRestoration_restorationIdentifier( object: &ProtocolObject<dyn UIStateRestoring>, restoration_identifier: &NSString, )
UIStateRestoration only.impl UIApplication
DefaultApplication.
Source§impl UIApplication
UIApplicationDeprecated.
impl UIApplication
UIApplicationDeprecated.
pub fn isProximitySensingEnabled(&self) -> bool
Sourcepub fn setProximitySensingEnabled(&self, proximity_sensing_enabled: bool)
👎Deprecated
pub fn setProximitySensingEnabled(&self, proximity_sensing_enabled: bool)
Setter for isProximitySensingEnabled.
pub fn setStatusBarHidden_animated(&self, hidden: bool, animated: bool)
Sourcepub fn setStatusBarOrientation(
&self,
status_bar_orientation: UIInterfaceOrientation,
)
👎Deprecated: Explicit setting of the status bar orientation is more limited in iOS 6.0 and laterAvailable on crate feature UIOrientation only.
pub fn setStatusBarOrientation( &self, status_bar_orientation: UIInterfaceOrientation, )
UIOrientation only.Setter for [statusBarOrientation][Self::statusBarOrientation].
pub fn setStatusBarOrientation_animated( &self, interface_orientation: UIInterfaceOrientation, animated: bool, )
UIOrientation only.Sourcepub fn setStatusBarStyle(&self, status_bar_style: UIStatusBarStyle)
👎Deprecated: Use -[UIViewController preferredStatusBarStyle]
pub fn setStatusBarStyle(&self, status_bar_style: UIStatusBarStyle)
Setter for [statusBarStyle][Self::statusBarStyle].
pub fn setStatusBarStyle_animated( &self, status_bar_style: UIStatusBarStyle, animated: bool, )
Sourcepub fn setStatusBarHidden(&self, status_bar_hidden: bool)
👎Deprecated: Use -[UIViewController prefersStatusBarHidden]
pub fn setStatusBarHidden(&self, status_bar_hidden: bool)
Setter for [isStatusBarHidden][Self::isStatusBarHidden].
pub fn setStatusBarHidden_withAnimation( &self, hidden: bool, animation: UIStatusBarAnimation, )
pub fn setKeepAliveTimeout_handler( &self, timeout: NSTimeInterval, keep_alive_handler: Option<&DynBlock<dyn Fn()>>, ) -> bool
block2 only.pub fn clearKeepAliveTimeout(&self)
Methods from Deref<Target = UIResponder>§
pub fn nextResponder(&self) -> Option<Retained<UIResponder>>
pub fn canBecomeFirstResponder(&self) -> bool
pub fn becomeFirstResponder(&self) -> bool
pub fn canResignFirstResponder(&self) -> bool
pub fn resignFirstResponder(&self) -> bool
pub fn isFirstResponder(&self) -> bool
pub fn touchesBegan_withEvent( &self, touches: &NSSet<UITouch>, event: Option<&UIEvent>, )
UIEvent and UITouch only.pub fn touchesMoved_withEvent( &self, touches: &NSSet<UITouch>, event: Option<&UIEvent>, )
UIEvent and UITouch only.pub fn touchesEnded_withEvent( &self, touches: &NSSet<UITouch>, event: Option<&UIEvent>, )
UIEvent and UITouch only.pub fn touchesCancelled_withEvent( &self, touches: &NSSet<UITouch>, event: Option<&UIEvent>, )
UIEvent and UITouch only.pub fn touchesEstimatedPropertiesUpdated(&self, touches: &NSSet<UITouch>)
UITouch only.pub fn pressesBegan_withEvent( &self, presses: &NSSet<UIPress>, event: Option<&UIPressesEvent>, )
UIEvent and UIPress and UIPressesEvent only.pub fn pressesChanged_withEvent( &self, presses: &NSSet<UIPress>, event: Option<&UIPressesEvent>, )
UIEvent and UIPress and UIPressesEvent only.pub fn pressesEnded_withEvent( &self, presses: &NSSet<UIPress>, event: Option<&UIPressesEvent>, )
UIEvent and UIPress and UIPressesEvent only.pub fn pressesCancelled_withEvent( &self, presses: &NSSet<UIPress>, event: Option<&UIPressesEvent>, )
UIEvent and UIPress and UIPressesEvent only.pub fn motionBegan_withEvent( &self, motion: UIEventSubtype, event: Option<&UIEvent>, )
UIEvent only.pub fn motionEnded_withEvent( &self, motion: UIEventSubtype, event: Option<&UIEvent>, )
UIEvent only.pub fn motionCancelled_withEvent( &self, motion: UIEventSubtype, event: Option<&UIEvent>, )
UIEvent only.pub fn remoteControlReceivedWithEvent(&self, event: Option<&UIEvent>)
UIEvent only.Sourcepub unsafe fn canPerformAction_withSender(
&self,
action: Sel,
sender: Option<&AnyObject>,
) -> bool
pub unsafe fn canPerformAction_withSender( &self, action: Sel, sender: Option<&AnyObject>, ) -> bool
§Safety
actionmust be a valid selector.sendershould be of the correct type.
Sourcepub unsafe fn targetForAction_withSender(
&self,
action: Sel,
sender: Option<&AnyObject>,
) -> Option<Retained<AnyObject>>
pub unsafe fn targetForAction_withSender( &self, action: Sel, sender: Option<&AnyObject>, ) -> Option<Retained<AnyObject>>
§Safety
actionmust be a valid selector.sendershould be of the correct type.
pub fn buildMenuWithBuilder(&self, builder: &ProtocolObject<dyn UIMenuBuilder>)
UIMenuBuilder only.pub fn validateCommand(&self, command: &UICommand)
UICommand and UIMenuElement only.Sourcepub fn providerForDeferredMenuElement(
&self,
deferred_element: &UIDeferredMenuElement,
) -> Option<Retained<UIDeferredMenuElementProvider>>
Available on crate features UIDeferredMenuElement and UIMenuElement only.
pub fn providerForDeferredMenuElement( &self, deferred_element: &UIDeferredMenuElement, ) -> Option<Retained<UIDeferredMenuElementProvider>>
UIDeferredMenuElement and UIMenuElement only.Asks the responder for an element provider to fulfill the given focus-based deferred element.
Check the identifier of the deferred element to identify which deferred element this is.
By default, this returns nil. Return a non-nil provider to make this responder responsible for providing
elements for this fulfillment of the deferred element.
pub fn undoManager(&self) -> Option<Retained<NSUndoManager>>
pub fn editingInteractionConfiguration( &self, ) -> UIEditingInteractionConfiguration
pub fn keyCommands(&self) -> Option<Retained<NSArray<UIKeyCommand>>>
UICommand and UIKeyCommand and UIMenuElement only.pub fn inputView(&self) -> Option<Retained<UIView>>
UIView only.pub fn inputAccessoryView(&self) -> Option<Retained<UIView>>
UIView only.Sourcepub fn inputAssistantItem(&self) -> Retained<UITextInputAssistantItem>
Available on crate feature UITextInput only.
pub fn inputAssistantItem(&self) -> Retained<UITextInputAssistantItem>
UITextInput only.This method is for clients that wish to put buttons on the Shortcuts Bar, shown on top of the keyboard. You may modify the returned inputAssistantItem to add to or replace the existing items on the bar. Modifications made to the returned UITextInputAssistantItem are reflected automatically. This method should not be overridden. Goes up the responder chain.
pub fn inputViewController(&self) -> Option<Retained<UIInputViewController>>
UIInputViewController and UIViewController only.pub fn inputAccessoryViewController( &self, ) -> Option<Retained<UIInputViewController>>
UIInputViewController and UIViewController only.pub fn textInputMode(&self) -> Option<Retained<UITextInputMode>>
UITextInput only.pub fn textInputContextIdentifier(&self) -> Option<Retained<NSString>>
pub fn reloadInputViews(&self)
pub fn userActivity(&self) -> Option<Retained<NSUserActivity>>
Sourcepub fn setUserActivity(&self, user_activity: Option<&NSUserActivity>)
pub fn setUserActivity(&self, user_activity: Option<&NSUserActivity>)
Setter for userActivity.
pub fn updateUserActivityState(&self, activity: &NSUserActivity)
pub fn restoreUserActivityState(&self, activity: &NSUserActivity)
Sourcepub unsafe fn captureTextFromCamera(&self, sender: Option<&AnyObject>)
pub unsafe fn captureTextFromCamera(&self, sender: Option<&AnyObject>)
§Safety
sender should be of the correct type.
pub fn activityItemsConfiguration( &self, ) -> Option<Retained<ProtocolObject<dyn UIActivityItemsConfigurationReading>>>
UIResponder_UIActivityItemsConfiguration and UIActivityItemsConfigurationReading only.Sourcepub fn setActivityItemsConfiguration(
&self,
activity_items_configuration: Option<&ProtocolObject<dyn UIActivityItemsConfigurationReading>>,
)
Available on crate features UIResponder_UIActivityItemsConfiguration and UIActivityItemsConfigurationReading only.
pub fn setActivityItemsConfiguration( &self, activity_items_configuration: Option<&ProtocolObject<dyn UIActivityItemsConfigurationReading>>, )
UIResponder_UIActivityItemsConfiguration and UIActivityItemsConfigurationReading only.Setter for activityItemsConfiguration.
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
Available on crate feature UIIndirectScribbleInteraction only.
pub fn class(&self) -> &'static AnyClass
UIIndirectScribbleInteraction only.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.Available on crate feature UIIndirectScribbleInteraction only.
pub unsafe fn get_ivar<T>(&self, name: &str) -> &Twhere
T: Encode,
Ivar::load instead.UIIndirectScribbleInteraction only.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,
Available on crate feature UIIndirectScribbleInteraction only.
pub fn downcast_ref<T>(&self) -> Option<&T>where
T: DowncastTarget,
UIIndirectScribbleInteraction only.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 AsRef<AnyObject> for UIApplication
impl AsRef<AnyObject> for UIApplication
Source§impl AsRef<NSObject> for UIApplication
impl AsRef<NSObject> for UIApplication
Source§impl AsRef<UIApplication> for UIApplication
impl AsRef<UIApplication> for UIApplication
Source§impl AsRef<UIResponder> for UIApplication
impl AsRef<UIResponder> for UIApplication
Source§fn as_ref(&self) -> &UIResponder
fn as_ref(&self) -> &UIResponder
Source§impl Borrow<AnyObject> for UIApplication
impl Borrow<AnyObject> for UIApplication
Source§impl Borrow<NSObject> for UIApplication
impl Borrow<NSObject> for UIApplication
Source§impl Borrow<UIResponder> for UIApplication
impl Borrow<UIResponder> for UIApplication
Source§fn borrow(&self) -> &UIResponder
fn borrow(&self) -> &UIResponder
Source§impl ClassType for UIApplication
impl ClassType for UIApplication
Source§const NAME: &'static str = "UIApplication"
const NAME: &'static str = "UIApplication"
Source§type Super = UIResponder
type Super = UIResponder
Source§type ThreadKind = dyn MainThreadOnly
type ThreadKind = dyn MainThreadOnly
Source§impl Debug for UIApplication
impl Debug for UIApplication
Source§impl Deref for UIApplication
impl Deref for UIApplication
Source§impl Hash for UIApplication
impl Hash for UIApplication
Source§impl Message for UIApplication
impl Message for UIApplication
Source§impl NSObjectProtocol for UIApplication
impl NSObjectProtocol for UIApplication
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_refSource§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 PartialEq for UIApplication
impl PartialEq for UIApplication
Source§impl RefEncode for UIApplication
impl RefEncode for UIApplication
Source§const ENCODING_REF: Encoding = <UIResponder as ::objc2::RefEncode>::ENCODING_REF
const ENCODING_REF: Encoding = <UIResponder as ::objc2::RefEncode>::ENCODING_REF
Source§impl UIResponderStandardEditActions for UIApplication
impl UIResponderStandardEditActions for UIApplication
Source§unsafe fn cut(&self, sender: Option<&AnyObject>)
unsafe fn cut(&self, sender: Option<&AnyObject>)
UIResponder only.Source§unsafe fn copy(&self, sender: Option<&AnyObject>)
unsafe fn copy(&self, sender: Option<&AnyObject>)
UIResponder only.Source§unsafe fn paste(&self, sender: Option<&AnyObject>)
unsafe fn paste(&self, sender: Option<&AnyObject>)
UIResponder only.Source§unsafe fn pasteAndMatchStyle(&self, sender: Option<&AnyObject>)
unsafe fn pasteAndMatchStyle(&self, sender: Option<&AnyObject>)
UIResponder only.Source§unsafe fn pasteAndGo(&self, sender: Option<&AnyObject>)
unsafe fn pasteAndGo(&self, sender: Option<&AnyObject>)
UIResponder only.Source§unsafe fn pasteAndSearch(&self, sender: Option<&AnyObject>)
unsafe fn pasteAndSearch(&self, sender: Option<&AnyObject>)
UIResponder only.Source§unsafe fn newFromPasteboard(&self, sender: Option<&AnyObject>)
unsafe fn newFromPasteboard(&self, sender: Option<&AnyObject>)
UIResponder only.Source§unsafe fn select(&self, sender: Option<&AnyObject>)
unsafe fn select(&self, sender: Option<&AnyObject>)
UIResponder only.Source§unsafe fn selectAll(&self, sender: Option<&AnyObject>)
unsafe fn selectAll(&self, sender: Option<&AnyObject>)
UIResponder only.Source§unsafe fn delete(&self, sender: Option<&AnyObject>)
unsafe fn delete(&self, sender: Option<&AnyObject>)
UIResponder only.Source§unsafe fn makeTextWritingDirectionLeftToRight(&self, sender: Option<&AnyObject>)
unsafe fn makeTextWritingDirectionLeftToRight(&self, sender: Option<&AnyObject>)
UIResponder only.Source§unsafe fn makeTextWritingDirectionRightToLeft(&self, sender: Option<&AnyObject>)
unsafe fn makeTextWritingDirectionRightToLeft(&self, sender: Option<&AnyObject>)
UIResponder only.Source§unsafe fn toggleBoldface(&self, sender: Option<&AnyObject>)
unsafe fn toggleBoldface(&self, sender: Option<&AnyObject>)
UIResponder only.Source§unsafe fn toggleItalics(&self, sender: Option<&AnyObject>)
unsafe fn toggleItalics(&self, sender: Option<&AnyObject>)
UIResponder only.Source§unsafe fn toggleUnderline(&self, sender: Option<&AnyObject>)
unsafe fn toggleUnderline(&self, sender: Option<&AnyObject>)
UIResponder only.Source§unsafe fn increaseSize(&self, sender: Option<&AnyObject>)
unsafe fn increaseSize(&self, sender: Option<&AnyObject>)
UIResponder only.Source§unsafe fn decreaseSize(&self, sender: Option<&AnyObject>)
unsafe fn decreaseSize(&self, sender: Option<&AnyObject>)
UIResponder only.Source§unsafe fn alignLeft(&self, sender: Option<&AnyObject>)
unsafe fn alignLeft(&self, sender: Option<&AnyObject>)
UIResponder only.Source§unsafe fn alignCenter(&self, sender: Option<&AnyObject>)
unsafe fn alignCenter(&self, sender: Option<&AnyObject>)
UIResponder only.Source§unsafe fn alignJustified(&self, sender: Option<&AnyObject>)
unsafe fn alignJustified(&self, sender: Option<&AnyObject>)
UIResponder only.Source§unsafe fn alignRight(&self, sender: Option<&AnyObject>)
unsafe fn alignRight(&self, sender: Option<&AnyObject>)
UIResponder only.Source§unsafe fn find(&self, sender: Option<&AnyObject>)
unsafe fn find(&self, sender: Option<&AnyObject>)
UIResponder only.Source§unsafe fn findAndReplace(&self, sender: Option<&AnyObject>)
unsafe fn findAndReplace(&self, sender: Option<&AnyObject>)
UIResponder only.Source§unsafe fn findNext(&self, sender: Option<&AnyObject>)
unsafe fn findNext(&self, sender: Option<&AnyObject>)
UIResponder only.Source§unsafe fn findPrevious(&self, sender: Option<&AnyObject>)
unsafe fn findPrevious(&self, sender: Option<&AnyObject>)
UIResponder only.Source§unsafe fn useSelectionForFind(&self, sender: Option<&AnyObject>)
unsafe fn useSelectionForFind(&self, sender: Option<&AnyObject>)
UIResponder only.Source§unsafe fn updateTextAttributesWithConversionHandler(
&self,
conversion_handler: UITextAttributesConversionHandler,
)
unsafe fn updateTextAttributesWithConversionHandler( &self, conversion_handler: UITextAttributesConversionHandler, )
UIResponder and block2 only.Source§unsafe fn print(&self, sender: Option<&AnyObject>)
unsafe fn print(&self, sender: Option<&AnyObject>)
UIResponder only.Source§unsafe fn rename(&self, sender: Option<&AnyObject>)
unsafe fn rename(&self, sender: Option<&AnyObject>)
UIResponder only.Source§unsafe fn duplicate(&self, sender: Option<&AnyObject>)
unsafe fn duplicate(&self, sender: Option<&AnyObject>)
UIResponder only.Source§unsafe fn move(&self, sender: Option<&AnyObject>)
unsafe fn move(&self, sender: Option<&AnyObject>)
UIResponder only.Source§unsafe fn export(&self, sender: Option<&AnyObject>)
unsafe fn export(&self, sender: Option<&AnyObject>)
UIResponder only.Source§unsafe fn toggleSidebar(&self, sender: Option<&AnyObject>)
unsafe fn toggleSidebar(&self, sender: Option<&AnyObject>)
UIResponder only.Source§unsafe fn toggleInspector(&self, sender: Option<&AnyObject>)
unsafe fn toggleInspector(&self, sender: Option<&AnyObject>)
UIResponder only.impl DowncastTarget for UIApplication
impl Eq for UIApplication
Auto Trait Implementations§
impl !Freeze for UIApplication
impl !RefUnwindSafe for UIApplication
impl !Send for UIApplication
impl !Sync for UIApplication
impl !Unpin for UIApplication
impl !UnwindSafe for UIApplication
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<'a, T> MainThreadOnly for T
impl<'a, T> MainThreadOnly for T
Source§fn mtm(&self) -> MainThreadMarker
fn mtm(&self) -> MainThreadMarker
MainThreadMarker from the main-thread-only object. Read more