简单使用runtime
将具有相同属性两个类赋值,目前只是简单考虑某些常用属性类型,包含如下:
NSString
、NSInteger
、NSNumber
、BOOL
、NSDate
、int
、double
、long
、NS_ENUM(NSUInteger, ENUM_NAME)
代码只是拿到属性,找到对应值,直接赋值,同名,不同类型还没考虑,应该还有没考虑的情况
例子:
#import "NSObject+WLClassTransform.h"
AClass *aClass = [[AClass alloc] init];
aClass.xx = @"xx";
aClass.yy = @"yy";
BClass *bClass = [aClass transformToClass:BClass.class];
NSLog(@"bClass.xx=[%@]", bClass.xx); //输出 xx
NSObject+WLClassTransform
源码:
- NSObject+WLClassTransform.h
//
// NSObject+WLClassTransform.h
// libWeever
//
// Created by LuYiHuang on 2019/3/24.
// Copyright © 2019 Weever. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface NSObject (WLClassTransform)
/**
将当前类的属性值,全赋值给toClass对应存在的属性
@param toClass 需要赋值的Class
@return toClass的实例对象
*/
- (Class)transformToClass:(Class)toClass;
@end
NS_ASSUME_NONNULL_END
- NSObject+WLClassTransform.m
//
// NSObject+WLClassTransform.m
// libWeever
//
// Created by LuYiHuang on 2019/3/24.
// Copyright © 2019 Weever. All rights reserved.
//
#import "NSObject+WLClassTransform.h"
#import "objc/runtime.h"
@implementation NSObject (WLClassTransform)
- (Class)transformToClass:(Class)toClass {
id model = [[toClass alloc] init];
unsigned int outCount;
objc_property_t *properties = class_copyPropertyList(toClass, &outCount);
for ( int i = 0; i < outCount; i++) {
objc_property_t property = properties[i];
const char *charName = property_getName(property);
NSString *propertyName = [NSString stringWithUTF8String:charName];
id propertyValue = [self propertyValueByName:propertyName]; //循环获取,效率??
//NSLog(@"%s %@=%@", __func__, propertyName, propertyValue);
[model setValue:propertyValue forKey:propertyName];
}
free(properties);
return model;
}
/**
获取当前类的存在该属性名对应的属性值
@param name 查找的属性名
@return 查找的属性名对应的属性值
*/
- (id)propertyValueByName:(NSString *)name {
id propertyValue = nil;
unsigned int outCount;
objc_property_t *properties = class_copyPropertyList(self.class, &outCount);
for ( int i = 0; i < outCount; i++) {
objc_property_t property = properties[i];
const char *charName = property_getName(property);
NSString *propertyName = [NSString stringWithUTF8String:charName];
//查找的属性名,是当前类存在的属性
if ([propertyName isEqualToString:name]) {
propertyValue = [self valueForKey:(NSString *)propertyName];
//NSLog(@"%s %@=%@", __func__, propertyName, propertyValue);
break;
}
}
free(properties);
return propertyValue;
}
@end