iOS/Swift

[Swift] 객체 생성자, 해제자

단비_danbee 2022. 12. 4. 11:16
이니셜라이저 (Initializers)
이니셜라이저는 특정 타입의 인스턴스를 생성합니다. 이니셜라이저의 가장 간단한 형태는 파라미터가 없고 init 키워드를 사용하는 것입니다.
import UIKit

class MyFriend {
    var name : String
    
    init(_ name: String = "이름없음"){
        self.name = name
        print("MyFriend가 메모리에 올라갔다 - \(name)")
    }
    deinit {
        print("메모리에서 사라짐 - \(name)")
    }
    
    var calledTimes = 0
    let MAX_TIME = 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_TIME {
            MyFriend.destroySelf(object:self)
        }
    }
}

var myFirstFriend = MyFriend()
print("이름없음 끝")
let mySecondFriend = MyFriend("단비")
print("단비 끝")
//인스턴스 메모리에서 해제하기
weak var selfDestructingObject = MyFriend("수진")
print("수진 끝")
if selfDestructingObject != nil {
    selfDestructingObject!.call()
} else {
    print("object no longer exists")
}

출력 결과

MyFriend가 메모리에 올라갔다 - 이름없음
이름없음 끝
MyFriend가 메모리에 올라갔다 - 단비
단비 끝
MyFriend가 메모리에 올라갔다 - 수진
메모리에서 사라짐 - 수진
수진 끝
object no longer exists