Struct NSAlert

Source
#[repr(C)]
pub struct NSAlert { /* private fields */ }
Available on crate feature NSAlert only.
Expand description

A modal dialog or sheet attached to a document window. The NSAlert class is not designed for subclassing.

See also Apple’s documentation

Implementations§

Source§

impl NSAlert

Source

pub unsafe fn alertWithError( error: &NSError, mtm: MainThreadMarker, ) -> Retained<NSAlert>

Returns an alert initialized from information in an error object.

  • Parameter error: Error information to display.
  • Returns: An initialized alert.
  • Note: The NSAlert class extracts the localized error description, recovery suggestion, and recovery options from the error parameter and uses them as the alert’s message text, informative text, and button titles, respectively.
Source

pub unsafe fn messageText(&self) -> Retained<NSString>

The text that is displayed prominently in the alert.

  • Note: Use this string to get the user’s attention and communicate the reason for displaying the alert.
Source

pub unsafe fn setMessageText(&self, message_text: &NSString)

Setter for messageText.

Source

pub unsafe fn informativeText(&self) -> Retained<NSString>

The descriptive text that provides more details about the reason for the alert.

  • Note: The informative text string is displayed below the message text and is less prominent. Use this string to provide additional context about the reason for the alert or about the actions that the user might take.
Source

pub unsafe fn setInformativeText(&self, informative_text: &NSString)

Setter for informativeText.

Source

pub unsafe fn icon(&self) -> Option<Retained<NSImage>>

Available on crate feature NSImage only.

The custom icon displayed in the alert. By default, the image used in an alert is the app icon (NSApplicationIcon). If this property’s value is set, the specified custom image is used in place of the app icon. If a custom alert icon had been set, it can be cleared by setting this property’s value to nil, which restores use of the app icon for the alert.

Source

pub unsafe fn setIcon(&self, icon: Option<&NSImage>)

Available on crate feature NSImage only.

Setter for icon.

Source

pub unsafe fn addButtonWithTitle(&self, title: &NSString) -> Retained<NSButton>

Available on crate features NSButton and NSControl and NSResponder and NSView only.

Adds a button with a given title to the alert.

Buttons should be added from most-to-least prominent. The exact visual arrangement of the buttons is determined by NSAlert internally. In general, they are arranged from trailing-to-leading edge when laid out horizontally, and top-to-bottom when laid out vertically, with some exceptions for buttons like “Cancel”.

The first three buttons are identified by the order in which they are added (not the order in which they may appear visually) as NSAlertFirstButtonReturn, NSAlertSecondButtonReturn, NSAlertThirdButtonReturn in the return-code parameter. Subsequent buttons are identified as NSAlertThirdButtonReturn + n, where n is an integer.

By default, the first button has a key equivalent of Return, any button with a title of “Cancel” has a key equivalent of Escape, and any button with the title “Don’t Save” has a key equivalent of Command-D (but only if it’s not the first button). You can also assign different key equivalents for the buttons using the keyEquivalent method of the NSButton class. In addition, you can use the tag property of the NSButton class to set the alert presentation’s return-code. The framework reserves the use of the button’s target and action.

  • Parameter title: Title of the button to add to the alert.
  • Returns: The button that was added to the alert.
Source

pub unsafe fn buttons(&self) -> Retained<NSArray<NSButton>>

Available on crate features NSButton and NSControl and NSResponder and NSView only.

The array of response buttons for the alert. The buttons are in the order in which they were added, and do not necessarily reflect the order they are arranged visually. The array does not include the default “OK” button that is shown in an alert presented without any buttons added with -addButtonWithTitle:.

Source

pub unsafe fn alertStyle(&self) -> NSAlertStyle

Indicates the alert’s severity level. See the NSAlertStyle enumeration for the list of alert style constants.

Source

pub unsafe fn setAlertStyle(&self, alert_style: NSAlertStyle)

Setter for alertStyle.

Source

pub unsafe fn showsHelp(&self) -> bool

Specifies whether the alert has a help button.

Set this property’s value to YES to specify that the alert has a help button, or NO to specify it does not.

When a user clicks an alert’s help button, the alert delegate (delegate) receives an alertShowHelp: message. The delegate is responsible for displaying the help information related to this particular alert.

Clicking an alert’s help button can alternately cause the -openHelpAnchor:inBook: message to be sent to the app’s help manager with a nil book and the anchor specified by the helpAnchor property, if any of the following conditions are true:

  • There is no alert delegate.
  • The alert delegate does not implement -alertShowHelp:.
  • The alert delegate implements -alertShowHelp: but returns NO. When this is the case, an exception is raised if no help anchor is set.
Source

pub unsafe fn setShowsHelp(&self, shows_help: bool)

Setter for showsHelp.

Source

pub unsafe fn helpAnchor(&self) -> Option<Retained<NSHelpAnchorName>>

Available on crate feature NSHelpManager only.

The alert’s HTML help anchor used when the user clicks the alert’s help button

Source

