归档 UIView 对象,该对象将 UIImageView 和 UIImage 作为它在 Objective-C 中的子视图 [英] Archiving UIView Object which holds UIImageView and UIImage as a subview of it in Objective-C

查看:25
本文介绍了归档 UIView 对象,该对象将 UIImageView 和 UIImage 作为它在 Objective-C 中的子视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何归档 UIImagView 和 UIImage 作为它的子视图的 UIVIew.我是这样尝试的,

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];

但是程序崩溃了,说 [UIImage encodeWithCoder:]:Unrecognized selector sent to instance.

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

我该如何解决这个问题?我如何在 Objective-C 中归档和取消归档这个 UIView 对象?

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

谢谢你.

推荐答案

UIView 实现了 NSCoding 协议,因此您可以使用 encodeWithCoder: 来获得序列化的表示,并使用 initWithCoder: 从这样的表示中重新构建 UIView.您可以在 Cocoa 序列化编程指南.

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;
}

请注意,如果我实际上使用的是 UIView 的自定义子类,则需要覆盖 encodeWithCoder: 和 initWithCoder: 以添加自己的属性

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

这篇关于归档 UIView 对象,该对象将 UIImageView 和 UIImage 作为它在 Objective-C 中的子视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