IOS file operations and custom object archiving (serialization) and anti-archiving (deserialization)
IOS allows you to create, read, write, move, and delete files.
1. File Creation:
// Set the location of the file stored in the text box NSString * strFilePath = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex: 0]; // specify the file name NSString * fileName = [strFilePath stringByAppendingPathComponent: @ "test.txt"]; // File Manager
NSFileManager *fmaneger=[NSFileManager defaultManager]; if ([fmaneger fileExistsAtPath:[self getFilePath]]) { self.txtField.text=[NSString stringWithContentsOfFile:[self getFilePath] encoding:NSUTF8StringEncoding error:nil]; }
2. File writing
// Write the text content into self.txt Field. text writeToFile: fileName atomically: YES encoding: NSUTF8StringEncoding error: nil]; NSLog (@ "saved successfully ");
3. File Reading
NSFileManager *fmanager=[NSFileManager defaultManager]; if ([fmanager fileExistsAtPath:fileName]) { [fmanager createFileAtPath:fileName contents:nil attributes:nil]; }
4. File Movement
// Move the file // target folder NSString * destPath = NSTemporaryDirectory (); // target file path NSString * destFilePath = [destPath stringByAppendingPathComponent: @ "test.txt"]; BOOL result = [fmanager moveItemAtPath: filePath toPath: destFilePath error: nil]; if (result) {NSLog (@ "moved successfully");} else {NSLog (@ "failed to move! ");}
5. delete an object
NSFileManager *fmanager=[NSFileManager defaultManager]; [fmanager removeItemAtPath:filePath error:nil];
File Operation summary:
You must specify the file path for file operations.
NSSearchPathForDirectoriesInDomains
To find the file path.
After obtaining or specifying the file path, you must have an NSFileManager object for file creation and movement operations.
There are many file writing methods, including NSString, NSDictionary, NSArray, and its subclass. You can call the Writing Method to write data to the file.
The following shows how to write and read files of custom class objects (archive or archive ):
Steps:
1. Define a Person class and enable the Person class to implement the NSCoding protocol (this Protocol is required to implement archiving)
/// Person. h // file operation // Created by lifewahaha on 15/5/15. // Copyright (c) 2015 lifewahaha. All rights reserved. // # import
@ Interface Person: NSObject
@ Property (strong, nonatomic) NSString * name; @ property (nonatomic) int age;-initWithName :( NSString *) name; @ end
2. Two Protocol methods must be implemented in the implementation file of the Person class.
-(void)encodeWithCoder:(NSCoder *)aCoder
-(id)initWithCoder:(NSCoder *)aDecoder
/// Person. m // file operation // Created by lifewahaha on 15/5/15. // Copyright (c) 2015 lifewahaha. all rights reserved. // # import "Person. h "@ implementation Person-(id) initWithName :( NSString *) name {if ([super init]) {self. name = name;} return self;} # pragma-mark method for converting an object to NSData-(void) encodeWithCoder :( NSCoder *) acder {[acder encodeObject: self. name forKey: @ "name"]; [ecoder encodeInt: self. age forKey: @ "age"];}-(id) initWithCoder :( NSCoder *) aDecoder {if ([self init]) {// self. name = [aDecoder decodeObjectForKey: @ "name"]; self. age = [aDecoder decodeIntForKey: @ "age"];} return self ;}@ end
3. Import the Person Class header file in ViewController, and then implement the following methods in ViewDidLoad:
-(Void) viewDidLoad {[super viewDidLoad]; Person * p = [[Person alloc] init]; p. name = @ "a"; p. age = 12; // ************* archive and serialize ***************** // 1. create a variable binary stream NSMutableData * data = [[NSMutableData alloc] init]; // 2. create an archive object (which can convert custom classes to binary streams) NSKeyedArchiver * archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData: data]; // 3. use this archive object to convert the custom class object into a binary stream [archiver encodeObject: p forKey: @ "person"]; // 4. archive the object [archiver finishEncoding]; // write data to the file [data writeToFile: [self getObjFilePath] atomically: YES]; NSLog (@ "% @", data ); ****************** NSMutableData * mData = [NSMutableData dataWithContentsOfFile: [self getObjFilePath]; // 2. create an archive object to decompress the binary data into the oc data in the row NSKeyedUnarchiver * unArchiver = [[initalloc] initForReadingWithData: mData]; Person * p2 = [unArchiver decodeObjectForKey: @ "person"]; NSLog (@ "Name: % @", p2.name );
}