views:

649

answers:

1

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

Thanks

+3  A: 

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;
}
Louis Gerbarg
Note that if you are actually using a custom subclass of UIView, you'll need to override encodeWithCoder: and initWithCoder: to add your own properties.
Dustin Voss