IOS has a complete data security system. IOS applications can only access their own directory, which is called the sandbox directory, and data sharing between applications is prohibited. Certain applications, such as contacts, must be accessed through specific apis.

The sandbox directories

Sandbox directory is a kind of data security strategy. Many systems use sandbox design, and some browsers that implement THE HTML5 specification also use sandbox design. The principle of sandbox directory design is to only allow their own applications to access the directory, and not allow other applications to access the directory. The sandbox directory has three subdirectories, Documents, Library, and TMP.

Get the home directory of the sandbox directory:

NSString *path = NSHomeDirectory();
NSLog(@"path : %@", path);
Copy the code

Documents directory: This directory is used to store very large files or data that needs to be updated very frequently and is capable of iTunes or iCloud backups.

Get the Documents directory location:

NSArray *documentArray = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [documentArray lastObject];
NSLog(@"% @",documentsPath);
Copy the code

Library directory: Under the Library directory you have the Preferences and Caches directories, where Preferences are used to store the application’s Settings data, and Caches are used to store the application’s data and cache files.

Get the Library directory location:

NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSLog(@"path : %@", pathArray.lastObject);
Copy the code

Tem directory: A temporary file directory that users can access and that cannot be used for iTunes or iCloud backups.

Get the TEM directory location:

NSString *temPath = NSTemporaryDirectory();
Copy the code

NSuserDefault

NSUserDefaults is a hierarchical persistent interprocess (optional distributed) key-value store optimized for storing user Settings. Defines an interface to the user’s default database.

NSUserDefaults is a singleton, and every application has one (and only one) NSUserDefaults object. This object is obtained by sending the standardUserDefaults message to the NSUserDefaults class.

NSUserDefaults caches information when it is read using an NSUserDefaults object, and when it is set, it synchronizes changes in the current process and asynchronously changes to persistent storage and other processes. Local data stored in NSUserDefaults remains unchanged when the application is restarted.

For any key that’s stored in there, you can use key-value observation to look at NSUserDefaults, When NSUserDefaults instance data stored by the changes, the system will send NSUserDefaultsDidChangeNotification notice, notification will return the current change of NSUserDefaults instance objects back.

Data types supported by NSUserDefaults

NSUserDefaults is a good place to store lightweight, frequently queried and occasionally modified local data. The Key must be an NSString object, with each Key corresponding to one setting (preference). The object accessed must be an object or a value of primitive type. If it is an object, it must be a serializable object. The supported data types are NSNumber, NSString, NSDate, NSArray, NSDictionary, and BOOL. Note that NSUserDefaults stores all immutable objects.

Path to the NSUserDefaults file

The sandbox path for storing files is Library/Preferences

The file format is.plist

Such as:

NSUserDefaults domain

The UserDefaults database is actually made up of multiple levels of fields. When reading a key value, NSUserDefaults looks for the correct value from top to bottom through the level of fields. Different fields have different functions, some fields are durable, others are not. Default contains five domains, as follows:

  • 1. The argument domain has the highest priority.
  • The application domain stores your app in NSUserDefaults set… ForKey added Settings.
  • 3. The Global domain stores system Settings.
  • Language-specific domains include areas, dates, etc.
  • The registration domain has a lower priority and is searched only from the registration domain if the application domain does not find a value.

For example, when an interface is run for the first time, the corresponding key value does not yet exist, so NSUserDefaults objects use a default value of 0. However, for some Settings, temporary, non-zero defaults may be required (such as “factory Settings”), otherwise the application will not work correctly. The default values are generally stored in the registered domain. By default, the application field is empty, with no keys and no values. When a user modifies a setting for the first time, the value is added to the application domain using the specified key. When a setting is retrieved from an NSUserDefaults object, the object looks up in the application domain. If not, NSUserDefaults looks up in the registered domain and returns the default values. Search order: Parameter domain > Application Domain > Global domain > Language domain > Registration domain.

Advantages and disadvantages of NSUserDefaults

Advantages:

  • You don’t need to care about the file name.
  • Fast key-value pair storage.
  • Store basic data types directly.

Disadvantages:

  • Custom data cannot be stored.
  • The data is immutable.

Common properties and functions provided by NSuserDefault

@property (class, readonly, strong) NSUserDefaults *standardUserDefaults;

