Is it possible to serialize a UIView object? If yes how can I do that?
            Asked
            
        
        
            Active
            
        
            Viewed 6,894 times
        
    8
            
            
        
        Gilles 'SO- stop being evil'
        
- 104,111
 - 38
 - 209
 - 254
 
1 Answers
12
            
            
        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;
}
        Gilles 'SO- stop being evil'
        
- 104,111
 - 38
 - 209
 - 254
 
        Louis Gerbarg
        
- 43,356
 - 8
 - 80
 - 90
 
- 
                    3Note that if you are actually using a custom subclass of UIView, you'll need to override encodeWithCoder: and initWithCoder: to add your own properties. – Donovan Voss Jul 24 '09 at 02:45
 - 
                    4i think you mean "NSKeyedUnarchiver *unarchiver" and not "NSKeyedArchiver *unarchiver". whilst they are both descended from NSCoding, they aren't the same thing. it still "works" but nanny XCode nags, as she should, in other less trivial instances. – unsynchronized Oct 20 '11 at 05:58
 - 
                    UIImageView conforms to NSCoding. I am not sure when the switch happened but my iOS app (iOS 5) has no issue with archiving a UIImageView. Probably iOS 5. – chadbag Oct 10 '12 at 20:13