Struct NSUserDefaults

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

NSUserDefaults is a hierarchical persistent interprocess (optionally distributed) key-value store, optimized for storing user settings.

Hierarchical: NSUserDefaults has a list of places to look for data called the “search list”. A search list is referred to by an arbitrary string called the “suite identifier” or “domain identifier”. When queried, NSUserDefaults checks each entry of its search list until it finds one that contains the key in question, or has searched the whole list. The list is (note: “current host + current user” preferences are unimplemented on iOS, watchOS, and tvOS, and “any user” preferences are not generally useful for applications on those operating systems):

  • Managed (“forced”) preferences, set by a configuration profile or via mcx from a network administrator
  • Commandline arguments
  • Preferences for the current domain, in the cloud
  • Preferences for the current domain, the current user, in the current host
  • Preferences for the current domain, the current user, in any host
  • Preferences added via -addSuiteNamed:
  • Preferences global to all apps for the current user, in the current host
  • Preferences global to all apps for the current user, in any host
  • Preferences for the current domain, for all users, in the current host
  • Preferences global to all apps for all users, in the current host
  • Preferences registered with -registerDefaults:

Persistent: Preferences stored in NSUserDefaults persist across reboots and relaunches of apps unless otherwise specified.

Interprocess: Preferences may be accessible to and modified from multiple processes simultaneously (for example between an application and an extension).

Optionally distributed (Currently only supported in Shared iPad for Students mode): Data stored in user defaults can be made “ubiqitous”, i.e. synchronized between devices via the cloud. Ubiquitous user defaults are automatically propagated to all devices logged into the same iCloud account. When reading defaults (via -*ForKey: methods on NSUserDefaults), ubiquitous defaults are searched before local defaults. All operations on ubiquitous defaults are asynchronous, so registered defaults may be returned in place of ubiquitous defaults if downloading from iCloud hasn’t finished. Ubiquitous defaults are specified in the Defaults Configuration File for an application.

Key-Value Store: NSUserDefaults stores Property List objects (NSString, NSData, NSNumber, NSDate, NSArray, and NSDictionary) identified by NSString keys, similar to an NSMutableDictionary.

Optimized for storing user settings: NSUserDefaults is intended for relatively small amounts of data, queried very frequently, and modified occasionally. Using it in other ways may be slow or use more memory than solutions more suited to those uses.

The ‘App’ CFPreferences functions in CoreFoundation act on the same search lists that NSUserDefaults does.

NSUserDefaults can be observed using Key-Value Observing for any key stored in it. Using NSKeyValueObservingOptionPrior to observe changes from other processes or devices will behave as though NSKeyValueObservingOptionPrior was not specified.

See also Apple’s documentation

Implementations§

Source§

impl NSUserDefaults

Source

pub unsafe fn standardUserDefaults() -> Retained<NSUserDefaults>

+standardUserDefaults returns a global instance of NSUserDefaults configured to search the current application’s search list.

Source

pub unsafe fn resetStandardUserDefaults()

+resetStandardUserDefaults releases the standardUserDefaults and sets it to nil. A new standardUserDefaults will be created the next time it’s accessed. The only visible effect this has is that all KVO observers of the previous standardUserDefaults will no longer be observing it.

Source

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

-init is equivalent to -initWithSuiteName:nil

Source

pub unsafe fn initWithSuiteName( this: Allocated<Self>, suitename: Option<&NSString>, ) -> Option<Retained<Self>>

Available on crate feature NSString only.

-initWithSuiteName: initializes an instance of NSUserDefaults that searches the shared preferences search list for the domain ‘suitename’. For example, using the identifier of an application group will cause the receiver to search the preferences for that group. Passing the current application’s bundle identifier, NSGlobalDomain, or the corresponding CFPreferences constants is an error. Passing nil will search the default search list.

Source

pub unsafe fn initWithUser( this: Allocated<Self>, username: &NSString, ) -> Option<Retained<Self>>

👎Deprecated: Use -init instead
Available on crate feature NSString only.

-initWithUser: is equivalent to -init

Source

pub unsafe fn objectForKey( &self, default_name: &NSString, ) -> Option<Retained<AnyObject>>

Available on crate feature NSString only.

-objectForKey: will search the receiver’s search list for a default with the key ‘defaultName’ and return it. If another process has changed defaults in the search list, NSUserDefaults will automatically update to the latest values. If the key in question has been marked as ubiquitous via a Defaults Configuration File, the latest value may not be immediately available, and the registered value will be returned instead.

Source

pub unsafe fn setObject_forKey( &self, value: Option<&AnyObject>, default_name: &NSString, )

Available on crate feature NSString only.

-setObject:forKey: immediately stores a value (or removes the value if nil is passed as the value) for the provided key in the search list entry for the receiver’s suite name in the current user and any host, then asynchronously stores the value persistently, where it is made available to other processes.

Source

pub unsafe fn removeObjectForKey(&self, default_name: &NSString)

Available on crate feature NSString only.

-removeObjectForKey: is equivalent to -[… setObject:nil forKey:defaultName]

Source

pub unsafe fn stringForKey( &self, default_name: &NSString, ) -> Option<Retained<NSString>>