Property description: Returns a global instance of NSUserDefaults.

@property (class, readonly, strong) NSUserDefaults *standardUserDefaults;
Copy the code

– (void)setObject:(nullable id)value forKey:(NSString *)defaultName;

Function description: Immediately stores the value of the supplied Key in the search list item (if the value passed is nil, it is removed), and then asynchronously persists the value if it is available to other processes.

Parameters:

Value: Object to be stored in the default database.

DefaultName: The key associated with the value.

- (void)setObject:(nullable id)value forKey:(NSString *)defaultName;
Copy the code

– (BOOL)synchronize;

Function description: Waits for any pending asynchronous updates to the default database and returns (waits for data to persist). This function is not recommended.

Return value: YES if the data is saved to disk successfully, NO otherwise.

- (BOOL)synchronize;
Copy the code

For example, storing data:

[[NSUserDefaults standardUserDefaults] setObject:@"I'm so happy." forKey:@"Happy eating and growing again."];
[[NSUserDefaults standardUserDefaults] synchronize];
Copy the code

– (nullable id)objectForKey:(NSString *)defaultName;

Function: returns the object associated with the specified key. This method searches the fields included in the search list in their listing order and returns the object associated with the first match that specifies the default value.

Parameters:

DefaultName: the Key in the default database for the current user.

Return value: The object associated with the specified key, or nil if no key can be found.

- (nullable id)objectForKey:(NSString *)defaultName;
Copy the code

For example, fetching data:

NSString *Study = [NSUserDefaults standardUserDefaults] objectForKey:@"Happy eating and growing again."];
Copy the code

– (void)removeObjectForKey:(NSString *)defaultName;

Delete the value of the specified default Key. If the same Key exists in the fields that precede the standard application fields in the search list, removing the default does not affect the value returned by the objectForKey: method.

Parameters:

DefaultName: The Key whose value is to be removed.

- (void)removeObjectForKey:(NSString *)defaultName;
Copy the code

– (nullable NSString *)stringForKey:(NSString *)defaultName;

Function description: Returns the string associated with the specified Key. The string returned is immutable, even if the value originally set was a mutable string.

Parameters:

DefaultName: the Key in the default database for the current user.

Return value: For string values, the string associated with the specified Key; For numeric values, is the string value of a number. If the default value does not exist or is not a string or numeric value, nil is returned.

- (nullable NSString *)stringForKey:(NSString *)defaultName;
Copy the code

– (nullable NSArray *)arrayForKey:(NSString *)defaultName;

Function description: Returns an array associated with the specified Key. The returned array and its contents are immutable, even if the value originally set was mutable.

Parameters:

DefaultName: the Key in the default database for the current user.

Return value: The array associated with the specified Key, nil if the Key does not exist or its value is not an array.

- (nullable NSArray *)arrayForKey:(NSString *)defaultName;
Copy the code

– (nullable NSDictionary<NSString *, id> *)dictionaryForKey:(NSString *)defaultName;

Function description: Returns the dictionary object associated with the specified Key. The dictionary returned and its contents are immutable, even if the value originally set was mutable.

Parameters:

DefaultName: the Key in the default database for the current user.

Return value: The NSDictionary object associated with the specified key, nil if the key does not exist or its value is not NSDictionary.

- (nullable NSDictionary<NSString *, id> *)dictionaryForKey:(NSString *)defaultName;
Copy the code

– (nullable NSData *)dataForKey:(NSString *)defaultName;

Function description: Returns the data object associated with the specified Key. The data object returned is immutable, even if the value originally set was a mutable data object.

Parameters:

DefaultName: the Key in the default database for the current user.

Return value: The NSData object associated with the specified key, nil if the key does not exist or its value is not an NSData object.

- (nullable NSData *)dataForKey:(NSString *)defaultName;
Copy the code

– (nullable NSArray<NSString *> *)stringArrayForKey:(NSString *)defaultName;

Function: returns an array of strings associated with the specified Key. The returned array and its contents are immutable, even if the value originally set was mutable.

Parameters:

DefaultName: the Key in the default database for the current user.

Return value: Array of string objects, nil if the specified default does not exist, does not contain an array, or does not contain a string.

- (nullable NSArray<NSString *> *)stringArrayForKey:(NSString *)defaultName;
Copy the code

