是否可以序列化UIView
个对象?如果是,我该怎么做?
答案 0 :(得分:11)
UIView
实施NSCoding
协议,因此您可以使用encodeWithCoder:
来获取序列化表示,并使用initWithCoder:
从此类表示中重新构建UIView
。您可以在Serializations Programming Guide for Cocoa中找到很多详细信息。
以下是如何操作的简单示例:
- (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;
}