Settings IBOutlets to nil in dealloc

2020-03-01 19:49发布

In the section titled 'Memory Warnings' here http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmNibObjects.html, I don't follow why the IBOutlet is set to nil in the dealloc. If

self.anOutlet = nil

causes a crash as mentioned in the topic, why are they setting the ivar to nil?

In general, why would you set an ivar to nil in the dealloc when you are already calling release?

4条回答
等我变得足够好
2楼-- · 2020-03-01 20:21

After a release, the pointer is essentially invalid and accessing it again may cause a crash. By setting a variable to nil after release you prevent that crash from happening. There's no harm in accessing a nil pointer.

The example you've linked to simply demonstrates why it's always a good idea to set a variable or ivar to nil after release, even when it looks like the variable/ivar won't be accessed again.

In the example, the anOutlet ivar is actually accessed by the superclass after your dealloc method, so if you don't set it to nil you will get a crash. Scenarios like that are very hard to spot just by looking at the code, so it's a good idea to nil every variable after release, even in dealloc.

查看更多
萌系小妹纸
3楼-- · 2020-03-01 20:25

Sometimes a crash is a good thing, and a quick solution would hide a deeper problem. Calling a released variable might be something you want to know about.

The book iOS Recipes refers to this issue:

Cleanup in -dealloc
In addition to releasing all relevant instance variables in the -dealloc, our examples set them to nil. This practice is one of the most hotly debated topics among Cocoa programmers, and both sides of the argu- ment hold weight. This book is not meant to participate in the debate at all: we set them to nil, but that doesn’t mean you have to. If you don’t like nil-in-dealloc, feel free to leave it out of your own code.

A quick google search found this thread:
http://www.cocoabuilder.com/archive/cocoa/204055-why-should-we-set-ivars-to-nil-in-dealloc.html

查看更多
\"骚年 ilove
4楼-- · 2020-03-01 20:27

Sometimes when one property becomes invalid (set to nil) we want to make other properties invalid too. If a class invalidates a property by using self.property_name=nil, then this will send a release message, which will cause a crash in dealloc if we have already called release on that property. If the invalidation occurs in a superclass, then this error is hidden and quite nasty. So whenever a superclass might invalidate a property it may be a good idea to set it to nil rather than just deallocing.

查看更多
倾城 Initia
5楼-- · 2020-03-01 20:41

Sending a message on an object that is released causes a crash, sending a message to a nil object is ignored.

查看更多
登录 后发表回答