Archiving and unarchiving of iOS objects-Runtime implementation

Preface

What is serialization in the previous article ? What is the role of serialization? How to achieve serialization in iOS? In this, we have implemented the serialization operation of the object in common methods, that is, archiving and unarchiving.

NSCodingArchiving and unarchiving of iOS objects that follow the protocol is a data persistence method we often use. But if there are too many attributes of the object, we still implement the method encodeObject:forKey:and decodeObjectForKey:method for each attribute. The amount of code written in this way will be too cumbersome. Today, I will teach you a simple method to implement it.

1. Create NSCodinga Person object that follows the protocol


#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface Person : NSObject<NSCoding>

@property (copy,   nonatomic) NSString *name;
@property (copy,   nonatomic) NSString *sex;
@property (assign, nonatomic) NSInteger age;
@property (assign, nonatomic) NSInteger height;

@end

NS_ASSUME_NONNULL_END

2.Person.m code to achieve archiving and unarchiving

  • runtime archive
- (void)encodeWithCoder:(NSCoder *)coder {
		//告诉系统归档的属性是哪些
	unsigned int count = 0;//表示对象的属性个数
	Ivar *ivars = class_copyIvarList([Person class], &count);
	for (int i = 0; i < count; i++) {
			//拿到Ivar
		Ivar ivar = ivars[i];
		const char *name = ivar_getName(ivar);//获取到属性的C字符串名称
		NSString *key = [NSString stringWithUTF8String:name];//转成对应的OC名称
		//归档 -- 利用KVC
		[coder encodeObject:[self valueForKey:key] forKey:key];
	}
	free(ivars);
		//在OC中使用了Copy、Creat、New类型的函数,需要释放指针!!(注:ARC管不了C函数)
}
  • runtime unarchive
- (instancetype)initWithCoder:(NSCoder *)coder {
	self = [super init];
	if (self) {
			//解档
		unsigned int count = 0;
		Ivar *ivars = class_copyIvarList([Person class], &count);
		for (int i = 0; i<count; i++) {
				//拿到Ivar
			Ivar ivar = ivars[i];
			const char *name = ivar_getName(ivar);
			NSString *key = [NSString stringWithUTF8String:name];
				//解档
			id value = [coder decodeObjectForKey:key];
				// 利用KVC赋值
			[self setValue:value forKey:key];
		}
		free(ivars);
	}
	return self;
}


The advantage of using runtime is self-evident, no matter how many attributes the object has, it can be done through this for loop, which is very powerful and very convenient. I wonder if you learned it?

Guess you like

Origin blog.csdn.net/zjpjay/article/details/86552305