본문 바로가기

iOS/Swift

UnsafePointer

A pointer for accessing data of a specific type

  • UnsafePointer provides no automated memory management or alignment guarantees.
  • You are responsible for handling the life cycle of any memory you work with through unsafe pointers to avoid leaks or undefined behavior

withUnsafePointer(to) { pointer _ }

Invokes the given closure with a pointer to the given argument

  • 주어진 변수를 클로저 안에서 포인터로 바꾸어 사용하도록 해주는 함수
  • 포인터를 통해 변수의 값을 변경하려고 하면, 정의되지 않은 행동이 발생할 수 있다.
  • 포인터를 통해 주어진 값을 변경하고 싶다면 withUnsafeMutablePointer를 사용해야 한다.
let terms = Terms(title: "Join")

withUnsafePointer(to: termA) { pointer in
    print(pointer.pointee)
}

UnsafeMutablePointer

A pointer for accessing and manipulating data of a specific type

  • ARC에 의해 관리되지 않는 포인터를 만들어 조작할 수 있는 객체
  • 자동으로 메모리 관리가 되지 않기 때문에, 메모리에 관련 해제 및 처리도 사용하는 개발자가 해야한다.
  • 관리를 잘못하면 메모리 누수 및 정의되지않은 동작을 일으킬 수 있다.
  • 포인터가 가르키는 객체가 참조를 포함하지 않는 값타입인 경우 객체 해제를 명시하지 않아도 메모리 누수가 발생하지는 않는다.
let pointer = UnsafeMutablePointer<Terms>.allocate(capacity: 1)

pointer.initialize(to: termA)
print(pointer, pointer.pointee)
pointer.deinitialize(count: 1)
pointer.deallocate()

참고

https://developer.apple.com/documentation/swift/unsafepointer

https://developer.apple.com/documentation/swift/withunsafepointer(to:_:)-1wfum

https://jcsoohwancho.github.io/2020-08-31-Swift에서-만나는-포인터/

'iOS > Swift' 카테고리의 다른 글

UIBackgroundTaskIdentifier  (0) 2024.05.20
NWPathMonitor  (0) 2024.05.08
UnsafePointer  (0) 2024.04.29
Singleton Pattern  (0) 2024.04.15
CombineLatest Vs Zip  (0) 2024.04.08