본문 바로가기
Swift

[Swift] deinit에서 self에 접근해도 되는가?

by Sky Titan 2022. 6. 2.
728x90
 

Swift - self in deinit method

Is it good practice to use self in swift deinit method?. In objective C we avoid use of self in init and dealloc method. Is same applied for swift?

stackoverflow.com

deinit에서 self에 접근해도 되는가?

  • 결론적으로 해도 된다.
  • deinit의 역할 자체가 메모리 해제 전 마지막으로 self에 접근할 수 있도록 하는 것이기 때문에 접근하는 것은 문제될 것이 없다.
  • 단, deinit에서 self를 다른 객체에 저장하는 행위는 해선 안된다.
    • 크래시 발생

 

deinit에서 self를 다른 객체에 저장할 경우

class SingleToneTest {
    static var test: Test = Test()
}
class Test {
    
    deinit {
        SingleToneTest.test = self
    }
}


var test: Test? = Test()
test = nil //error: Execution was interrupted, reason: signal SIGABRT.

/* 크래시 발생
Simultaneous accesses to 0x1032703d0, but modification requires exclusive access.
Previous access (a modification) started at  (0x105758ed0).
Current access (a modification) started at:
0    libswiftCore.dylib                 0x000000018f97c0d0 swift::runtime::AccessSet::insert(swift::runtime::Access*, void*, void*, swift::ExclusivityFlags) + 428
1    libswiftCore.dylib                 0x000000018f97c2f0 swift_beginAccess + 72
4    libswiftCore.dylib                 0x000000018f97e538 _swift_release_dealloc + 28
7    libswiftCore.dylib                 0x000000018f97e538 _swift_release_dealloc + 28
9    MyPlayground                       0x0000000102e273c8 main + 0
10   CoreFoundation                     0x000000018036056c __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 20
11   CoreFoundation                     0x000000018035f6bc __CFRunLoopDoBlocks + 408
12   CoreFoundation                     0x0000000180359d1c __CFRunLoopRun + 764
13   CoreFoundation                     0x00000001803595c8 CFRunLoopRunSpecific + 572
14   GraphicsServices                   0x000000018c23656c GSEventRunModal + 160
15   UIKitCore                          0x0000000184d7b94c -[UIApplication _run] + 992
16   UIKitCore                          0x0000000184d80858 UIApplicationMain + 112
17   MyPlayground                       0x0000000102e273c8 main + 192
Fatal access conflict detected.
*/
728x90

'Swift' 카테고리의 다른 글

[Swift] 메모리 구조  (0) 2022.06.06
[Swift] Class vs Struct  (0) 2022.06.02
[Swift] closure에서 self를 써야하는 이유  (0) 2022.05.16
[Swift] 캡처리스트 (Capture List)  (0) 2022.04.05
[Swift] closure 내부의 weak self 사용  (0) 2022.04.03

댓글