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は、「background」と呼ばれるメインのViewControllerのプロパティです。私はそれをこのように保存します:
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
次に、サブビュー(または少なくともそのうちの1つ!)をアーカイブされていないルートオブジェクトと一緒に表示したいと思います。
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;
}
imageプロパティのエンコーディングを使用して、または使用せずにこれを試しました。
アーカイブされていないビューにサブビューが明らかに追加されているので、問題はこのプロパティに関連していると思われます-それは表示されないだけです!imageプロパティが設定されていないように感じますが、自分で設定する方法が見つからず、正しい方法を教えてくれるものも見つかりません。