UnsafePointer、UnsafeMutablePointer一种是不可变的,一种是可变的。
UnsafePointer我的理解就是用来做传参数用的,不可写。而我们平常用的最多的就是UnsafeMutablePointer。
指针初始化
var a = UnsafeMutablePointer<Int>.allocate(capacity: 1);// 声明一个指针,指针类型是Int,内存大小就是1份Int的大小
a.pointee = 10;//指针a的值设定是10
获取对象指针
var f : Int = 1;
var fPointer = withUnsafePointer(to: &f) {
return $0;
}
指针运算
let aptr = UnsafeMutablePointer<Int>.allocate(capacity: 5); //申明一个5份Int大小的内存空间
aptr.initialize(from: [33,34,35,36,37]); // 初始化
print("0_\(aptr.pointee)");
let a = aptr.advanced(by: 1); // 指针后移
print("1_\(a.pointee)");
let b = a.successor(); // 指针后移
print("2_\(b.pointee)");
let c = b + 1; // 指针后移
print("2_\(c.pointee)");
Unmanaged 对象来管理引用计数
let thisPointer = Unmanaged<UIViewController>.passUnretained(self).toOpaque();
得到self的指针地址。然后再通过
let this = Unmanaged<UIViewController>.fromOpaque(thisPointer).takeRetainedValue()
将其转换回来。
passRetained & passUnretained 强弱引用
takeRetainedValue & takeRetainedValue 强弱引用
强制指针类型转换
pointer.withMemoryRebound(to: Int.self, capacity: 1, { (p2) -> Void in
print(p2.pointee)
})
上面代码等同于
UnsafeRawPointer(pointer).bindMemory(to: Int.self, capacity: 1)
网友评论