Ios archive learning notes
Archive refers to the process of saving one or more objects in a certain format for future restoration of these objects.
Archiving using xml Attribute lists
If you archive NSString, NSDictionary, NSArray, NSData, and NSNumber objects, you can use the writeToFile: atomically: method implemented in the class to write data to the file.
Use the dictionaryWithContentsOfFile or arrayWithContentsOfFile, dataWithContentsOfFile, and stringWithContentsOfFile methods to read back data.
Use NSKeyedArchiver for archiving
Store various types of objects in files, not just strings, arrays, and dictionaries. There is a more flexible method, that is, the NSKeyedArchiver class creates a file with a key.
In a file with a key, each archive field has a name. When you archive an object, provide it with a name, that is, a key. This key is used to retrieve objects from an archive.
Encoding and decoding methods
Custom class objects cannot be archived directly. Because the system does not know how to archive.
Follow Protocol. Add the encodeWithCoder method and the initWithCoder Method to the class to implement the archive specification.
The encodeWithCoder method informs the archive program how to archive. The initWithCoder method tells you how to decode.
The basic oc class described above can be encoded using encodeObject: forKey and decodeObject: forKey for decoding. The following method is used for basic C types:
Encoding Method |
Decoding Method |
EncodeBool: forKey: |
DecodeBool: forKey: |
EncodeInt: forKey: |
DecodeInt: forKey: |
EncodeInt32: forKey: |
DecodeInt32: forKey: |
EncodeInt64: forKey: |
DecodeInt64: forKey: |
EncodeFloat: forKey: |
DecodeFloat: forKey: |
EncodeDouble: forKey: |
DecodeDouble: forKey: |
Here is an example:
- (void)encodeWithCoder:(NSCoder *)coder{ [coder encodeObject:@"tongxue" forKey:@"name"]; [coder encodeInt:13 forKey:@"age"];}- (id)initWithCoder:(NSCoder *)aDecoder{ NSString * name = [aDecoder decodeObjectForKey:@"name"]; int age = [aDecoder decodeIntForKey:@"age"]; return self;}