How to serialize a UIView?

2019-01-14 18:32发布

问题:

Is it possible to serialize a UIView object? If yes how can I do that?

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

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

  return view;
}