Introduction and use of NSUserDefaults API in both Chinese and English documents

Source: Internet
Author: User

Introduction and use of NSUserDefaults API in both Chinese and English documents

Overview


The NSUserDefaults class provides a programmatic interface for interacting with the defaults system. the defaults system allows an application to customize its behavior to match a user's preferences. for example, you can allow users to determine what units of measurement your application displays or how often tables ENTs are automatically saved. applications record such preferences by assigning values to a set of parameters in a user's ults database. the parameters are referred to as defaults since they're commonly used to determine an application's default state at startup or the way it acts by default.

At runtime, you use anNSUserDefaults object to read the defaults that your application uses from a user's defaults database. NSUserDefaults caches the information to avoid having to open the user's defaults database each time you need a default value. thesynchronize method, which is automatically invoked at periodic intervals, keeps the in-memory cache in sync with a user's ults database.

The NSUserDefaults class provides convenience methods for accessing common types such as floats, doubles, integers, Booleans, and URLs. A default object must be a property list, that is, an instance of (or for collections a combination of instances of): NSData, NSString, NSNumber, NSDate, NSArray, orNSDictionary. if you want to store any other type of object, you should typically archive it to create an instance ofNSData. for more details, seePreferences and Settings Programming Guide.

Values returned fromNSUserDefaults are immutable, even if you set a mutable object as the value. for example, if you set a mutable string as the value for "MyStringDefault", the string you later retrieve using stringForKey: will be immutable.

A defaults database is created automatically for each user. theNSUserDefaults class does not currently support per-host preferences. to do this, you must use the CFPreferences API (seePreferences Utilities Reference ). however, NSUserDefaults correctly reads per-host preferences, so you can safely mix CFPreferences code withNSUserDefaults code.

If your application supports managed environments, you can use anNSUserDefaults object to determine which preferences are managed by an administrator for the benefit of the user. managed environments correspond to computer labs or classrooms where an administrator or teacher may want to configure the systems in a participant way. in these situations, the teacher can establish a set of default preferences and force those preferences on users. if a preference is managed in this manner, applications shocould prevent users from editing that preference by disabling any appropriate controls.

The NSUserDefaults class is thread-safe.

Tasks


