I have a class representing a structure.
This class with the name Objecthas the following properties
@property (nonatomic, strong) NSArray *children;
@property (nonatomic, assign) NSInteger type;
@property (nonatomic, strong) NSString *name;
@property (nonatomic, weak) id parent;
childrenis an array of other Objects. parent- weak reference to the parent object.
I am trying to copy and paste a branch of this structure. If the root object is selected, it is obvious that it parentis zero. If the object is not a root, it has a parent.
To do this, view objects Objectmust conform to NSCopyingand NSCoding.
This is my implementation of these protocols in this class.
-(id) copyWithZone: (NSZone *) zone
{
Object *obj = [[Object allocWithZone:zone] init];
if (obj) {
[obj setChildren:_children];
[obj setType:_type];
[obj setName:_name];
[obj setParent:_parent];
}
return obj;
}
- (void)encodeWithCoder:(NSCoder *)coder {
[coder encodeObject:@(self.type) forKey:@"type"];
[coder encodeObject:self.name forKey:@"name"];
NSData *childrenData = [NSKeyedArchiver archivedDataWithRootObject:self.children];
[coder encodeObject:childrenData forKey:@"children"];
[coder encodeConditionalObject:self.parent forKey:@"parent"];
}
- (id)initWithCoder:(NSCoder *)coder {
self = [super init];
if (self) {
_type = [[coder decodeObjectForKey:@"type"] integerValue];
_name = [coder decodeObjectForKey:@"name"];
_parent = [coder decodeObjectForKey:@"parent"];
NSData *childrenData = [coder decodeObjectForKey:@"children"];
_children = [NSKeyedUnarchiver unarchiveObjectWithData:childrenData];
_parent = nil;
}
return self;
}
, , self.parent initWithCoder: encodeWithCoder:, - = nil.
, . - . , Object.
ObjectA > ObjectB > ObjectC
encoderWithCoder: ObjectA, ObjectB ObjectC, ObjectB, , ObjectA, , , . .
/ ?
, , . , , .
. , //*, , _parent - nil initWithCoder: , parent