c_cpp NSManagedObject类别,用于在另一个上下文中创建深层副本
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp NSManagedObject类别,用于在另一个上下文中创建深层副本相关的知识,希望对你有一定的参考价值。
//
// Copyright © 2013 Yuri Kotov
//
#import "NSManagedObject+ADVCopying.h"
@implementation NSManagedObject (ADVCopying)
- (instancetype) adv_copyInContext:(NSManagedObjectContext *)context
{
return [self adv_copyInContext:context withCache:[NSMutableDictionary new]];
}
- (instancetype) adv_copyInContext:(NSManagedObjectContext *)context withCache:(NSMutableDictionary *)cache
{
NSManagedObject *copy;
copy = cache[self.objectID];
if (copy) return copy;
copy = [[NSManagedObject alloc] initWithEntity:self.entity insertIntoManagedObjectContext:context];
cache[self.objectID] = copy;
// Attributes
NSArray *keys = [[self.entity attributesByName] allKeys];
NSDictionary *attributes = [self dictionaryWithValuesForKeys:keys];
[copy setValuesForKeysWithDictionary:attributes];
// Relationships
NSDictionary *relationships = [self.entity relationshipsByName];
if (0 == relationships.count) return copy;
id enumerator = ^(NSString *key, NSRelationshipDescription *relationship, BOOL *stop)
{
if ([relationship isToMany])
{
// TODO: Add support for ordered relationships
NSMutableSet *sourceSet = [self mutableSetValueForKey:key];
NSMutableSet *targetSet = [copy mutableSetValueForKey:key];
for (NSManagedObject *value in sourceSet)
{
[targetSet addObject:[value adv_copyInContext:context withCache:cache]];
}
}
else
{
NSManagedObject *value = [self valueForKey:key];
value = [value adv_copyInContext:context withCache:cache];
[copy setValue:value forKey:key];
}
};
[relationships enumerateKeysAndObjectsUsingBlock:enumerator];
return copy;
}
@end
//
// Copyright © 2013 Yuri Kotov
//
#import <CoreData/CoreData.h>
@interface NSManagedObject (ADVCopying)
- (instancetype) adv_copyInContext:(NSManagedObjectContext *)context;
@end
以上是关于c_cpp NSManagedObject类别,用于在另一个上下文中创建深层副本的主要内容,如果未能解决你的问题,请参考以下文章
NSManagedObject 和类别/子类
类别中的自定义 NSManagedObject 设置器
Objective -C 类问题
c_cpp 用于跟踪完成的RACCommand类别
序列化 NSManagedObject
NSmanagedobject 的子类的子类