Getting the Shared NSUserDefaults Instance


  • + StandardUserDefaults
  • + ResetStandardUserDefaults

    Initializing an NSUserDefaults Object


    • -Init
    • -InitWithUser: Deprecated in OS X v10.9

      Registering Defaults


      • -RegisterDefaults:

        Getting Default Values


        • -ArrayForKey:
        • -BoolForKey:
        • -DataForKey:
        • -DictionaryForKey:
        • -FloatForKey:
        • -IntegerForKey:
        • -ObjectForKey:
        • -StringArrayForKey:
        • -StringForKey:
        • -DoubleForKey:
        • -URLForKey:

          Setting Default Values


          • -SetBool: forKey:
          • -SetFloat: forKey:
          • -SetInteger: forKey:
          • -SetObject: forKey:
          • -SetDouble: forKey:
          • -SetURL: forKey:

            Removing Defaults


            • -RemoveObjectForKey:

              Maintaining Persistent Domains


              • -Synchronize
              • -PersistentDomainForName:
              • -RemovePersistentDomainForName:
              • -SetPersistentDomain: forName:
              • -PersistentDomainNamesDeprecated in OS X v10.9

                Accessing Managed Environment Keys


                • -ObjectIsForcedForKey:
                • -ObjectIsForcedForKey: inDomain:

                  Managing the Search List


                  • -DictionaryRepresentation

                    Maintaining Volatile Domains


                    • -RemoveVolatileDomainForName:
                    • -SetVolatileDomain: forName:
                    • -VolatileDomainForName:
                    • -VolatileDomainNames

                      Maintaining Suites


                      • -AddSuiteNamed:
                      • -RemoveSuiteNamed:


                        The meaning of NSUserDefaults API is as follows:

                        The NSUserDefaults class provides a programming interface for interacting with the default system. The NSUserDefaults object is used to save and restore preference settings and configuration data related to the application. By default, the system allows applications to customize their behaviors to suit users' preferences. You can read the program settings from the user's default database when the program is running. At the same time, the NSUserDefaults cache avoids enabling the user's default database every time the data is read. You can call the synchronize method to synchronize the cache in the memory with the user's default system.


                        The NSUserDefaults class provides a very convenient way to obtain common types, such as floats, doubles, intergers, Booleans, and URLs. Therefore, an NSUserDefaults object must be an Attribute Table, which means we can store instances such as NSData, NSString, NSNUmber, NSDate, NSArray, and NSDictionary. If you want to store other types of objects, You need to archive them and create an NSData for storage.

                        The value returned from NSUserDefaults cannot be changed, even if you are using a variable value during storage. For example, if you use mutable string as the value of "MyStringDefault", the value obtained by using the stringForKey: method is still unchangeable.

                        NSUserDefaults is a singleton and thread-safe.


                        Detailed method to obtain a public NSUserDefaults instance[Plain]View plaincopy
                        1. + (NSUserDefaults *) standardUserDefaults;
                        2. In Singleton mode, obtain an instance of NSUserDefaults. The default Key value is as follows:
                        3. AppleLanguages,
                        4. AppleKeyboardsExpanded,
                        5. AppleITunesStoreItemKinds,
                        6. AppleLocale,
                        7. AppleKeyboards,
                        8. NSLanguages,
                        9. NSInterfaceStyle
                          [Plain]View plaincopy
                          1. + (Void) resetStandardUserDefaults; Initialize an NSUserDefaults object[Plain]View plaincopy
                            1. -(Id) init;
                            2. -(Id) initWithUser :( NSString *) username;
                            3. Init is a public ults object.
                            4. InitWithUser is used to initialize a defaults object for username registration.[Plain]View plaincopy
                              1. -(Void) registerDefaults :( NSDictionary *) registrationDictionary;
                              2. The registered content (in registrationDictionary) is not written to the disk to obtain the Defaults value.[Plain]View plaincopy
                                1. -(NSArray *) arrayForKey :( NSString *) defaultName;[Plain]View plaincopy
                                  1. -(BOOL) boolForKey :( NSString *) defaultName;
                                  2. Returns a Boolean value associated with defaultName. If defaname does not exist, NO is returned.[Plain]View plaincopy
                                    1. -(NSData *) dataForKey :( NSString *) defaultName
                                    2. Returns the NSData data of defaultName. If defaname does not exist or the returned data is not of the NSData type, nil is returned.
                                    3. The returned data is of an unchangeable type.[Plain]View plaincopy
                                      1. -(NSDictionary *) dictionaryForKey :( NSString *) defaultName
                                      2. Same as dataForKey[Plain]View plaincopy
                                        1. -(Float) floatForKey :( NSString *) defaultName
                                        2. Same as dataForKey
                                        3. If defaultName does not exist, 0 is returned.[Plain]View plaincopy
                                          1. -(NSInteger) integerForKey :( NSString *) defaultName
                                          2. Same as floatForKey
                                          3. If defaultName does not exist, 0 is returned.[Plain]View plaincopy
                                            1. -(Id) objectForKey :( NSString *) defaultName
                                            2. Same as dataForKey[Plain]View plaincopy
                                              1. -(NSArray *) stringArrayForKey :( NSString *) defaultName
                                              2. Same as dataForKey
                                              3. If defaultName does not exist, or defaultName does not correspond to an array, or if the array does not contain an NSString object, nil is returned.[Plain]View plaincopy
                                                1. -(NSString *) stringForKey :( NSString *) defaultName
                                                2. Same as dataForKey[Plain]View plaincopy
                                                  1. -(Double) doubleForKey :( NSString *) defaultName
                                                  2. Same as floatForKey[Plain]View plaincopy
                                                    1. -(NSURL *) URLForKey :( NSString *) defaultName
                                                    2. Same as dataForKey
                                                    3. When [NSUserDefaults URLForKey:] is called, there are three situations:
                                                    4. 1. If the value is NSData, NSData can be used as a parameter for [NSKeyedUnarchiver unarchiveObjectWithData. If NSData can be archived as an NSURL, an NSURL is returned. Otherwise, nil is returned.
                                                    5. 2. If the value is the URL referenced by a file, the URL referenced by the file will be created, but its bookmarks will not be resolved until NSURL instance is used in the future.
                                                    6. 3. If the value is ~ This string will be extended using [NSString stringByExpandingTildeInPath], and the file will be created with NSURL to set the ults Value[Plain]View plaincopy
                                                      1. -SetBool: forKey:
                                                      2. -SetFloat: forKey:
                                                      3. -SetInteger: forKey:
                                                      4. -SetDouble: forKey:
                                                      5. -SetObject: forKey:
                                                      6. Object parameters can only be attribute list objects: NSData, NSString, NSNumber, NSDate, NSArray, NSDictionary
                                                      7. -SetURL: forKey: remove the ults Value[Plain]View plaincopy
                                                        1. -(Void) removeObjectForKey :( NSString *) ultname maintains the persistent domain[Plain]View plaincopy
                                                          1. -(BOOL) synchronize
                                                          2. Write any changes in the persistent domain to the disk and update any unmodified persistent domain on the disk.
                                                          3. If YES is returned, the data is successfully saved to the disk. Otherwise, NO is returned.
                                                          4. This method is automatically called at intervals of a certain period. If you do not want to wait for the automatic call, you can call this method for synchronization. (For example, if your application is about to exit, or you want to update the ults on the disk even if you have not made any changes)[Plain]View plaincopy
                                                            1. -(NSDictionary *) persistentDomainForName :( NSString *) domainName
                                                            2. Returns the key-value pairs of a specific persistent domain.[Plain]View plaincopy
                                                              1. -(NSArray *) persistentDomainNames
                                                              2. Returns the name of the current persistent domain.[Plain]View plaincopy
                                                                1. -(Void) removePersistentDomainForName :( NSString *) domainName
                                                                2. Remove the persistent domain of the corresponding domainName[Plain]View plaincopy
                                                                  1. -(Void) setPersistentDomain :( NSDictionary *) domain forName :( NSString *) domainName
                                                                  2. Set persistent domain
                                                                  3. DomainName
                                                                  4. This value shoshould be equal to your application's bundle identifier. Environment value of Access Management[Plain]View plaincopy
                                                                    1. -(BOOL) objectIsForcedForKey :( NSString *) key
                                                                    2. -(BOOL) objectIsForcedForKey :( NSString *) key inDomain :( NSString *) domain management search list[Plain]View plaincopy
                                                                      1. -(NSDictionary *) dictionaryRepresentation
                                                                      2. Returns all key-value pairs of the corresponding domains in the search list that are not stable.[Plain]View plaincopy
                                                                        1. -RemoveVolatileDomainForName:
                                                                        2. -SetVolatileDomain: forName:
                                                                        3. -VolatileDomainForName:
                                                                        4. -VolatileDomainNames maintenance suite[Plain]View plaincopy
                                                                          1. -(Void) addSuiteNamed :( NSString *) suiteName
                                                                          2. One suite can be used between different applications[Plain]View plaincopy
                                                                            1. -(Void) removeSuiteNamed :( NSString *) suiteName
                                                                            2. Remove Kit


                                                                              The sample code is as follows:


                                                                              # Pragma mark --------- save // create NSUserDefaults Singleton NSUserDefaults * ud = [NSUserDefaults standardUserDefaults]; // SET _ userNameTextField. text is saved to NSUserDefaults [ud setObject: _ userNameTextField. text forKey: @ "myKey"]; # pragma mark --------- extract data from NSUserDefaults NSString * value = [ud objectForKey: @ "myKey"]; NSLog (@ "value = % @", value );






Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.