– (void)setInteger:(NSInteger)value forKey:(NSString *)defaultName;

The default Key value is set to the specified integer value. This is a convenient way to call setObject forKey.

Parameters:

Value: Integer value to be stored in the default database.

DefaultName: The Key associated with the value.

- (void)setInteger:(NSInteger)value forKey:(NSString *)defaultName;
Copy the code

– (NSInteger)integerForKey:(NSString *)defaultName;

Function description: Returns the integer value associated with the specified Key. This method automatically casts some values to the equivalent integer value (if the conversion can be determined). The Boolean value YES becomes 1 and NO becomes 0. A floating point number becomes the largest integer less than that number (for example, 2.67 becomes 2). A string representing an integer becomes an equivalent integer (for example, 123 becomes 123).

Parameters:

DefaultName: the Key in the default database for the current user.

Return value: the integer value associated with the specified Key. This method returns 0 if the specified Key does not exist.

- (NSInteger)integerForKey:(NSString *)defaultName;
Copy the code

– (void)setFloat:(float)value forKey:(NSString *)defaultName;

Function description: Sets the specified default Key value to the specified floating point value. This is a convenient way to call setObject forKey.

Parameters:

Value: Floating point value to be stored in the default database.

DefaultName: The Key associated with the value.

- (void)setFloat:(float)value forKey:(NSString *)defaultName;
Copy the code

– (float)floatForKey:(NSString *)defaultName;

Function description: Returns the floating point value associated with the specified Key. This method automatically casts some values to equivalent floating-point values (if the conversion can be determined). The Boolean value YES becomes 1.0 and NO becomes 0.0. Integers become floating point equivalents (for example, 2 becomes 2.0). A string representing a floating point number becomes its floating point equivalent (for example, “123.4” becomes 123.4).

Parameters:

DefaultName: the Key in the default database for the current user.

Return value: the floating point value associated with the specified Key. If the Key does not exist, this method returns 0.

- (float)floatForKey:(NSString *)defaultName;
Copy the code

– (void)setDouble:(double)value forKey:(NSString *)defaultName;

Function description: Sets the specified default Key value to a double-precision floating-point value. This is a convenient way to call setObject forKey.

Parameters:

Value: a double-precision floating point value to be stored in the default database.

DefaultName: The Key associated with the value.

- (void)setDouble:(double)value forKey:(NSString *)defaultName;
Copy the code

– (double)doubleForKey:(NSString *)defaultName;

Function description: Returns a double-precision floating-point value associated with the specified key. This method automatically casts some values to an equivalent double value (if it can be determined). The Boolean value YES becomes 1.000000 and NO becomes 0.000000. The integer becomes an equivalent double (for example, 2 becomes 2.000000). A string representing a floating point number becomes an equivalent double (for example, “123.40000000000001” becomes 123.40000000000001).

Parameters:

DefaultName: the Key in the default database for the current user.

Return value: the double precision floating point value associated with the specified Key. If the Key does not exist, this method returns 0.

- (double)doubleForKey:(NSString *)defaultName;
Copy the code

– (void)setBool:(BOOL)value forKey:(NSString *)defaultName;

The specified default Key is set to the specified Boolean value. This is a convenient way to call setObject forKey.

Parameters:

Value: Boolean value to be stored in the default database.

DefaultName: The Key associated with the value.

- (void)setBool:(BOOL)value forKey:(NSString *)defaultName;
Copy the code

– (BOOL)boolForKey:(NSString *)defaultName;

Function description: Returns the Boolean value associated with the specified Key. This method automatically forces certain “truthy” values (such as the strings “true”, “YES” and “1”, and the numbers 1 and 1.0) to the Boolean value YES. The same is true for certain “falsy” values, such as the strings “false,” “NO,” and “0,” as well as the numbers 0 and 0.0, which are automatically enforced as Boolean values NO.

Parameters:

DefaultName: the Key in the default database for the current user.

Return value: The Boolean value associated with the specified Key. If the specified Key does not exist, this method returns no.

- (BOOL)boolForKey:(NSString *)defaultName;
Copy the code

– (void)setURL:(nullable NSURL *)url forKey:(NSString *)defaultName API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), Tvos (9.0));

