数组NSArray继承自NSObject,属于对象, 包含Copy的方法,然而Swift的数组是struct,没有了Copy方法。那么把一个数组变量赋值给另一个变量之后,两个变量的内存地址一样吗?
定义class和struct
class MyClass {
var intArr = [Int]()
var structArr = [MyStructElement]()
var objectArr = [MyClassElement]()
}
struct MyStructElement {
}
class MyClassElement{
var name: String?
init() {
}
init(name: String) {
self.name = name
}
}
//获取内存地址
let memoryAddress : (Any) -> String = {
guard let cVarArg = $0 as? CVarArg else { return "Can not find memory address" }
return String(format: "%p", cVarArg)
}
测试Int 数组
//array 的元素是 Int、struct 等,在赋值时就 copy
func testIntArr() {
print(#function)
let my = MyClass()
for i in 0...10000 {
my.intArr.append(i)
}
print("Before arr address:",memoryAddress(my.intArr))
let arr = my.intArr// If move this into async closure, crash
print("temp arr address: ",memoryAddress(arr)) // Copy. Address different from my.intArr
my.intArr.removeAll()
print("After arr address:", memoryAddress(my.intArr)) // New address
}
结论:[Int]数组赋值给另一个变量时,内存地址发生改变,数组被重新创建
测试struct数组
private func testStructArr() {
print(#function)
let my = MyClass()
for _ in 0...10000 {
my.structArr.append(MyStructElement())
}
print("Before arr address:\(memoryAddress(my.structArr))")
let arr = my.structArr
print("Temp arr address:", memoryAddress(arr)) // Copy. Address different from my.structArr
my.structArr.removeAll()
print("After arr address:", memoryAddress(my.structArr)) // New address
}
结论:结构体数组赋值给另一个变量时,内存地址发生改变,数组被重新创建
测试对象数组
private func testObjectArr() {
print(#function)
let my = MyClass()
for _ in 0...10000 {
my.objectArr.append(MyClassElement())
}
print("Before arr address:", memoryAddress(my.objectArr))
var arr = my.objectArr
print("Temp arr address:", memoryAddress(arr)) // Not copy. Same as my.objectArr
//更新arr数组的元素时,arr发生copy行为,地址发生变化
my.objectArr.removeAll()
print("After arr address:", memoryAddress(my.objectArr)) // New address
print("原数组元素个数:\(my.objectArr.count),新数组 arr 的元素个数:\(arr.count)")
}
结论:对象数组赋值给另外一个变量时,内存地址不变,只将引用赋值给另一个变量;原来的 array 改变后,内存地址改变,但不影响被赋值的变量。