swift read write private property

냠냠·2022년 5월 23일
0

iOS

목록 보기
1/3

swift 에서 reflection 으로 객체의 private property 는 읽어올 수 있으나 값 할당은 불가능 합니다. 그리고 private method 는 실행할 수 없습니다.

목적 - object 의 private property read/write. 그리고 private method 호출

방법1. reflection 을 이용할려고 했으나 private proterty read 만 가능하고 write 및 private method 호출이 안됩니다.

방법2. UnsafeMutableRawPointer 를 통한 private proterty read/write. 아쉽게도 private method 호출 불가

아래 코드는 방법 2의 예시 입니다.

let ivar = class_getInstanceVariable(ClassName.self, "PropertyName")
if let ivar = ivar {
	// 객체의 주소값 포인터
	let pointerToInstance = Unmanaged.passUnretained(instanceOfClass).toOpaque()
	// 해당 property 가 객체가 할당된 주소의 처음에서 얼마나 떨어져 있는지
	let fieldOffset = ivar_getOffset(ivar)
    // property read
    var property = pointerToInstance.advanced(by: fieldOffset).load(as: PropertyType.self)
    // property write (property type 에 맞는 데이터를 할당, 여기서는 object 라고 가정하고 object 주소를 가지는 변수(아마 8byte)를 같은 사이즈인 Int64 타입 0 값으로 초기화 했다.
    pointerToInstance.advanced(by: fieldOffset).storeBytes(of: Int64(0), as: Int64.self)
}

해당 방법으로 object property nil 처리는 잘 되는것 처럼 보이지만 reference count 를 감소시키지 않아서 메모리 누수가 발생하는지는 확인해야 할 것 같다. nil 으로 처리가 되는 경우와 안되는 경우가 있는데 이유는 따로 확인해야 할 것 같다.

0개의 댓글