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;
}