pub unsafe fn setHelpAnchor(&self, help_anchor: Option<&NSHelpAnchorName>)

Available on crate feature NSHelpManager only.

Setter for helpAnchor.

Source

pub unsafe fn delegate( &self, ) -> Option<Retained<ProtocolObject<dyn NSAlertDelegate>>>

The delegate of the receiver, currently only allows for custom help behavior of the alert. For apps linked against 10.12, this property has zeroing weak memory semantics. When linked against an older SDK this back to having retain semantics, matching legacy behavior.

Source

pub unsafe fn setDelegate( &self, delegate: Option<&ProtocolObject<dyn NSAlertDelegate>>, )

This is a weak property. Setter for delegate.

Source

pub unsafe fn accessoryView(&self) -> Option<Retained<NSView>>

Available on crate features NSResponder and NSView only.

The accessory view displayed in the alert, placed between the informative text or suppression checkbox (if present) and the response buttons. Before changing the location of the accessory view, first call the -layout method.

Source

pub unsafe fn setAccessoryView(&self, accessory_view: Option<&NSView>)

Available on crate features NSResponder and NSView only.

Setter for accessoryView.

Source

pub unsafe fn layout(&self)

Specifies that the alert must do immediate layout instead of lazily just before display. Used to indicate that the alert panel should do immediate layout, overriding the default behavior of laying out lazily just before showing panel. Only call this method if wanting to do custom layout after it returns. Call this method only after the alert’s other customization, including setting message and informative text, and adding buttons and an accessory view if needed. Layout changes can be made after this method returns, in particular to adjust the frame of an accessory view. Note that the standard layout of the alert may change in the future, so layout customization should be done with caution.

Source

pub unsafe fn runModal(&self) -> NSModalResponse

Available on crate feature NSApplication only.

Runs the alert as an app-modal dialog and returns the constant that identifies the button clicked.

Source

pub unsafe fn showsSuppressionButton(&self) -> bool

Specifies whether the alert includes a suppression checkbox, which can be employed to allow a user to opt out of seeing the alert again. The default value of this property is NO, which specifies the absence of a suppression checkbox in the alert. Set the value to YES to show a suppression checkbox in the alert. By default, a suppression checkbox has the title, “Do not show this message again.” In macOS 11.0 and later, if the alert displays multiple buttons that prompt the user to make a choice, the title is “Do not ask again.” To customize it, use the checkbox’s title property, as follows:

myAlert.suppressionButton.title = “ Do not show this warning again“;

To create an alert that responds to the selection state of the suppression checkbox, check myAlert.suppressionButton.state.

Source

pub unsafe fn setShowsSuppressionButton(&self, shows_suppression_button: bool)

Source

pub unsafe fn suppressionButton(&self) -> Option<Retained<NSButton>>

Available on crate features NSButton and NSControl and NSResponder and NSView only.

The alert’s suppression checkbox. The checkbox may be customized, including the title and the initial state. Additionally, use this method to get the state of the button after the alert is dismissed, which may be stored in user defaults and checked before showing the alert again. In order to show the suppression button in the alert panel, you must set showsSuppressionButton to YES.

Source

pub unsafe fn beginSheetModalForWindow_completionHandler( &self, sheet_window: &NSWindow, handler: Option<&DynBlock<dyn Fn(NSModalResponse)>>, )

Available on crate features NSApplication and NSResponder and NSWindow and block2 only.

Runs the alert modally as a sheet attached to the specified window.

  • Parameters:
  • sheetWindow: The window on which to display the sheet.
  • handler: The completion handler that gets called when the sheet’s modal session ends.

This method uses the NSWindow sheet methods to display the alert. If the alert has an alert style of NSCriticalAlertStyle, it is presented as a critical sheet, which means that it can display on top of other sheets that might already be attached to the window. Otherwise, it is presented–or queued for presentation–as a standard sheet. Note that -orderOut: no longer needs to be called in the completion handler. If the alert isn’t don’t dismiss the alert, it will be done for you after the completion handler finishes.

Source

pub unsafe fn window(&self) -> Retained<NSWindow>

Available on crate features NSResponder and NSWindow only.

The app-modal panel or document-modal sheet that corresponds to the alert

Source§

impl NSAlert

Methods declared on superclass NSObject.

Source

pub unsafe fn init(this: Allocated<Self>) -> Retained<Self>

Source

pub unsafe fn new(mtm: MainThreadMarker) -> Retained<Self>

Source§

impl NSAlert

NSAlertDeprecated.

Source

pub unsafe fn beginSheetModalForWindow_modalDelegate_didEndSelector_contextInfo( &self, window: &NSWindow, delegate: Option<&AnyObject>, did_end_selector: Option<Sel>, context_info: *mut c_void, )

👎Deprecated: Use -beginSheetModalForWindow:completionHandler: instead
Available on crate features NSResponder and NSWindow only.

Methods from Deref<Target = NSObject>§

Source

pub fn doesNotRecognizeSelector(&self, sel: Sel) -> !

Handle messages the object doesn’t recognize.

See Apple’s documentation for details.

