2017-08-28 40 views
-1

我需要复制一个自定义对象。是否有可能不手动复制每个领域?如何复制自定义对象?

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" */ 

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

+0

是的,你可以这样做,就像test2 = test1.mutableCopy() –

+0

在尝试mutablecopy时在该行上崩溃 – Jan

+2

只有当'CustomerInfo'是一个单例时才会发生这种情况。用一个普通的结构或类,你会得到两个不同的对象。 – vadian

回答

0

因为类是引用类型,你可以使用struct(价值型)做

This answer确实是一个很好的例子

2
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并实现上面的copyWithZone:方法。

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

  3. 每当你想复制只需复制你的激动人心的对象。 为完整的参考追踪这个苹果官方https://developer.apple.com/library/content/documentation/General/Conceptual/DevPedia-CocoaCore/ObjectCopying.html

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

相关问题