The setting is the following:
- I have a cocoa object in a nib file that is loaded when the NSWindow and view is loaded
- The window can be closed
- I also access the object programmatically
Now what happens in some situations is that I get a crash, when I try to send a message to the object, but it has been deallocated before (because the window is closed). The crash looks like this:
Exception Type: EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: KERN_INVALID_ADDRESS at 0x0000000000000017
Crashed Thread: 0
Dispatch queue: com.apple.main-thread
Application Specific Information:
objc_msgSend() selector name: ...
Is there any way to check if the object is available or not? Checking for nil does not work, it is not nil. Probably th开发者_C百科e control flow is not perfect, and I could rewrite other chunks of the app to make this problem go away, but I think this is a more general problem that I have no solution for, and it boils down to this:
How can I make sure that an object that is loaded from a nib is set to nil on deallocation?
I guess you could use Interfacebuilder to write your Window-class and in its dealloc method you could set the VARIABLE to nil. But you cannot set the object itself to nil. the variable saves a pointer to the object, if its deallocated the pointer points to a place in memory where anything could be.
So if you access said object from another class, you have another variable, so setting the one in your windows-class to nil, wouldnt be useful at all.
The solution is quiet simple, since the window-class sends this object a release message when the window get deallocated, you should retain your object bevor you use it in another class, and then release it when youre done with it.
If you use a property for your object with the retain-attribute dont forget to call the setter with self.object = ... without property it could look sth like this:
so you need to retain your object bevor the window gets closed. maybe in the first viewDidLoad-method that gets called by your app:
...
- (void)viewDidLoad {
otherClassObject.YOUROBJECT = [self.YOUROBJECT retain];
Try deactivating the window setting "Release when close" on Interface Builder.
精彩评论