[swift]12. 객체 생성자, 해제자

RudinP·2023년 9월 14일
0

Study

목록 보기
31/227

메모리에 올리고 내리는 것

생성자: init

해제자: deinit

class MyFriend{
    var name: String
    
    init(_ name: String = "이름없음"){
        self.name = name
        print("MyFriend가 메모리에 올라갔다.")
    }
    
    deinit{
        print("메모리에서 사라짐: \(self.name)")
    }
}

객체 주소 프린트

let anObjectMemoryAddress = Unmanaged.passUnretained(aFriend).toOpaque()

  • 객체가 생성될 때엔 init을, 사라질 땐 deinit을 실행한다.
import UIKit

class MyFriend{
    var name: String
    
    init(_ name: String = "이름없음"){
        self.name = name
        print("MyFriend가 메모리에 올라갔다.")
    }
    
    deinit{
        print("메모리에서 사라짐: \(self.name)")
    }
    
    var calledTimes = 0
    let MAX_TIMES = 5
    
    static var instancesOfSelf = [MyFriend]()
    
    class func destroySelf(object: MyFriend){
        instancesOfSelf = instancesOfSelf.filter{(aFriend : MyFriend) in aFriend !== object
            
        }
    }
    
    func call(){
        calledTimes += 1
        print("called \(calledTimes)")
        if calledTimes > MAX_TIMES{
            MyFriend.destroySelf(object: self)
        }
    }
}

var myFriend = MyFriend("쩡대리")
let aFriend = MyFriend()

//Unmanaged.passUnretained(객체).toOpaque()로 해당 객체 메모리 주소 프린트
let anObjectMemoryAddress = Unmanaged.passUnretained(aFriend).toOpaque()
let secondMemoryAddress = Unmanaged.passUnretained(myFriend).toOpaque()

print(anObjectMemoryAddress)
print(secondMemoryAddress)

weak var aFriendToBeDetroied = MyFriend("개발하는정대리")

if aFriendToBeDetroied != nil{
    aFriendToBeDetroied!.call()
} else{
    print("객체가 더 이상 메모리에 없습니다.")
}
profile
곰을 좋아합니다. <a href = "https://github.com/RudinP">github</a>

0개의 댓글