Why do I have to call super -dealloc last, and not first?

后端 未结 6 1118
南旧
南旧 2020-11-27 16:09

correct example:

- (void)dealloc {
    [viewController release];
    [window release];
    [super dealloc];
}

wrong example:



        
6条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-27 16:37

    Here is actual example where [super dealloc] must be last, otherwise the call to removeFromRunLoop will cause crash. I'm not sure what happens inside NSOutputStream's removeFromRunLoop, but it seems to access 'self' in this case.

    Setup:

    [outputStream setDelegate:self];
    [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    

    Dealloc:

    - (void)dealloc {
        if (outputStream) {
            [outputStream close];
            [outputStream removeFromRunLoop:[NSRunLoop currentRunLoop]
                                    forMode:NSDefaultRunLoopMode];
            [outputStream release];
            outputStream = nil;
        }
        delegate = nil;
        [super dealloc]; // must be last!
    }
    

提交回复
热议问题