iOS 类之间 model传递方案

序言:

当A传值给B时,如:B.model = A.model,如果model在B使用的过程中发生了变化,那么A里面的model的值也会变化,究其根本是两个指针指向同一个对象。解决方案有两种。

正文

方案1:

A copy 一份新的model 赋值给B.model。思路:model类实现NSCopy协议里的方法,在方法里利用runtime快速给新对象的各属性赋值。(一个自定义类若不实现协议里的方法,直接调用copy,会崩溃)

#import 
#import 

@interface DataModel : NSObject

@property (nonatomic,copy) NSString *title;
@property (nonatomic,assign) NSInteger age;

@end
#import "DataModel.h"

@implementation DataModel

- (id)copyWithZone:(NSZone *)zone{
    
    DataModel *model = [[self class] allocWithZone:zone];
    
    unsigned int count;
    Ivar *ivar = class_copyIvarList([self class], &count);
    for (int i = 0; i < count; i ++) {
        Ivar iv = ivar[I];
        const char *name = ivar_getName(iv);
        NSString *key = [NSString stringWithUTF8String:name];
        [model setValue:[self valueForKey:key] forKey:key];
    }
    
    return model;
}

使用:

    Dog *dg = [[Dog alloc] init];
    DataModel *md = [self.model copy];
    dg.model = md;
方案2:

使用归档解档,思路:model类实现NSCoding协议里的俩方法,在方法里利用runtime快速给新对象的各属性赋值。

#import 
#import 

@interface DataModel : NSObject

@property (nonatomic,copy) NSString *title;
@property (nonatomic,assign) NSInteger age;

@end
- (void)encodeWithCoder:(NSCoder *)coder
{
    unsigned int count;
    Ivar *ivar = class_copyIvarList([self class], &count);
    for (int i = 0; i < count; i ++) {
        Ivar va = ivar[I];
        char const *name = ivar_getName(va);
        NSString *key = [NSString stringWithUTF8String:name];
        
        NSString *value = [self valueForKey:key];
        
        [coder encodeObject:value forKey:key];
    }
    
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder{
    
    self = [super init];
    if (self) {
        unsigned int count;
        Ivar *allKey = class_copyIvarList([self class], &count);
        for (int i = 0; i < count; i ++) {
            Ivar iv = allKey[I];
            char const *name = ivar_getName(iv);
            NSString *key = [NSString stringWithUTF8String:name];
            id value = [aDecoder decodeObjectForKey:key];
            [self setValue:value forKey:key];
        }
    }
    return self;
}

使用:

    //写入
    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/hehe.data"];
    BOOL writeFile = [NSKeyedArchiver archiveRootObject:self.model toFile:path];
    if (!writeFile) {
        NSLog(@"文件写入失败");
    }
    //取出
    Dog *dg = [[Dog alloc] init];
    DataModel *md = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    dg.model = md;

结束语:

两个黄蝴蝶,双双飞上天。
不知为什么,一个忽飞还。
剩下那一个,孤单又可怜。
也无心上天,天上太孤单。
--《两只蝴蝶》胡适


iOS 类之间 model传递方案_第1张图片
陶然亭公园.png

你可能感兴趣的:(iOS 类之间 model传递方案)