The URL () function sets the default Key to the specified URL. If the url is the file url, it is the method the absolute url, to determine whether the path can be relative to the user’s home directory to create, if you can, use the stringByAbbreviatingWithTildeInPath method on the abbreviations. If the url is not the file url, it is by calling archivedDataWithRootObject: method and transfer the url as the root object to create data objects.

Parameters:

Url: THE URL to store in the default database.

DefaultName: The Key associated with the value.

- (void)setURL:(nullable NSURL *)url forKey (NSString *)defaultName API_AVAILABLE(MacOS (10.6), ios(4.0), Watchos (2.0), TVOs (9.0));Copy the code

– (void)registerDefaults:(NSDictionary<NSString *, id> *)registrationDictionary;

Adds the contents of the specified dictionary to the registry domain. If there is no registry domain, one is created using the specified dictionary and the NSRegistrationDomain is added to the end of the search list. The contents of the registered domain are not written to disk; You need to call this method every time you start the application. You can place the plist file in your application’s Resources directory and call the registerDefaults: method with what you read from that file.

Parameters:

Dictionary: dictionary of keys and values to be registered.

- (void)registerDefaults:(NSDictionary<NSString *, id> *)registrationDictionary;
Copy the code

– (void)addSuiteNamed:(NSString *)suiteName;

Inserts the specified domain name into the recipient’s search list. The suiteName field is similar to a bundle identifier string, but is not necessarily bound to a specific application or bundle. A suite can be used to hold preferences shared between multiple applications. The additional search list for the suiteName field is searched after the current field but before the global default (that is, when adding a suite, the preference subsystem searches first for the application’s user preferences, then again as if it were an application with a bundle identifier equal to suiteName, and finally for the global preferences). Passing NSGlobalDomain or the bundle identifier of the current application is not supported.

Parameters:

SuiteName: domain name to be inserted.

- (void)addSuiteNamed:(NSString *)suiteName;
Copy the code

– (void)removeSuiteNamed:(NSString *)suiteName;

Removes the specified domain name from the receiver’s search list.

Parameters:

SuiteName: Domain name to be deleted.

- (void)removeSuiteNamed:(NSString *)suiteName;
Copy the code

– (NSDictionary<NSString *, id> *)dictionaryRepresentation;

Function description: Returns a dictionary containing the union of all key-value pairs in the search list. As with objectForKey:, key-value pairs in the earlier fields in the search list take precedence. The result of the merge does not retain information about which domain each entry came from.

Return value: dictionary containing key values. These keys are the names of default values, and each key corresponds to a property list object (NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary).

- (NSDictionary<NSString *, id> *)dictionaryRepresentation;
Copy the code

@property (readonly, copy) NSArray<NSString *> *volatileDomainNames;

Property Description: Current volatile domain name. The domain name is a string. The content of each domain is retrieved by passing the returned domain name to the volatileDomainForName: method.

@property (readonly, copy) NSArray<NSString *> *volatileDomainNames;
Copy the code

– (NSDictionary<NSString *, id> *)volatileDomainForName:(NSString *)domainName;

Function description: Returns a dictionary for the specified volatile domain.

Parameters:

DomainName: the domain whose Key and value are required.

Return value: a dictionary of keys and values belonging to the domain. The Key in the dictionary is the name of the default value, and the value for each Key is an attribute list object (NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary).

- (NSDictionary<NSString *, id> *)volatileDomainForName:(NSString *)domainName;
Copy the code

– (void)setVolatileDomain:(NSDictionary<NSString *, id> *)domain forName:(NSString *)domainName;

Function description: Sets the dictionary for the specified volatile domain. If the existing non-volatile fields with specified name, this method cause NSInvalidArgumentException.

Parameters:

Domain: dictionary of keys and values to be assigned to a domain.

DomainName: The domain for which the dictionary is to be set.

- (void)setVolatileDomain:(NSDictionary<NSString *, id> *)domain forName:(NSString *)domainName;
Copy the code

– (void)removeVolatileDomainForName:(NSString *)domainName;

Function description: Removes the specified volatile field from the user’s default value.

Parameters:

DomainName: Volatile domain to delete.

- (void)removeVolatileDomainForName:(NSString *)domainName;
Copy the code

