This section only deals with archiving of custom classes

Teacher.h:

@interface Teacher: NSObject <NSCoding,NSSecureCoding> @property (nonatomic, copy) NSString *name; @property (nonatomic, assign) int age; @endCopy the code

Teacher.m:

// Archive - (void)encodeWithCoder:(nonnull NSCoder *)coder {[coder encodeInt:self. Age forKey:@"age"]; [coder encodeObject:self.name forKey:@"name"]; } // (nullable instancetype)initWithCoder:(nonnull NSCoder *)coder {if(self = [super init]){self.age = [coder decodeIntForKey:@"age"]; self.name = [coder decodeObjectForKey:@"name"]; } return self; } // Necessary + (BOOL)supportsSecureCoding{return YES; }Copy the code

ViewController.m:

- (IBAction)save:(id)sender {// get TMP NSString *tmpPath = NSTemporaryDirectory(); / / get the file path nsstrings * filePath = [tmpPath stringByAppendingPathComponent: @ "the teacher. The arc"]. Teacher *t = [[Teacher alloc] init]; Teacher *t = [Teacher alloc] init]; T.name = @" ahhhhh "; t.age = 29; / / archive NSData * data = [NSKeyedArchiver archivedDataWithRootObject: t requiringSecureCoding: NO error: nil]; [data writeToFile:filePath atomically:YES]; } - (IBAction)read:(id)sender {// get TMP NSString *tmpPath = NSTemporaryDirectory(); / / get the file path nsstrings * filePath = [tmpPath stringByAppendingPathComponent: @ "the teacher. The arc"]. / / suffix into line with common type gear NSData * / / solution data = [NSData dataWithContentsOfFile: filePath]; Teacher *t = [NSKeyedUnarchiver unarchivedObjectOfClass:[Teacher class] fromData:data error:nil]; NSLog(@"%d",t.age); }Copy the code

If you need to archive an array containing a custom object, note the change:

Archive:

NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self.contacts requiringSecureCoding:NO error:nil]; Contacts is the object of the class, contacts is an array of contacts so you can archive it as an array

Solution file:

self.contacts = (NSMutableArray *)[NSKeyedUnarchiver unarchivedArrayOfObjectsOfClass:[Contact class] fromData:data error:nil];

Note to use:

+ (nullable NSArray *)unarchivedArrayOfObjectsOfClass:(Class)cls fromData:(NSData *)data error:(NSError **)error API_AVAILABLE(MacOS (11.0), ios(14.0), Watchos (7.0), TVOs (14.0)) NS_REFINED_FOR_SWIFT;

  • Objects is a plural

  • If you need to force the type, force it