开发者

Cocoa Interface Builder object initialization

Base on the documentation and sample code that I开发者_JAVA技巧 have gone through, I got an impression that when a class defined in xcode is read into and configured in Interface Builder, an object based on the class is effectively created and stored in an xib or nib file. So the object is ready to be used when the corresponding application is launched.

Alternatively, for classes that have not been handled by Interface Builder, code such as the "new" statements have to be written in xcode explicitly in order for the associated objects to be created and used.

It will be very nice to have people who are more knowledgable than me to confirm or to correct my very naive understanding of Interface Builder ...


Your understanding is correct, but incomplete. Yes, Interface Builder instantiates classes and serializes them into the NIB. However, those objects are not automatically available to your code.

For each IB object you want to access through Xcode, you need to declare an IBOutlet variable. Example:

IBOutlet NSWindow* mainWindow;  // A Reference to your main window

Put this code in the header file of a custom object that you instantiate through Interface Builder (drag a generic Object to your class list, then in the Identity tab of the inspector, set the custom object to be an instance of your class). Then, right-click on your custom object in Interface Builder. You should see an entry for your IBOutlet in the window that pops up. Drag from the little circle next to it to (in this example) your main window. You now have a reference to the IB object in Xcode.

It is through making these connections (with IBOutlets for references and IBActions for methods) that you define much of the behavior of your application.


Nib files contain an archived copy of an object graph; everything NSNib or NSBundle needs to know in order to create new instances of all the objects stored in the nib file, connected together as described by the nib's bindings, and with their properties set to the values specified in the nib.

The full process is documented in The Object Loading Process

Objects are not automatically created from a nib but rather created on demand in response to some object loading that nib file. The difference is important because you can have a single object load a nib more than once or have multiple objects load the same nib file.

For example I might create a nib whose "File's Owner" is UIViewController which binds a single UIView object to the File's Owner's 'view' property. I could then have two different UIViewController subclasses (or two instances of the same UIViewController subclass) load that same nib file to each get their own copy of the UIView. Similarly I might load a new UITableViewCell from a nib every time I need a new cell for a table.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