Delegate as external class in Objective-C

孤街浪徒 提交于 2019-12-04 13:50:16
Chris Lundie

Your Control1Delegate object is getting destroyed soon after it is created. All top-level Nib objects must be retained if you want to keep them alive. Refer to the Resource Programming Guide: The Nib Object Life Cycle.

The File's Owner could have a property like this, in order to retain the object:

@property (nonatomic, retain) IBOutlet Control1Delegate *control1delegate;

Remember to release the object after it is no longer needed.

You can put delegate methods in any class, including one built just for that purpose. The reason Apple (and other programmers) usually don't make classes specifically for delegate functions is it becomes overly complex and hard to share data. For instance, in one of my projects I might make a Window Controller subclass that handles delegate methods from the window, the table view inside the window, and the window's toolbar. Everything you need to manipulate and maintain the state of that window is in one controller class. Now imagine three separate classes (plus probably a controller class to manage them) doing the same functions-- that's a lot of extra work for no real benefit.

As to why it's crashing, it sounds like you're making a mistake with memory management somewhere else in your application. You can use the debugger to track down exactly where it's coming from.

Thank you both. Not only I know now how to solve my problem, but also finally understood how objects are retained in Nib creation process. It's not enough to create object in IB, if it's a new entity, it has to be connected to a real ivar in File's Owner (with properly synthetised getter/setter).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!