Archiving UIView Object which holds UIImageView an

2019-08-04 06:43发布

问题:

How do i Archive UIVIew which has UIImagView and UIImage as subview of it. I tried to do it in this way,

data= [NSKeyedArchiver archivedDataWithRootObject: viewObject];
new_ViewObject= [NSKeyedUnarchiver unarchiveObjectWithData: data];

But the program crashes saying that [UIImage encodeWithCoder:]:Unrecognized selector sent to instance.

How do i solve this problem? How can i archive and unarchive this UIView Object in Objective-C?

Thank U.

回答1:

UIView implements the NSCoding protocol, so you can use encodeWithCoder: to get a serialized representation, and initWithCoder: to reconstitute a UIView from such a representation. You can find a lot of details in the Serializations Programming Guide for Cocoa.

Here is quick example of how to do it:

- (NSData *)dataForView:(UIView *)view {
  NSMutableData *data = [NSMutableData data];
  NSKeyedArchiver  *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
  [archiver encodeObject:view forKey:@"view"];
  [archiver finishEncoding];
  [archiver release];

  return (id)data;
}

- (UIView *)viewForData:(NSData *)data {
  NSKeyedArchiver  *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];

   UIView *view = [unarchiver decodeObjectForKey:@"view"];
  [unarchiver finishDecoding];
  [unarchiver release];

  return view;
}

Note that if I am actually using a custom subclass of UIView, you'll need to override encodeWithCoder: and initWithCoder: to add your own properties