使用归档程序复制对象

作者:追风剑情 发布于:2019-3-8 16:39 分类:Objective-C

利用归档程序进行深度复制,对于不支持NSCopying协议的对象可用这项技术。

示例

  1. #import <Foundation/Foundation.h>
  2.  
  3. int main(int argc, const char * argv[]) {
  4. @autoreleasepool {
  5. NSData *data;
  6. NSMutableArray *dataArray = [NSMutableArray arrayWithObjects:
  7. [NSMutableString stringWithString: @"one"],
  8. [NSMutableString stringWithString: @"two"],
  9. [NSMutableString stringWithString: @"three"],
  10. nil
  11. ];
  12. NSMutableArray *dataArray2;
  13. NSMutableString *mStr;
  14. // 使用归档器进行深层复制
  15. //data = [NSKeyedArchiver archivedDataWithRootObject: dataArray];
  16. //dataArray2 = [NSKeyedUnarchiver unarchiveObjectWithData: data];
  17. // 合并成一句代码
  18. dataArray2 = [NSKeyedUnarchiver unarchiveObjectWithData:
  19. [NSKeyedArchiver archivedDataWithRootObject: dataArray]];
  20. mStr = dataArray2[0];
  21. [mStr appendString: @"ONE"];
  22. NSLog(@"dataArray: ");
  23. for (NSString *elem in dataArray)
  24. NSLog(@"%@", elem);
  25. NSLog(@"dataArray2: ");
  26. for (NSString *elem in dataArray2)
  27. NSLog(@"%@", elem);
  28. }
  29. return 0;
  30. }
运行测试
111.png

标签: Objective-C

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号