“This is the third day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021.”

The cause of

There will be times during development when you need to save some data locally, but the size of the database is too heavy, so saving as a file becomes a more appropriate option.

When storing files, the normal situation is to convert the object to JSON data in the form of a string and save it locally. When retrieving the json data, you also need to convert the object to an object for operation.

IOS provides a filing in the operation, the object can be saved to a local file, obtain again is also read in the file data is the object directly, is very convenient, but there is a problem, and then save the need to specify the properties of each to the archive, if there is too much attribute object so directly to the scalp, Is there an easier way to do it?

Of course I do, and that’s why I have to mention runtime, and by now some of you already know what to do,

Here is the code to speak 👇🏻↓

Without further ado, let’s get right to the code

The first, of course, is the import header file

#import <objc/runtime.h>
Copy the code

Copy the following code into the.m of the model file you want to save

// archive - (void)encodeWithCoder:(NSCoder *)aCoder{unsigned int count; Ivar *ivar = class_copyIvarList([self class], &count); for (int i=0; i<count; i++) { Ivar iva = ivar[i]; const char *name = ivar_getName(iva); NSString *strName = [NSString stringWithUTF8String:name]; // Use KVC value id value = [self valueForKey:strName]; [aCoder encodeObject:value forKey:strName]; } free(ivar); } -(instancetype)initWithCoder:(NSCoder *)aDecoder{if (self = [super init]) {unsigned int count = 0; Ivar *ivar = class_copyIvarList([self class], &count); for (int i = 0; i < count; i++) { Ivar iva = ivar[i]; const char *name = ivar_getName(iva); NSString *strName = [NSString stringWithUTF8String:name]; / / value solution file id value = [aDecoder decodeObjectForKey: strName); // Use KVC to assign attribute [self setValue:value forKey:strName]; } free(ivar); } return self; }Copy the code

Get file address

/ / get sandbox Document path filePath = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory NSUserDomainMask, YES) firstObject]; FilePath = NSTemporaryDirectory(); / / get sandbox Cache path filePath = [NSSearchPathForDirectoriesInDomains (NSCachesDirectory NSUserDomainMask, YES) firstObject]; / / file path nsstrings * uniquePath = [filePath stringByAppendingPathComponent: your file name].Copy the code

You want to save the normal location of the file can be

[NSKeyedArchiver archiveRootObject: the model you want to save toFile: the path to save the file];Copy the code

Normal unfile (with return value)

= [NSKeyedUnarchiver unarchiveObjectWithFile: where you saved the file];Copy the code

Delete files from sandbox

-(void)deleteFileWithFileName:(NSString *)fileName filePath:(NSString *)filePath {// create a file management object NSFileManager* fileManager=[NSFileManager defaultManager]; If (! FilePath) {/ / if the file directory set free, delete the Cache files in the directory by default filePath = [NSSearchPathForDirectoriesInDomains (NSCachesDirectory, NSUserDomainMask, YES) firstObject]; } / / stitching fileName nsstrings * uniquePath = [filePath stringByAppendingPathComponent: [nsstrings stringWithFormat: @ "% @", fileName]]. / / file exists BOOL blHave = [[NSFileManager defaultManager] fileExistsAtPath: uniquePath]; If (! BlHave) {NSLog(@" file does not exist "); return ; } else {/ / if the file is deleted BOOL blDele = [fileManager removeItemAtPath: uniquePath error: nil]; If (blDele) {NSLog(@" delete successfully "); }else {NSLog(@" delete failed "); }}}Copy the code