– (NSArray *)persistentDomainNames API_DEPRECATED(“Not recommended”, MacOS (10.0,10.9), ios(2.0,7.0), Watchos (2.0,2.0), Tvos (9.0, 9.0));

Return an array of the current persistent domain names (not recommended). The Key and value for each domain can be obtained by passing the returned domain name to the persistentDomainForName: method.

Returned value: An array of NSString objects containing domain names.

- (NSArray *)persistentDomainNames API_DEPRECATED("Not recommended", macos (10.0, 10.9), the ios (2.0, 7.0), watchos (2.0, 2.0), tvos (9.0, 9.0));Copy the code

– (nullable NSDictionary<NSString *, id> *)persistentDomainForName:(NSString *)domainName;

Function description: Returns a dictionary representation of the default value for the specified field. Calling this method is equivalent to initializing the user default object with initWithSuiteName: pass the domainName and call the dictionaryRepresentation method on it.

Parameters:

DomainName: indicates the name of the domain to be represented.

Return value: contains a dictionary of default values and keys for each default name.

- (nullable NSDictionary<NSString *, id> *)persistentDomainForName:(NSString *)domainName;
Copy the code

– (void)setPersistentDomain:(NSDictionary<NSString *, id> *)domain forName:(NSString *)domainName;

Function description: Sets the dictionary for the specified persistence domain. Calling this method is equivalent to initializing the user default value object with initWithSuiteName: passing the domainName and calling the setObject:forKey: method for each key-value pair in the domain.

Parameters:

Domain: dictionary of keys and values to be assigned to a domain.

DomainName: The name of the domain whose content is to be set.

- (void)setPersistentDomain:(NSDictionary<NSString *, id> *)domain forName:(NSString *)domainName;
Copy the code

– (void)removePersistentDomainForName:(NSString *)domainName;

Deletes the contents of the specified persistent domain from the user’s default value. Calling this method is equivalent to initializing the user default object with initWithSuiteName: passing the domainName and calling the removeObjectForKey: method for each of its keys. When change permanent domain, will release NSUserDefaultsDidChangeNotification notification.

Parameters:

DomainName: The name of the domain whose content is to be deleted.

- (void)removePersistentDomainForName:(NSString *)domainName;
Copy the code

– (BOOL)objectIsForcedForKey:(NSString *)key;

Function description: Returns a Boolean value indicating whether the specified Key is managed by an administrator. This approach assumes that Key is the preference associated with the current user and application. For managed keys, the application should disable any user interface that allows the user to modify the value of the Key.

Parameters:

Key: The key whose status is to be checked.

Returned value: YES if the specified key value is managed by the administrator; NO otherwise.

- (BOOL)objectIsForcedForKey:(NSString *)key;
Copy the code

– (BOOL)objectIsForcedForKey:(NSString *)key inDomain:(NSString *)domain;

Function description: Returns a Boolean value indicating whether the Key in the specified domain is managed by an administrator. This approach assumes that Key is the preference associated with the current user. For managed keys, the application should disable any user interface that allows the user to modify the value of the Key.

Parameters:

Key: The key whose status is to be checked.

Domain: indicates the domain of the Key.

Returned value: YES if the Key is managed by an administrator in the specified domain; NO otherwise.

- (BOOL)objectIsForcedForKey:(NSString *)key inDomain:(NSString *)domain;
Copy the code

NSUserDefaults initialization function

– (nullable instancetype)initWithSuiteName:(nullable NSString *)suitename API_AVAILABLE(macos(10.9), ios(7.0), Watchos (2.0), tvos NS_DESIGNATED_INITIALIZER (9.0));

Creates an initialized NSUserDefaults object using the default values of the specified field identifier. You can use this approach to share preferences or other data between applications when developing an application suite, or between an extender and its contained applications when developing an application extension. Parameters and registration fields are shared between all instances of NSUserDefaults.

The suiteName parameter matches the domain parameters of the corresponding CFPreferences API (except when converting between Foundation and Core Foundation constants). Such as:

id userDefaultsValue = [[[NSUserDefaults alloc] initWithSuiteName:@"someDomain"] objectForKey:@"someKey"];
id preferencesValue = CFPreferencesCopyAppValue(@"someKey"The @"someDomain"); //userDefaultsValue and preferencesValue are equalCopy the code

Parameters:

Suitename: Field identifier for the search list. If you pass nil to this argument, the system uses the default search list used by the standardUserDefaults class method. Because the suite management specifies the default value of the application group, the suite name must be different from the main Bundle identifier of the application. NSGlobalDomain is also an invalid suite name because it cannot be written by an application.

Return value: Creates an initialized NSUserDefaults object using the default values of the specified field identifier.

- (nullable instancetype)initWithSuiteName:(nullable NSString *)suitename API_AVAILABLE(macos(10.9), ios(7.0), Watchos (2.0), tvos NS_DESIGNATED_INITIALIZER (9.0));Copy the code

– (nullable id)initWithUser:(NSString *)username API_DEPRECATED(” use-init instead”) macos(10.0,10.9) ios(2.0,7.0) Watchos (2.0, 2.0), tvos (9.0, 9.0));

Creates NSUserDefaults objects that are initialized with the default values of the specified user account. This method does not put anything in the search list. It is called only if you assign your own NSUserDefaults instance instead of using a shared instance. You usually don’t use this method to initialize instances of NSUserDefaults. Applications used by superusers can use this method to update the default database for many users. The user who started the application must have proper access (read, write, or both) to the default database for the new user, or this method will return nil.

Parameters:

Username: indicates the user account name.

Return value: an initialized NSUserDefaults object with parameters and registration fields set. This method returns nil if the current user does not have access to the specified user account.

- (nullable id)initWithUser:(NSString *)username API_DEPRECATED("Use -init instead", macos (10.0, 10.9), the ios (2.0, 7.0), watchos (2.0, 2.0), tvos (9.0, 9.0));Copy the code

The domain of constants

FOUNDATION_EXPORT NSString * const NSGlobalDomain;

Constant description: a field (global) made up of default values seen by all applications.

FOUNDATION_EXPORT NSString * const NSGlobalDomain;
Copy the code

FOUNDATION_EXPORT NSString * const NSArgumentDomain;

Constant description: a field (parameter field) that resolves default values from the application’s parameters.

FOUNDATION_EXPORT NSString * const NSArgumentDomain;
Copy the code

FOUNDATION_EXPORT NSString * const NSRegistrationDomain;

Constant description: A field consisting of a set of temporary default values that can be set by the application to ensure that the search is always successful (register domain).

FOUNDATION_EXPORT NSString * const NSRegistrationDomain;
Copy the code

NSUserDefaults notice

FOUNDATION_EXPORT NSNotificationName const NSUserDefaultsSizeLimitExceededNotification API_AVAILABLE (ios (9.3), Tvos watchos (2.0), (9.0)) API_UNAVAILABLE (macOS);

Notification description: Sent when more data is stored in the user default data.

FOUNDATION_EXPORT NSNotificationName const NSUserDefaultsSizeLimitExceededNotification API_AVAILABLE (ios (9.3), Tvos watchos (2.0), (9.0)) API_UNAVAILABLE (macos);Copy the code

FOUNDATION_EXPORT NSNotificationName const NSUbiquitousUserDefaultsNoCloudAccountNotification API_AVAILABLE (ios (9.3), Tvos watchos (2.0), (9.0)) API_UNAVAILABLE (macOS);

Notification description: Sent by iCloud users when the cloud default is set but not logged in.

FOUNDATION_EXPORT NSNotificationName const NSUbiquitousUserDefaultsNoCloudAccountNotification API_AVAILABLE (ios (9.3), Tvos watchos (2.0), (9.0)) API_UNAVAILABLE (macos);Copy the code

FOUNDATION_EXPORT NSNotificationName const NSUbiquitousUserDefaultsDidChangeAccountsNotification API_AVAILABLE (ios (9.3), Tvos watchos (2.0), (9.0)) API_UNAVAILABLE (macOS);

Notification description: Sent when the user changes the primary iCloud account.

FOUNDATION_EXPORT NSNotificationName const NSUbiquitousUserDefaultsDidChangeAccountsNotification API_AVAILABLE (ios (9.3), Tvos watchos (2.0), (9.0)) API_UNAVAILABLE (macos);Copy the code

FOUNDATION_EXPORT NSNotificationName const NSUbiquitousUserDefaultsCompletedInitialSyncNotification API_AVAILABLE (ios (9.3), watchos (2.0), tvos (9.0)) API_UNAVAILABLE (macOS);