Methods from Deref<Target = AnyObject>§

Source

pub fn class(&self) -> &'static AnyClass

Available on crate feature NSAccessibilityConstants 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());
Source

pub unsafe fn get_ivar<T>(&self, name: &str) -> &T
where T: Encode,

👎Deprecated: this is difficult to use correctly, use Ivar::load instead.
Available on crate feature NSAccessibilityConstants 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.

Source

pub fn downcast_ref<T>(&self) -> Option<&T>
where T: DowncastTarget,

Available on crate feature NSAccessibilityConstants 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 NSAlert

Source§

fn as_ref(&self) -> &AnyObject

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl AsRef<NSAlert> for NSAlert

Source§

fn as_ref(&self) -> &Self

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl AsRef<NSObject> for NSAlert

Source§

fn as_ref(&self) -> &NSObject

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl Borrow<AnyObject> for NSAlert

Source§

fn borrow(&self) -> &AnyObject

Immutably borrows from an owned value. Read more
Source§

impl Borrow<NSObject> for NSAlert

Source§

fn borrow(&self) -> &NSObject

Immutably borrows from an owned value. Read more
Source§

impl ClassType for NSAlert

Source§

const NAME: &'static str = "NSAlert"

The name of the Objective-C class that this type represents. Read more
Source§

type Super = NSObject

The superclass of this class. Read more
Source§

type ThreadKind = dyn MainThreadOnly

Whether the type can be used from any thread, or from only the main thread. Read more
Source§

fn class() -> &'static AnyClass

Get a reference to the Objective-C class that this type represents. Read more
Source§

fn as_super(&self) -> &Self::Super

Get an immutable reference to the superclass.
Source§

impl Debug for NSAlert

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Deref for NSAlert

Source§

type Target = NSObject

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Self::Target

Dereferences the value.
Source§

impl Hash for NSAlert

Source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Message for NSAlert

Source§

fn retain(&self) -> Retained<Self>
where Self: Sized,

Increment the reference count of the receiver. Read more
Source§

impl NSObjectProtocol for NSAlert

Source§

fn isEqual(&self, other: Option<&AnyObject>) -> bool
where Self: Sized + Message,

Check whether the object is equal to an arbitrary other object. Read more
Source§

fn hash(&self) -> usize
where Self: Sized + Message,

An integer that can be used as a table address in a hash table structure. Read more
Source§

fn isKindOfClass(&self, cls: &AnyClass) -> bool
where Self: Sized + Message,

Check if the object is an instance of the class, or one of its subclasses. Read more
Source§

fn is_kind_of<T>(&self) -> bool
where T: ClassType, Self: Sized + Message,

👎Deprecated: use isKindOfClass directly, or cast your objects with AnyObject::downcast_ref
Check if the object is an instance of the class type, or one of its subclasses. Read more
Source§

fn isMemberOfClass(&self, cls: &AnyClass) -> bool
where Self: Sized + Message,

Check if the object is an instance of a specific class, without checking subclasses. Read more
Source§

fn respondsToSelector(&self, aSelector: Sel) -> bool
where Self: Sized + Message,

Check whether the object implements or inherits a method with the given selector. Read more
Source§

fn conformsToProtocol(&self, aProtocol: &AnyProtocol) -> bool
where Self: Sized + Message,

Check whether the object conforms to a given protocol. Read more
Source§

fn description(&self) -> Retained<NSObject>
where Self: Sized + Message,

A textual representation of the object. Read more
Source§

fn debugDescription(&self) -> Retained<NSObject>
where Self: Sized + Message,

A textual representation of the object to use when debugging. Read more
Source§

fn isProxy(&self) -> bool
where Self: Sized + Message,

Check whether the receiver is a subclass of the NSProxy root class instead of the usual NSObject. Read more
Source§

fn retainCount(&self) -> usize
where Self: Sized + Message,

The reference count of the object. Read more
Source§

impl PartialEq for NSAlert

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl RefEncode for NSAlert

Source§

const ENCODING_REF: Encoding = <NSObject as ::objc2::RefEncode>::ENCODING_REF

The Objective-C type-encoding for a reference of this type. Read more
Source§

impl DowncastTarget for NSAlert

Source§

impl Eq for NSAlert

Auto Trait Implementations§

§

impl !Freeze for NSAlert

§

impl !RefUnwindSafe for NSAlert

§

impl !Send for NSAlert

§

impl !Sync for NSAlert

§

impl !Unpin for NSAlert

§

impl !UnwindSafe for NSAlert

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<'a, T> MainThreadOnly for T
where T: ClassType<ThreadKind = dyn MainThreadOnly + 'a> + ?Sized,

Source§

fn mtm(&self) -> MainThreadMarker

Get a MainThreadMarker from the main-thread-only object. Read more
Source§

fn alloc(mtm: MainThreadMarker) -> Allocated<Self>
where Self: Sized + ClassType,

Allocate a new instance of the class on the main thread. Read more
Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> AutoreleaseSafe for T
where T: ?Sized,