如何序列化UIView?

时间:2009-07-23 01:00:31

标签: iphone objective-c serialization uiview

是否可以序列化UIView个对象?如果是,我该怎么做?

1 个答案:

答案 0 :(得分:11)

UIView实施NSCoding协议,因此您可以使用encodeWithCoder:来获取序列化表示,并使用initWithCoder:从此类表示中重新构建UIView 。您可以在Serializations Programming Guide for Cocoa中找到很多详细信息。

以下是如何操作的简单示例:

- (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 {
  NSKeyedUnarchiver  *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];

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

  return view;
}