Archiving UIView Object which holds UIImageView and UIImage as a subview of it in Objective-C

亡梦爱人 提交于 2019-12-11 12:42:41

问题


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



来源:https://stackoverflow.com/questions/8722067/archiving-uiview-object-which-holds-uiimageview-and-uiimage-as-a-subview-of-it-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!