1. 实体类中属性太多,如何进行快速初始化?
现有如下类TestModel,需要给字符串进行初始化:
TestModel.h
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface TestModel : NSObject
@property (nonatomic, copy) NSString *property1;
@property (nonatomic, copy) NSString *property2;
@property (nonatomic, copy) NSString *property3;
@end
NS_ASSUME_NONNULL_END
- 我们一般都会在
TestModel.m中逐个初始化属性
#import "TestModel.h"
@implementation TestModel
- (instancetype)init{
self = [super init];
if (self) {
self.property1 = @"";
self.property2 = @"";
self.property3 = @"";
}
return self;
}
@end
2. 实现快速初始化的方法
使用Runtime初始化实体类:
- 为
NSObject新建一个分类,比如:NSObject+Assisant.h,代码如下:
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
@interface NSObject (Assistant)
@end
#import "NSObject+Assistant.h"
@implementation NSObject (Assistant)
- (void)makePropetiesValueEmptyString {
unsigned int methodCount = 0;
Ivar *ivars = class_copyIvarList([self class], &methodCount);
for (unsigned int i = 0; i < methodCount; i ++) {
Ivar ivar = ivars[i];
// 获取属性名称
NSString *propertyName = [NSString stringWithUTF8String:ivar_getName(ivar)];
// 获取属性类型
NSString *propertyType = [NSString stringWithUTF8String:ivar_getTypeEncoding(ivar)];
if ([propertyType containsString:@"String"]) {
// 初始化类型为NSString的属性
[self setValue:@"" forKey:propertyName];
}
}
free(ivars);
}
@end
- 在
TestModel.m中导入NSObject+Assisant.h,并在init初始化方法中调用[self makePropetiesValueEmptyString]方法即可。
#import "TestModel.h"
#import "NSObject+Assistant.h"
@implementation TestModel
- (instancetype)init{
self = [super init];
if (self) {
[self makePropetiesValueEmptyString];
}
return self;
}
@end
- 这样做以后,
[TestModel new]的时候就会初始化全部NSString类型的属性了。