gpt4 book ai didi

ios - 如何复制自定义对象?

转载 作者:行者123 更新时间:2023-11-28 21:05:28 25 4
gpt4 key购买 nike

我需要复制一个自定义对象。是否可以不手动复制每个字段?

 var test1  = CustomerInfo()
var test2 = CustomerInfo()
test1 = test2
test1.customername = "First"
test2.customername = "Second"

print(test1.customername) /* Getting "Second" , actually i want to get "First" */

请建议我任何可能的解决方案?

最佳答案

 func copy(with zone: NSZone? = nil) -> Any {
let copy = CustomerInfo(myIvar1: Type, myIvar2: type)//constructor or your class
return copy
}
var test1 = CustomerInfo()
var test2 = test1.copy as! CustomerInfo

你好简,

  1. 需要确认NSCopying协议(protocol)并实现上面的copyWithZone:方法。

  2. 在 copyWithZone 方法中,只需使用您的构造函数方法创建对象并返回该对象。

  3. 每当您想要复制时,只需在令人兴奋的对象上调用复制即可。如需完整引用,请关注苹果官方 https://developer.apple.com/library/content/documentation/General/Conceptual/DevPedia-CocoaCore/ObjectCopying.html

如果您的对象主要关注复制,则只需使用结构而不是类,因为它们是值类型而不是引用类型。将您的类更改为结构将使您的类型成为值类型,但有很多面向对象的限制。谢谢

关于ios - 如何复制自定义对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45913005/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com