swift 对象储存地址分析

版权声明:转载请标明出处 https://blog.csdn.net/ZY_FlyWay/article/details/79216805

前言:

 开始学swift,大家不知道有没有我这个疑问,现在用let var 来给常量变量赋值,那么以前OC那些属性修饰符在swift 是怎么用呢?

 swift let var 是strong 强引用 是weak 弱引用 还是copy 呢。带着这个问题,测试分析一波。

测试打印程序

先定义一个打印对象地址方法:

swift4.0打印内存地址的方法是: Unmanaged.passUnretained(obj).toOpaque()

swift语言还在改动中,目前已经趋于稳定,4之前的打印地址内存地址方法:%p ,unsafeaddressof 都以无效。

//定义方法打印对象内存地址
func printAddress(values:AnyObject...){
    for value in values {
        print(Unmanaged.passUnretained(value).toOpaque())
    }
    print("-----------------------------------------")
}

验证测试:先看看这个打印方法是不是打印内存地址,而不是指针地址。制作一个单例,然后看看是否使用一块内存。

final class Single:NSObject {
    static let sharedManger = Single()
    private override init(){
    
    }
}
var  sing1 = Single.sharedManger
var  sing2 = Single.sharedManger
var  sing3 = Single.sharedManger
printAddress(values: sing1 as AnyObject,sing2 as AnyObject,sing3 as AnyObject)

打印结果:

step1 :先测试下基本类型 int (float,doule一致)

直接看程序分析结果:

var a1 = 5
let b1 = a1
a1=8
print(a1,b1)
printAddress(values: a1 as AnyObject,b1 as AnyObject)

let a2 = 5
let b2 = a2
print(a2,b2)
printAddress(values: a2 as AnyObject,b2 as AnyObject)

var a = 5
var b = a
a=8
print(a,b)
printAddress(values: a as AnyObject,b as AnyObject)

打印结果:

step2 :字符串:string 和nsstring

//string
var str = "hello"
var str1 = str
str = "world"
str1
printAddress(values: str as AnyObject,str1 as AnyObject)

//nsssting
var nsstr = NSString.init(string:"6666")
var nsstr1 = nsstr
nsstr = "ssss"
nsstr1
printAddress(values: nsstr as AnyObject,nsstr1 as AnyObject)

step3:数组、字典、结构体:

//数组
var array  = ["1","2","3"]
var array1 = array
array.remove(at: 2)
print(array.description+"---"+array1.description)
printAddress(values: array as AnyObject,array1 as AnyObject)

//结构体
var  my  =  myStruct()
var  my1 =  my
my.height = 5
print(my1.height)

step4:类对象

class ReferenceObj:NSObject,NSCopying{
    func copy(with zone: NSZone? = nil) -> Any {
        let copyobj = ReferenceObj()
        return copyobj;
    }
    
    var name:String = ""
    var age=0
    var friends:NSArray?
    var skill:Dictionary<String, Any>?
}
var ref  = ReferenceObj();
ref.name = "re1"

var ref1  = ref;
print(ref.name+"\n"+ref1.name)

var ref2  = ref.copy() as! ReferenceObj

printAddress(values: ref as AnyObject,ref1 as AnyObject,ref2 as AnyObject)

分析结果:

      以上类型除了let 赋值let的时候和类对象赋值默认赋值情况下是引用,没有对内存地址进行拷贝。其他情况都会进行地址拷贝。如果类对象进行地址拷贝和oc一样遵循NSCopying协议,对象执行copy方法即可拷贝地址。

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券