Function description: Download data is completed by default when publishing, either the first time the device connects to an iCloud account, or when the user switches their main iCloud account to send it.

FOUNDATION_EXPORT NSNotificationName const NSUbiquitousUserDefaultsCompletedInitialSyncNotification API_AVAILABLE (ios (9.3), watchos (2.0), tvos (9.0)) API_UNAVAILABLE (macos);Copy the code

FOUNDATION_EXPORT NSNotificationName const NSUserDefaultsDidChangeNotification;

Function description: Send when the user default value is changed in the current process

FOUNDATION_EXPORT NSNotificationName const NSUserDefaultsDidChangeNotification;
Copy the code

Object file

Object archiving is a serialization method. To facilitate data transfer, the archived object is serialized into a file, and then the data is restored to the object through de-archiving. Archiving techniques can be used to persist data, but in the case of large amounts of data and frequent reads and writes, it is not appropriate.

A complete archiving of an object requires that the class of the object must implement the NSCoding protocol, and that each member variable should be a primitive data type or an instance of a class that implements the NSCoding protocol.

The archive class NSKeyedArchiver and the anti-archive class NSKeyedUnArchiver are always associated with NSData. NSData encapsulates the cache class of byte data and provides methods for reading data files as follows:

+ (nullable instancetype)dataWithContentsOfFile:(NSString *)path; It is a static factory method that reads data from a file to create an NSData object.

+ (nullable instancetype)dataWithContentsOfFile:(NSString *)path options:(NSDataReadingOptions)readOptionsMask error:(NSError **)errorPtr; It is a static factory method used to create an NSData object by reading data from a file. The options parameter specifies the options for reading data, and error returns an error for reading data.

– (nullable instancetype)initWithContentsOfFile:(NSString *)path; It is the instance constructor that reads data from a file to create an NSData object.

– (nullable instancetype)initWithContentsOfFile:(NSString *)path options:(NSDataReadingOptions)readOptionsMask error:(NSError **)errorPtr; It is the instance constructor used to create an NSData object by reading data from a file. The options parameter specifies the options for reading data, and error returns the error for reading data.

– (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile; Write the NSData object into the file. Atomically whether to write the auxiliary file. If false, the data is directly written into the target file path; if true, the auxiliary file path is changed to the target file path. If the target file already exists, atomically set this parameter to true to prevent old files from being damaged due to system crash.

– (BOOL)writeToFile:(NSString *)path options:(NSDataWritingOptions)writeOptionsMask error:(NSError **)errorPtr; The NSData object is written to a file by providing write options. The options parameter specifies the option to write data, and the error parameter returns the error to write data.

The archiving process uses an NSKeyedArchiver object to archive data by writing the archiving data to an NSData object and then to an NAData object to the archive file. The process of anti-archiving is to read data from archive files to NSData objects, and then use the NSKeyedUnArchiver object to de-archive data from NSData objects.

SQLite database

D. Richard, 2000. Heep developed and published SQlite, a relational database for embedded systems, and SQlite 3 is currently the mainstream version. SQLite is open source, it is written in C language, with strong portability, high reliability, small and easy to use characteristics. SQLite runs in the same process space as the applications that use it, rather than two separate processes. SQLite provides support for the SQL-92 standard for multiple tables, indexes, transactions, views, and triggers. SQLite is a database with no data type, and fields do not have to be typed.

Although SQLite can ignore data types, programming specifications suggest that data types should be specified in the Create Table statement. Because the data type can indicate the meaning of this field, it is easy to read and understand the code.

Common data types supported by SQlite are:

  • INTEGER — The signed INTEGER type.
  • REAL — Floating point type.
  • TEXT — The character string is utF-8 or UTF-16.
  • BLOB — A binary large object type capable of storing any binary data.

There is no BOOLEAN type in SQLite and integers 0 and 1 can be used instead. SQLite also has no time and date types, which are stored in TEXT, REAL, and INTEGER types. To be compatible with other data types in the SQL-92 standard, we can convert them to the following types:

  • Convert VARCHAR, CHAR, and CLOB to TEXT types.
  • Convert FLOAT and DOUBLE to REAL.
  • Convert NUMERIC to the INTEGER or REAL type.