#[repr(C)]pub struct NSUserDefaults { /* private fields */ }
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
impl NSUserDefaults
Sourcepub unsafe fn standardUserDefaults() -> Retained<NSUserDefaults>
pub unsafe fn standardUserDefaults() -> Retained<NSUserDefaults>
+standardUserDefaults returns a global instance of NSUserDefaults configured to search the current application’s search list.
Sourcepub unsafe fn resetStandardUserDefaults()
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.
Sourcepub unsafe fn init(this: Allocated<Self>) -> Retained<Self>
pub unsafe fn init(this: Allocated<Self>) -> Retained<Self>
-init is equivalent to -initWithSuiteName:nil
Sourcepub unsafe fn initWithSuiteName(
this: Allocated<Self>,
suitename: Option<&NSString>,
) -> Option<Retained<Self>>
Available on crate feature NSString
only.
pub unsafe fn initWithSuiteName( this: Allocated<Self>, suitename: Option<&NSString>, ) -> Option<Retained<Self>>
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.
Sourcepub unsafe fn initWithUser(
this: Allocated<Self>,
username: &NSString,
) -> Option<Retained<Self>>
👎Deprecated: Use -init insteadAvailable on crate feature NSString
only.
pub unsafe fn initWithUser( this: Allocated<Self>, username: &NSString, ) -> Option<Retained<Self>>
NSString
only.-initWithUser: is equivalent to -init
Sourcepub unsafe fn objectForKey(
&self,
default_name: &NSString,
) -> Option<Retained<AnyObject>>
Available on crate feature NSString
only.
pub unsafe fn objectForKey( &self, default_name: &NSString, ) -> Option<Retained<AnyObject>>
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.
Sourcepub unsafe fn setObject_forKey(
&self,
value: Option<&AnyObject>,
default_name: &NSString,
)
Available on crate feature NSString
only.
pub unsafe fn setObject_forKey( &self, value: Option<&AnyObject>, default_name: &NSString, )
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.
Sourcepub unsafe fn removeObjectForKey(&self, default_name: &NSString)
Available on crate feature NSString
only.
pub unsafe fn removeObjectForKey(&self, default_name: &NSString)
NSString
only.-removeObjectForKey: is equivalent to -[… setObject:nil forKey:defaultName]
Sourcepub unsafe fn stringForKey(
&self,
default_name: &NSString,
) -> Option<Retained<NSString>>
Available on crate feature NSString
only.
pub unsafe fn stringForKey( &self, default_name: &NSString, ) -> Option<Retained<NSString>>
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.
Sourcepub unsafe fn arrayForKey(
&self,
default_name: &NSString,
) -> Option<Retained<NSArray>>
Available on crate features NSArray
and NSString
only.
pub unsafe fn arrayForKey( &self, default_name: &NSString, ) -> Option<Retained<NSArray>>
NSArray
and NSString
only.-arrayForKey: is equivalent to -objectForKey:, except that it will return nil if the value is not an NSArray.
Sourcepub unsafe fn dictionaryForKey(
&self,
default_name: &NSString,
) -> Option<Retained<NSDictionary<NSString, AnyObject>>>
Available on crate features NSDictionary
and NSString
only.
pub unsafe fn dictionaryForKey( &self, default_name: &NSString, ) -> Option<Retained<NSDictionary<NSString, AnyObject>>>
NSDictionary
and NSString
only.-dictionaryForKey: is equivalent to -objectForKey:, except that it will return nil if the value is not an NSDictionary.
Sourcepub unsafe fn dataForKey(
&self,
default_name: &NSString,
) -> Option<Retained<NSData>>
Available on crate features NSData
and NSString
only.
pub unsafe fn dataForKey( &self, default_name: &NSString, ) -> Option<Retained<NSData>>
NSData
and NSString
only.-dataForKey: is equivalent to -objectForKey:, except that it will return nil if the value is not an NSData.
Sourcepub unsafe fn stringArrayForKey(
&self,
default_name: &NSString,
) -> Option<Retained<NSArray<NSString>>>
Available on crate features NSArray
and NSString
only.
pub unsafe fn stringArrayForKey( &self, default_name: &NSString, ) -> Option<Retained<NSArray<NSString>>>
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.
Sourcepub unsafe fn integerForKey(&self, default_name: &NSString) -> NSInteger
Available on crate feature NSString
only.
pub unsafe fn integerForKey(&self, default_name: &NSString) -> NSInteger
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.
Sourcepub unsafe fn floatForKey(&self, default_name: &NSString) -> c_float
Available on crate feature NSString
only.
pub unsafe fn floatForKey(&self, default_name: &NSString) -> c_float
NSString
only.-floatForKey: is similar to -integerForKey:, except that it returns a float, and boolean values will not be converted.
Sourcepub unsafe fn doubleForKey(&self, default_name: &NSString) -> c_double
Available on crate feature NSString
only.
pub unsafe fn doubleForKey(&self, default_name: &NSString) -> c_double
NSString
only.-doubleForKey: is similar to -integerForKey:, except that it returns a double, and boolean values will not be converted.
Sourcepub unsafe fn boolForKey(&self, default_name: &NSString) -> bool
Available on crate feature NSString
only.
pub unsafe fn boolForKey(&self, default_name: &NSString) -> bool
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.
Sourcepub unsafe fn URLForKey(
&self,
default_name: &NSString,
) -> Option<Retained<NSURL>>
Available on crate features NSString
and NSURL
only.
pub unsafe fn URLForKey( &self, default_name: &NSString, ) -> Option<Retained<NSURL>>
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.
Sourcepub unsafe fn setInteger_forKey(
&self,
value: NSInteger,
default_name: &NSString,
)
Available on crate feature NSString
only.
pub unsafe fn setInteger_forKey( &self, value: NSInteger, default_name: &NSString, )
NSString
only.-setInteger:forKey: is equivalent to -setObject:forKey: except that the value is converted from an NSInteger to an NSNumber.
Sourcepub unsafe fn setFloat_forKey(&self, value: c_float, default_name: &NSString)
Available on crate feature NSString
only.
pub unsafe fn setFloat_forKey(&self, value: c_float, default_name: &NSString)
NSString
only.-setFloat:forKey: is equivalent to -setObject:forKey: except that the value is converted from a float to an NSNumber.
Sourcepub unsafe fn setDouble_forKey(&self, value: c_double, default_name: &NSString)
Available on crate feature NSString
only.
pub unsafe fn setDouble_forKey(&self, value: c_double, default_name: &NSString)
NSString
only.-setDouble:forKey: is equivalent to -setObject:forKey: except that the value is converted from a double to an NSNumber.
Sourcepub unsafe fn setBool_forKey(&self, value: bool, default_name: &NSString)
Available on crate feature NSString
only.
pub unsafe fn setBool_forKey(&self, value: bool, default_name: &NSString)
NSString
only.-setBool:forKey: is equivalent to -setObject:forKey: except that the value is converted from a BOOL to an NSNumber.
Sourcepub unsafe fn setURL_forKey(&self, url: Option<&NSURL>, default_name: &NSString)
Available on crate features NSString
and NSURL
only.
pub unsafe fn setURL_forKey(&self, url: Option<&NSURL>, default_name: &NSString)
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.
Sourcepub unsafe fn registerDefaults(
&self,
registration_dictionary: &NSDictionary<NSString, AnyObject>,
)
Available on crate features NSDictionary
and NSString
only.
pub unsafe fn registerDefaults( &self, registration_dictionary: &NSDictionary<NSString, AnyObject>, )
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.
Sourcepub unsafe fn addSuiteNamed(&self, suite_name: &NSString)
Available on crate feature NSString
only.
pub unsafe fn addSuiteNamed(&self, suite_name: &NSString)
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.
Sourcepub unsafe fn removeSuiteNamed(&self, suite_name: &NSString)
Available on crate feature NSString
only.
pub unsafe fn removeSuiteNamed(&self, suite_name: &NSString)
NSString
only.-removeSuiteNamed: removes a sub-searchlist added via -addSuiteNamed:.
Sourcepub unsafe fn dictionaryRepresentation(
&self,
) -> Retained<NSDictionary<NSString, AnyObject>>
Available on crate features NSDictionary
and NSString
only.
pub unsafe fn dictionaryRepresentation( &self, ) -> Retained<NSDictionary<NSString, AnyObject>>
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].
pub unsafe fn volatileDomainNames(&self) -> Retained<NSArray<NSString>>
NSArray
and NSString
only.pub unsafe fn volatileDomainForName( &self, domain_name: &NSString, ) -> Retained<NSDictionary<NSString, AnyObject>>
NSDictionary
and NSString
only.pub unsafe fn setVolatileDomain_forName( &self, domain: &NSDictionary<NSString, AnyObject>, domain_name: &NSString, )
NSDictionary
and NSString
only.pub unsafe fn removeVolatileDomainForName(&self, domain_name: &NSString)
NSString
only.Sourcepub unsafe fn persistentDomainNames(&self) -> Retained<NSArray>
👎Deprecated: Not recommendedAvailable on crate feature NSArray
only.
pub unsafe fn persistentDomainNames(&self) -> Retained<NSArray>
NSArray
only.-persistentDomainNames returns an incomplete list of domains that have preferences stored in them.
Sourcepub unsafe fn persistentDomainForName(
&self,
domain_name: &NSString,
) -> Option<Retained<NSDictionary<NSString, AnyObject>>>
Available on crate features NSDictionary
and NSString
only.
pub unsafe fn persistentDomainForName( &self, domain_name: &NSString, ) -> Option<Retained<NSDictionary<NSString, AnyObject>>>
NSDictionary
and NSString
only.-persistentDomainForName: returns a dictionary representation of the search list entry specified by ‘domainName’, the current user, and any host.
Sourcepub unsafe fn setPersistentDomain_forName(
&self,
domain: &NSDictionary<NSString, AnyObject>,
domain_name: &NSString,
)
Available on crate features NSDictionary
and NSString
only.
pub unsafe fn setPersistentDomain_forName( &self, domain: &NSDictionary<NSString, AnyObject>, domain_name: &NSString, )
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.
Sourcepub unsafe fn removePersistentDomainForName(&self, domain_name: &NSString)
Available on crate feature NSString
only.
pub unsafe fn removePersistentDomainForName(&self, domain_name: &NSString)
NSString
only.-removePersistentDomainForName: removes all values from the search list entry specified by ‘domainName’, the current user, and any host. The change is persistent.
Sourcepub unsafe fn synchronize(&self) -> bool
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
pub unsafe fn objectIsForcedForKey(&self, key: &NSString) -> bool
NSString
only.pub unsafe fn objectIsForcedForKey_inDomain( &self, key: &NSString, domain: &NSString, ) -> bool
NSString
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 AsRef<AnyObject> for NSUserDefaults
impl AsRef<AnyObject> for NSUserDefaults
Source§impl AsRef<NSObject> for NSUserDefaults
impl AsRef<NSObject> for NSUserDefaults
Source§impl AsRef<NSUserDefaults> for NSUserDefaults
impl AsRef<NSUserDefaults> for NSUserDefaults
Source§impl Borrow<AnyObject> for NSUserDefaults
impl Borrow<AnyObject> for NSUserDefaults
Source§impl Borrow<NSObject> for NSUserDefaults
impl Borrow<NSObject> for NSUserDefaults
Source§impl ClassType for NSUserDefaults
impl ClassType for NSUserDefaults
Source§const NAME: &'static str = "NSUserDefaults"
const NAME: &'static str = "NSUserDefaults"
Source§type ThreadKind = <<NSUserDefaults as ClassType>::Super as ClassType>::ThreadKind
type ThreadKind = <<NSUserDefaults as ClassType>::Super as ClassType>::ThreadKind
Source§impl Debug for NSUserDefaults
impl Debug for NSUserDefaults
Source§impl Deref for NSUserDefaults
impl Deref for NSUserDefaults
Source§impl Hash for NSUserDefaults
impl Hash for NSUserDefaults
Source§impl Message for NSUserDefaults
impl Message for NSUserDefaults
Source§impl NSObjectProtocol for NSUserDefaults
impl NSObjectProtocol for NSUserDefaults
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