在Objective-C中如果想將一個數組賦值給另外一個數組,同時想讓兩個數組之間相互獨立(即改變其中的一個數組,不影響另外的一個),有很多的辦法,比如我們可以直接copy,用類方法創建新數組。這樣得到的數組和原來的數組就是兩個完全獨立的數組了,即使數組中的元素是對象。
在swift中情況和Objective-C中稍有不同,根據官方文檔的介紹
Paste_Image.png
1
即,如果數組中的元素是整形,字符串,結構體等簡單數據類型,那么當你將一個數組賦值給另外的數組時,數組中的元素會被拷貝一份,兩個數組中的元素相互獨立。
var numbers = [1, 2, 3, 4, 5]
var numbersCopy = numbers
numbers[0] = 100
print(numbers)
// Prints "[100, 2, 3, 4, 5]"
print(numbersCopy)
// Prints "[1, 2, 3, 4, 5]"
而如果數組中的元素是類的實例,那么會有些不同
Paste_Image.png
2
即,當數組的元素是類的實例時,簡單的將一個數組賦值給另外的數組后,由于兩個數組中元素所引用的對象相同,當你改變其中一個數組中元素的屬性時,另外的數組中同樣引用的元素對應的屬性也會隨之改變,除非數組中的元素只想不同的類的實例
// An integer type with reference semantics
class IntegerReference {
var value = 10
}
var firstIntegers = [IntegerReference(), IntegerReference()]
var secondIntegers = firstIntegers
// Modifications to an instance are visible from either array
firstIntegers[0].value = 100
print(secondIntegers[0].value)
// Prints "100"
// Replacements, additions, and removals are still visible
// only in the modified array
firstIntegers[0] = IntegerReference()
print(firstIntegers[0].value)
// Prints "10"
print(secondIntegers[0].value)
// Prints "100"
由于這樣的特性就會產生一些問題,比如從頁面1中將一個含有特定類實例的數組傳遞給第二個頁面,在第二個頁面中對這個數組中的某些元素的屬性進行了更改,那么就會影響到第一個頁面的對應數組中的該元素,常見的場景就是含有model的數組的傳遞。
解決辦法1:
根據官方文檔介紹由于swift加強了結構體的功能,同時數組中元素如果是結構體的話,會自動進行拷貝(前面說過),所以遇到這種情況如果可以用結構體的話就不要用類(但是結構體有時確實很不方便呀,不太習慣創建model的時候用結構題呀)。
解決辦法2:
在Model類中遵守Coping協議,同時實現對應的方法,具體如下:
protocol Copying {
init(original: Self)
}
extension Copying {
func copy() -> Self {
return Self.init(original: self)
}
}
class Model: NSObject, Copying {
required init(original: Model) {
//Model的屬性
planId = original.planId
selectName = original.selectName
}
}
這樣Model的實例就可以調用copy方法來拷貝一個新的對象了,如果對于數組來說就這樣:
var modelArr = [model0, model1,model2,model3,]
var copyPlantsArr = [Model]()
for model in modelArr {
let copyModel = model.copy()
copyPlantsArr.append(copyModel)
}
在copyPlantsArr中就是拷貝后的新的數組,兩個數組之間相互獨立(辦法有點麻煩😭),也可以將上一步替換為給數組增加擴展(這個沒有親自試過)
extension Array where Element: Copying {
func clone() -> Array {
var copiedArray = Array()
for element in self {
copiedArray.append(element.copy())
}
return copiedArray
}
}
上面就是我找到swift中實現數組的深拷貝的辦法了,總感覺有點麻煩,希望有知道更簡單,好用辦法的兄弟給我留言,謝謝。
希望我的文章對你有幫助,努力,堅持,與君共勉。