Available on crate feature NSString only.

-stringForKey: is equivalent to -objectForKey:, except that it will convert NSNumber values to their NSString representation. If a non-string non-number value is found, nil will be returned.

Source

pub unsafe fn arrayForKey( &self, default_name: &NSString, ) -> Option<Retained<NSArray>>

Available on crate features NSArray and NSString only.

-arrayForKey: is equivalent to -objectForKey:, except that it will return nil if the value is not an NSArray.

Source

pub unsafe fn dictionaryForKey( &self, default_name: &NSString, ) -> Option<Retained<NSDictionary<NSString, AnyObject>>>

Available on crate features NSDictionary and NSString only.

-dictionaryForKey: is equivalent to -objectForKey:, except that it will return nil if the value is not an NSDictionary.

Source

pub unsafe fn dataForKey( &self, default_name: &NSString, ) -> Option<Retained<NSData>>

Available on crate features NSData and NSString only.

-dataForKey: is equivalent to -objectForKey:, except that it will return nil if the value is not an NSData.

Source

pub unsafe fn stringArrayForKey( &self, default_name: &NSString, ) -> Option<Retained<NSArray<NSString>>>

Available on crate features NSArray and NSString only.

-stringForKey: is equivalent to -objectForKey:, except that it will return nil if the value is not an NSArray <NSString *>. Note that unlike -stringForKey:, NSNumbers are not converted to NSStrings.

Source

pub unsafe fn integerForKey(&self, default_name: &NSString) -> NSInteger

Available on crate feature NSString only.

-integerForKey: is equivalent to -objectForKey:, except that it converts the returned value to an NSInteger. If the value is an NSNumber, the result of -integerValue will be returned. If the value is an NSString, it will be converted to NSInteger if possible. If the value is a boolean, it will be converted to either 1 for YES or 0 for NO. If the value is absent or can’t be converted to an integer, 0 will be returned.

Source

pub unsafe fn floatForKey(&self, default_name: &NSString) -> c_float

Available on crate feature NSString only.

-floatForKey: is similar to -integerForKey:, except that it returns a float, and boolean values will not be converted.

Source

pub unsafe fn doubleForKey(&self, default_name: &NSString) -> c_double

Available on crate feature NSString only.

-doubleForKey: is similar to -integerForKey:, except that it returns a double, and boolean values will not be converted.

Source

pub unsafe fn boolForKey(&self, default_name: &NSString) -> bool

Available on crate feature NSString only.

-boolForKey: is equivalent to -objectForKey:, except that it converts the returned value to a BOOL. If the value is an NSNumber, NO will be returned if the value is 0, YES otherwise. If the value is an NSString, values of “YES” or “1” will return YES, and values of “NO”, “0”, or any other string will return NO. If the value is absent or can’t be converted to a BOOL, NO will be returned.

Source

pub unsafe fn URLForKey( &self, default_name: &NSString, ) -> Option<Retained<NSURL>>

Available on crate features NSString and NSURL only.

-URLForKey: is equivalent to -objectForKey: except that it converts the returned value to an NSURL. If the value is an NSString path, then it will construct a file URL to that path. If the value is an archived URL from -setURL:forKey: it will be unarchived. If the value is absent or can’t be converted to an NSURL, nil will be returned.

Source

pub unsafe fn setInteger_forKey( &self, value: NSInteger, default_name: &NSString, )

Available on crate feature NSString only.

-setInteger:forKey: is equivalent to -setObject:forKey: except that the value is converted from an NSInteger to an NSNumber.

Source

pub unsafe fn setFloat_forKey(&self, value: c_float, default_name: &NSString)

Available on crate feature NSString only.

-setFloat:forKey: is equivalent to -setObject:forKey: except that the value is converted from a float to an NSNumber.

Source

pub unsafe fn setDouble_forKey(&self, value: c_double, default_name: &NSString)

Available on crate feature NSString only.

-setDouble:forKey: is equivalent to -setObject:forKey: except that the value is converted from a double to an NSNumber.

Source

pub unsafe fn setBool_forKey(&self, value: bool, default_name: &NSString)

Available on crate feature NSString only.

-setBool:forKey: is equivalent to -setObject:forKey: except that the value is converted from a BOOL to an NSNumber.

Source

pub unsafe fn setURL_forKey(&self, url: Option<&NSURL>, default_name: &NSString)

Available on crate features NSString and NSURL only.

-setURL:forKey is equivalent to -setObject:forKey: except that the value is archived to an NSData. Use -URLForKey: to retrieve values set this way.

Source

pub unsafe fn registerDefaults( &self, registration_dictionary: &NSDictionary<NSString, AnyObject>, )

Available on crate features NSDictionary and NSString only.

-registerDefaults: adds the registrationDictionary to the last item in every search list. This means that after NSUserDefaults has looked for a value in every other valid location, it will look in registered defaults, making them useful as a “fallback” value. Registered defaults are never stored between runs of an application, and are visible only to the application that registers them.

Default values from Defaults Configuration Files will automatically be registered.

Source

pub unsafe fn addSuiteNamed(&self, suite_name: &NSString)

