I. Use the NSKeyedArchiver class to operate on Object Access
Features: This class can store objects in the form of key-value pairs and extract them from the file using keys. It is similar to SharedPreference in android and Its serialized data is encrypted.
1. Save data to a file:
NSString * rootDir = NSHomeDirectory (); NSString * path = [rootDir stringByAppendingPathComponent: @ "test.txt"]; NSMutableData * data = [NSMutable data]; NSKeyedArchiver * archiver = [[NSKeyedArchiver alloc] initForWritingMutableData: data]; NSArray * array = @ [@ "one", @ "two"]; [archiver encodeInt: 100 forKey: @ "age"]; // equivalent to putInteger (key, value) of SharedPreference; [archiver encodeObject: array forKey: @ "names"]; // [archiver finishEncoding]; // if this method is called, data is stored in data [archiver release]; if ([data writeToFile: path atomically: YES]) {NSLog (@ "Object saved to file succeeded ");}
2. extract data from the file
NSData * data = [NSData failed: path]; NSKeyedArchiver * unarchiver = [[NSKeyedArchiver alloc] initForReadingWithData: data]; int age = [unarchiver decodeIntForKey: @ "age"] // obtain the value NSArray * array = [unarchiver decodeObjectForKey: @ "names"]; [archiver release];
Ii. Use the NSUserDefaults class to access objects
Features: This class stores objects in the system's fixed plist cache file in the form of key-value pairs, and extracts the objects from the file using the key, which is the same as SharedPreference in android Application scenarios, used to cache small and simple cache data
// 1. store Data NSArray * array = @ [@ "abc", @ "d"]; NSUserDefaults * userDefault = [NSUserDefaults standardUserDefaults]; [userDefault setInteger: 123 forKey: @ "number"]; [userDefault setObject: array forKey: @ "array"]; [userDefault synchronize]; // save to file // 2. NSInteger number = [userDefault integerForKey: @ "number"]; NSArray * array = [userDefault objectForKey: @ "array"];