使用子视图取消UIImageView的存档

我有点疯狂试图归档和取消存档的UIImageView有一些子视图是从UIImageView派生自定义视图。 以下是我所做的:

向项目添加一个类别,以允许UIImage不符合NSCoding的事实:

#import "UIImage-NSCoding.h" #define kEncodingKey @"UIImage" @implementation UIImage(NSCoding) - (id)initWithCoder:(NSCoder *)decoder { if ((self = [super init])) { NSData *data = [decoder decodeObjectForKey:kEncodingKey]; self = [self initWithData:data]; } return self; } - (void)encodeWithCoder:(NSCoder *)encoder { NSData *data = UIImagePNGRepresentation(self); [encoder encodeObject:data forKey:kEncodingKey]; } @end 

我正在归档的UIImageView是我的主视图控制器的一个属性,称为“背景”。 我像这样保存它:

 NSData *dataToSave = [NSKeyedArchiver archivedDataWithRootObject:self.background]; [dataToSave dataWithContentsOfFile:imagePath options:NSDataWritingAtomic error:nil]; 

后来我把它解除了这个样子:

 NSData *savedData = [NSData dataWithContentsOfFile:imagePath]; UIImageView *restoredImageView = [NSKeyedUnarchiver unarchiveObjectWithData:savedData]; self.background.image = restoredImageView.image; // this works - archived image is displayed 

现在我想让我的子视图(或者至less是其中的一个!)与未归档的根对象一起显示:

 NSLog(@"Subviews: %d", [restoredImageView.subviews count]); // this tells me my subviews have been archived along with the root object NSLog(@"Subview 0: %@", [restoredImageView.subviews objectAtIndex:0]); // and they exist as expected NSLog(@"Subviews: %d", [self.background.subviews count]); // at this point no subviews are present [self.background addSubview:[restoredImageView.subviews objectAtIndex:0]]; // subview is not visible on screen NSLog(@"Subviews: %d", [self.background.subviews count]); // count is one, but where is it? ORUImageView *oru = [[ORUImageView alloc] init]; // I try creating the subview myself oru = [self.background.subviews objectAtIndex:0]; [self.background addSubview:oru]; // it still doesn't show on screen [self.background bringSubviewToFront:oru]; // makes no difference NSLog(@"String: %@", oru.testString); // this correctly logs the test string I added to my custom class 

这是我已经添加到我的ORUImageView子类:

 - (void)encodeWithCoder:(NSCoder *)aCoder { [super encodeWithCoder:aCoder]; [aCoder encodeObject:self.testString forKey:@"theString"]; [aCoder encodeObject:self.image forKey:@"theImage"]; // not sure if this is needed } - (id)initWithCoder:(NSCoder *)aDecoder { self = [super initWithCoder:aDecoder]; [self setTestString:[aDecoder decodeObjectForKey:@"theString"]]; [self setImage:[aDecoder decodeObjectForKey:@"theImage"]]; // not sure if this is needed return self; } 

我已经试过这个和没有图像属性的编码。

我怀疑这个问题是与这个属性有关的,因为我明显地把子视图添加到了非存档的视图 – 这只是不可见! 我觉得图像属性没有设置,但我找不到一个方法来自己设置,我找不到任何告诉我这样做的正确方法。

[以前的答案已删除。]

编辑:嗯。 我只是试过这个:

 - (IBAction)doButton1:(id)sender { theData = [NSKeyedArchiver archivedDataWithRootObject:iv]; [iv removeFromSuperview]; iv = nil; } - (IBAction)doButton2:(id)sender { iv = [NSKeyedUnarchiver unarchiveObjectWithData:theData]; [self.view addSubview:iv]; } 

它工作 – 与一个普通的UIImageView。 所以现在我想我不明白你在做什么。 看起来UIImageView已经被存档了。 所以你一定要试图解决一些其他的问题。 但我并没有把握什么是问题。