Available on crate feature NSString only.

-addSuiteNamed: adds the full search list for ‘suiteName’ as a sub-search-list of the receiver’s. The additional search lists are searched after the current domain, but before global defaults. Passing NSGlobalDomain or the current application’s bundle identifier is unsupported.

Source

pub unsafe fn removeSuiteNamed(&self, suite_name: &NSString)

Available on crate feature NSString only.

-removeSuiteNamed: removes a sub-searchlist added via -addSuiteNamed:.

Source

pub unsafe fn dictionaryRepresentation( &self, ) -> Retained<NSDictionary<NSString, AnyObject>>

Available on crate features NSDictionary and NSString only.

-dictionaryRepresentation returns a composite snapshot of the values in the receiver’s search list, such that [[receiver dictionaryRepresentation] objectForKey:x] will return the same thing as [receiver objectForKey:x].

Source

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

Available on crate features NSArray and NSString only.
Source

pub unsafe fn volatileDomainForName( &self, domain_name: &NSString, ) -> Retained<NSDictionary<NSString, AnyObject>>

Available on crate features NSDictionary and NSString only.
Source

pub unsafe fn setVolatileDomain_forName( &self, domain: &NSDictionary<NSString, AnyObject>, domain_name: &NSString, )

Available on crate features NSDictionary and NSString only.
Source

pub unsafe fn removeVolatileDomainForName(&self, domain_name: &NSString)

Available on crate feature NSString only.
Source

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

👎Deprecated: Not recommended
Available on crate feature NSArray only.

-persistentDomainNames returns an incomplete list of domains that have preferences stored in them.

Source

pub unsafe fn persistentDomainForName( &self, domain_name: &NSString, ) -> Option<Retained<NSDictionary<NSString, AnyObject>>>

Available on crate features NSDictionary and NSString only.

-persistentDomainForName: returns a dictionary representation of the search list entry specified by ‘domainName’, the current user, and any host.

Source

pub unsafe fn setPersistentDomain_forName( &self, domain: &NSDictionary<NSString, AnyObject>, domain_name: &NSString, )

Available on crate features NSDictionary and NSString only.

-setPersistentDomain:forName: replaces all values in the search list entry specified by ‘domainName’, the current user, and any host, with the values in ‘domain’. The change will be persisted.

Source

pub unsafe fn removePersistentDomainForName(&self, domain_name: &NSString)

Available on crate feature NSString only.

-removePersistentDomainForName: removes all values from the search list entry specified by ‘domainName’, the current user, and any host. The change is persistent.

Source

pub unsafe fn synchronize(&self) -> bool

-synchronize is deprecated and will be marked with the API_DEPRECATED macro in a future release.

-synchronize blocks the calling thread until all in-progress set operations have completed. This is no longer necessary. Replacements for previous uses of -synchronize depend on what the intent of calling synchronize was. If you synchronized…

  • …before reading in order to fetch updated values: remove the synchronize call
  • …after writing in order to notify another program to read: the other program can use KVO to observe the default without needing to notify
  • …before exiting in a non-app (command line tool, agent, or daemon) process: call CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication)
  • …for any other reason: remove the synchronize call
Source

pub unsafe fn objectIsForcedForKey(&self, key: &NSString) -> bool

Available on crate feature NSString only.
Source

pub unsafe fn objectIsForcedForKey_inDomain( &self, key: &NSString, domain: &NSString, ) -> bool

Available on crate feature NSString only.
Source§

impl NSUserDefaults

Methods declared on superclass NSObject.

Source

pub unsafe fn new() -> Retained<Self>

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

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.

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,

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 NSUserDefaults

Source§

fn as_ref(&self) -> &AnyObject

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

impl AsRef<NSObject> for NSUserDefaults

Source§

fn as_ref(&self) -> &NSObject

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

impl AsRef<NSUserDefaults> for NSUserDefaults

Source§

fn as_ref(&self) -> &Self

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

impl Borrow<AnyObject> for NSUserDefaults

Source§

fn borrow(&self) -> &AnyObject

Immutably borrows from an owned value. Read more
Source§

impl Borrow<NSObject> for NSUserDefaults

Source§

fn borrow(&self) -> &NSObject

Immutably borrows from an owned value. Read more
Source§

impl ClassType for NSUserDefaults

Source§

const NAME: &'static str = "NSUserDefaults"

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 = <<NSUserDefaults as ClassType>::Super as ClassType>::ThreadKind

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 NSUserDefaults

Source§

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

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

impl Deref for NSUserDefaults

Source§

type Target = NSObject

The resulting type after dereferencing.
Source§

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

Dereferences the value.
Source§

impl Hash for NSUserDefaults

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 NSUserDefaults

Source§

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

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

impl NSObjectProtocol for NSUserDefaults

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 NSUserDefaults

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 NSUserDefaults

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 NSUserDefaults

Source§

impl Eq for NSUserDefaults

Auto Trait Implementations§

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<'a, T> AnyThread for T
where T: ClassType<ThreadKind = dyn AnyThread + 'a> + ?Sized,

Source§

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

Allocate a new instance of the class. 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<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,