How to serialize a UIView?

前端 未结 1 1373
既然无缘
既然无缘 2020-12-06 02:23

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

相关标签:
1条回答
  • 2020-12-06 03:28

    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;
    }
    
    0 讨论(0)
提交回复
热议问题