source: trunk/source/examples/cocoa/nib-loading/HOWTO.html @ 11975

Last change on this file since 11975 was 11975, checked in by rme, 12 years ago

Update nib-loading example by getting rid of @class and correcting
some memory manangement errors.

File size: 17.8 KB
1<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
2          "">
3<html xmlns="">
4  <head>
5    <title>Nib-Loading HOWTO</title>
6    <link rel="stylesheet" type="text/css" href="HOWTO_files/stylesheets/styles.css" />
7  </head>
9  <body>
11    <div class="title">
12      <h1>Nib-Loading HOWTO</h1>
13    </div>
15    <div class="body-text">
16      <p>This HOWTO shows how you can load <strong>nibfiles</strong>
17        into a running copy of Clozure CL by evaluating Lisp forms. You
18        might want to load nibfiles this way to test user-interface
19        elements that you are working on for an application project, or
20        to enable an application to dynamically load optional
21        user-interface elements.</p>
23    </div>
25    <div class="section-head">
26      <h2>Nibfiles</h2>
27    </div>
29    <div class="body-text">
30      <p>A large part of developing Cocoa applications is creating
31        user-interface elements using the Cocoa frameworks. Although
32        it's perfectly possible to create any user-interface element
33        just by making method calls against the frameworks, the more
34        standard way to design a user interface is to use Apple's
35        InterfaceBuilder application to
36        create <strong>nibfiles</strong>&mdash;files of archived
37        Objective-C objects that implement the user-interface
38        elements.</p>
40      <p>InterfaceBuilder is an application that ships with Apple's
41        Developer Tools. The Developer Tools are an optional install
42        that comes with Mac OS X. Before you can use this HOWTO, you'll
43        need to make sure that Apple's Developer Tools are installed on
44        your system. Members of Apple's developer programs may download
45        the tools for free from
46        Apple's <href="">developer
47          website</href>, but normally there is no need. You can simply
48        use the optional Developer Tools installer on the Mac OS X
49        system disks to install the tools.</p>
50    </div>
52    <div class="section-head">
53      <h2>Using Nibfiles</h2> 
54    </div>
56    <div class="body-text">
57      <p>Using InterfaceBuilder, you can quickly and easily create
58        windows, dialog boxes, text fields, buttons, and other
59        user-interface elements. The elements you create with
60        InterfaceBuilder have the standard appearance and behavior
61        specified by Apple's Human Interface Guidelines.</p>
63      <p>InterfaceBuilder saves descriptions of these objects
64        in <strong>nibfiles</strong>. These files contain archived
65        representations of Objective-C classes and objects. When you
66        launch an application and it loads a nibfile, the Cocoa runtime
67        creates these Objective-C objects in memory, complete with any
68        instance-variable references to other objects that might have
69        been saved in the nibfile. In short, a nibfile is an archived
70        collection of user-interface objects that Cocoa can quickly and
71        easily revive in memory.</p>
73      <p>The normal way that Objective-C programmers use nibfiles is
74        by storing them in an application bundle. The application's
75        Info.plist file (also stored in the bundle) specifies which
76        nibfile is the application's main nibfile, and that file is
77        loaded automatically when the application starts up. The
78        application can dynamically load other nibfiles from the bundle
79        by making method calls.</p>
81      <p>Lisp applications written with Clozure CL can also use
82        nibfiles in this same fashion (see the "currency-converter"
83        HOWTO in the "cocoa" examples folder), but Lisp programmers are
84        accustomed to highly interactive development, and might want to
85        simply load an arbitrary nibfile into a running Clozure CL
86        session. Fortunately, this is easy to do.</p>
87    </div>
89    <div class="section-head">
90      <h2>How To Load a Nibfile</h2> 
91    </div>
93    <div class="body-text">
94      <p>Let's start by loading a very simple nibfile from the Clozure
95        CL Listener window. Start by launching the Clozure CL
96        application.</p>
98      <p>In the same directory as this HOWTO file, you'll find a
99        nibfile named "hello.nib". This is an extremely simple nibfile
100        that creates a single Cocoa window with a greeting in it. We'll
101        use forms typed into the Listener window to load it.</p>
103      <p>We're going to call the Objective-C class
104        method <code>loadNibFile:externalNameTable:withZone:</code> to
105        load the nibfile into memory, creating the window that is
106        described in the file. First, though, we need to set up some
107        data structures that we'll pass to this method.</p>
109      <p>The arguments
110        to <code>loadNibFile:externalNameTable:withZone:</code> are a
111        pathname, a dictionary object, and a memory zone. As with every
112        Objective-C method call, we also pass the object that receives
113        the message, which in this case is the class NSBundle.</p>
115      <p>The pathname is just a reference to the nibfile we want to
116        load. The dictionary holds references to objects. In this
117        first simple example, we'll use it only to identify the
118        nibfile's owner, which in this case is the application
119        itself. The zone is a reference to the area of memory where
120        the nibfile objects will be allocated.</p>
122      <p>Don't worry if none of this makes sense to you; the code to
123        create these objects is simple and straightforward, and should
124        help clarify what's going on.</p>
126      <div class="section-head">
127        <h3>1. Get the Zone</h3> 
128      </div>
130      <p>First, we'll get a memory zone. We'll tell Cocoa to allocate
131        the nibfile objects in the same zone that the application
132        uses, so getting a zone is a simple matter of asking the
133        application for the one it's using.</p>
135      <p>Before we can ask the application anything, we need a
136        reference to it.  When the Clozure CL application starts up,
137        it stores a reference to the Cocoa application object into
138        the special variable *NSApp*.</p>
140      <p>Start by changing to the CCL package; most of the utility
141        functions we'll use are defined in that package:</p>
143      <pre>
144        ? (in-package :ccl)
145        #&lt;Package "CCL"&gt;
146      </pre>
148      <p>We have a reference to the running Clozure CL application
149        object in the special variable *NSApp*.  We can ask it for its
150        zone, where it allocates objects in memory:</p>
152      <pre>
153        ? (setf *my-zone* (#/zone *NSApp*))
154        #&lt;A Foreign Pointer #x8B000&gt;
155      </pre>
157      <p>Now we have a reference to the application's zone, which is
158        one of the parameters we need to pass
159        to <code>loadNibFile:externalNameTable:withZone:</code>.</p>
161      <div class="section-head">
162        <h3>2. Make a Dictionary</h3> 
163      </div>
165      <p>The dictionary argument
166        to <code>loadNibFile:externalNameTable:withZone:</code> is
167        used for two purposes: to identify the nibfile's owner, and
168        to collect toplevel objects.</p>
170      <p>The nibfile's owner becomes the owner of all the toplevel
171        objects created when the nibfile is loaded, objects such as
172        windows, buttons, and so on. A nibfile's owner manages the
173        objects created when the nibfile is loaded, and provides a
174        way for your code to get references to those objects. You
175        supply an owner object in the dictionary, under the
176        key <code>"NSNibOwner"</code>.</p>
178      <p>The toplevel objects are objects, such as windows, that are
179        created when the nibfile is loaded. To collect these, you
180        can pass an <code>NSMutableArray</code> object under the
181        key <code>NSNibTopLevelObjects</code>.</p>
183      <p>For this first example, we'll pass an owner object (the
184        application object), but we don't need to collect toplevel
185        objects, so we'll omit
186        the <code>NSNibTopLevelObjects</code> key.</p>
188      <pre>
189        ? (setf *my-dict*
190        (#/dictionaryWithObject:forKey: ns:ns-mutable-dictionary
191        *my-app*
192        #@"NSNibOwner"))
193        #&lt;NS-MUTABLE-DICTIONARY {
194        NSNibOwner = &lt;LispApplication: 0x1b8e10&gt;;
195        } (#x137F3DD0)&gt;
197      </pre>
199      <div class="section-head">
200        <h3>3. Load the Nibfile</h3> 
201      </div>
203      <p>Now that we have the zone and the dictionary we need, we
204        can load the nibfile. We just need to create an NSString with
205        the proper pathname first:</p>
207      <pre>
208        ? (setf *nib-path*
209        (%make-nsstring
210        (namestring "/usr/local/openmcl/ccl/examples/cocoa/nib-loading/hello.nib")))
211        #&lt;NS-MUTABLE-STRING "/usr/local/openmcl/ccl/examples/cocoa/nib-loading/hello.nib" (#x13902C10)&gt;
212      </pre>
214      <p>Now we can actually load the nibfile, passing the method
215        the objects we've created:</p>
217      <pre>
218        ? (#/loadNibFile:externalNameTable:withZone:
219        ns:ns-bundle
220        *nib-path*
221        *my-dict*
222        *my-zone*)
223        T
224      </pre>
226      <p>The window defined in the "hello.nib" file should appear
227        on the
228        screen. The <code>loadNibFile:externalNameTable:withZone:</code>
229        method returns <code>T</code> to indicate it loaded the
230        nibfile successfully; if it had failed, it would have
231        returned <code>NIL</code>.</p>
233      <p>At this point we no longer need the pathname and
234        dictionary objects.  The *nib-path* we must release:</p>
236      <pre>
237        ? (setf *nib-path* (#/release *nib-path*))
238        NIL
239      </pre>
241      <p>The *my-dict* instance was not created with #/alloc (or with
242      MAKE-INSTANCE), so it is already autoreleased, and we don't need
243      to release it again.
245      <div class="section-head">
246        <h2>Making a Nib-loading Function</h2> 
247      </div>
249      <p>Loading a nibfile seems like something we might want to do
250        repeatedly, and so it makes sense to make it as easy as possible
251        to do. Let's make a single function we can call to load a nib as
252        needed.</p>
254      <p>The nib-loading function can take the file to be loaded as a
255      parameter, and then perform the sequence of steps covered in the
256      previous section. If we just literally do that, the result will
257      look something like this:</p>
259      <pre>
260(defun load-nibfile (nib-path)
261  (let* ((app-zone (#/zone *NSApp*))
262         (nib-name (%make-nsstring (namestring nib-path)))
263         (dict (#/dictionaryWithObject:forKey:
264                 ns-mutable-dictionary app #@"NSNibOwner")))
265    (#/loadNibFile:externalNameTable:withZone: ns:ns-bundle
266                                               nib-name
267                                               dict
268                                               app-zone
269                                             )))
270      </pre>
272      <p>The trouble with this function is that it leaks a string
273      every time we call it. We need to release the
274      <code>nib-name</code> before returning. So how about this
275      version instead?</p>
277      <pre>
278(defun load-nibfile (nib-path)
279  (let* ((app-zone (#/zone *NSApp*))
280         (nib-name (%make-nsstring (namestring nib-path)))
281         (dict (#/dictionaryWithObject:forKey:
282                ns-mutable-dictionary app #@"NSNibOwner"))
283         (result (#/loadNibFile:externalNameTable:withZone: ns:ns-bundle
284                                                            nib-name
285                                                            dict
286                                                            app-zone)))
287    (#/release nib-name)
288    result))
289      </pre>
291      <p>This version solves the leaking problem by binding the result
292      of the load call to <code>result</code>, then releasing the
293      <code>nib-name</code> before returning the result of the
294      load.</p>
296      <p>There's just one more problem: what if we want to use the
297      dictionary to collect the nibfile's toplevel objects, so that we
298      can get access to them from our code? We'll need another version
299      of our function.</p>
301      <p>In order to collect toplevel objects, we'll want to pass an
302      NSMutableArray object in the dictionary, stored under the key
303      <code>NSNibTopLevelObjects</code>. So we first need to create such an
304      array object in the <code>let</code> form:</p>
306      <pre>
307(let* (...
308       (objects-array (#/arrayWithCapacity: ns:ns-mutable-array 16))
309       ...)
310  ...)
311      </pre>
313      <p>Now that we have the array in which to store the nibfile's
314      toplevel objects, we need to change the code that creates the
315      dictionary, so that it contains not only the owner object, but
316      also the array we just created:</p>
318      <pre>
319  (let* (...
320         (dict (#/dictionaryWithObjectsAndKeys: ns:ns-mutable-dictionary
321                    app #@"NSNibOwner"
322                    objects-array #&amp;NSToplevelObjects
323                    +null-ptr+))
324         ...)
325    ...)
327      </pre>
329      <p>We now want to collect the objects in it. We'll do that by
330      making a local variable to store them, then iterating over the
331      array object to get them all.  (Normally, when we want to keep
332      an object from an array, we have to retain it.  Top-level nib
333      objects are a special case: they are created by the nib loading
334      process with a retain count of 1, and we are responsible for releasing
335      them when we're through with them.)</p>
337      <pre>
338  (let* (...
339         (toplevel-objects (list))
340         ...)
341    (dotimes (i (#/count objects-array))
342      (setf toplevel-objects
343            (cons (#/objectAtIndex: objects-array i)
344                  toplevel-objects)))
345    ...)
346      </pre>
348      <p>After collecting the objects, we can release the array, then
349      return the list of objects. It's still possible we might want
350      to know whether the load succeeded, so we
351      use <code>values</code> to return both the toplevel objects and
352      the success or failure of the load.</p>
354      <p>The final version of the nib-loading code looks like
355      this:</p>
357      <pre>
358(defun load-nibfile (nib-path)
359  (let* ((app-zone (#/zone *NSApp*))
360         (nib-name (%make-nsstring (namestring nib-path)))
361         (objects-array (#/arrayWithCapacity: ns:ns-mutable-array 16))
362         (dict (#/dictionaryWithObjectsAndKeys: ns:ns-mutable-dictionary
363                    *NSApp* #@"NSNibOwner"
364                    objects-array #&NSNibTopLevelObjects
365                    +null-ptr+))
366         (toplevel-objects (list))
367         (result (#/loadNibFile:externalNameTable:withZone: ns:ns-bundle
368                                                            nib-name
369                                                            dict
370                                                            app-zone)))
371    (dotimes (i (#/count objects-array))
372      (setf toplevel-objects
373            (cons (#/objectAtIndex: objects-array i)
374                  toplevel-objects)))
375    (#/release nib-name)
376    (values toplevel-objects result)))
377      </pre>
379      <p>Now we can call this function with some suitable nibfile,
380      such as simple "hello.nib" that comes with this HOWTO:</p>
382      <pre>
383? (ccl::load-nibfile "hello.nib")
384(#&lt;LISP-APPLICATION &lt;LispApplication: 0x1b8da0&gt; (#x1B8DA0)&gt;
385 #&lt;NS-WINDOW &lt;NSWindow: 0x171344d0&gt; (#x171344D0)&gt;)
388      </pre>
390      <p>The "Hello!" window appears on the screen, and two values are
391      returned. The first value is the list of toplevel objects that
392      were loaded. The second value, <code>T</code> indicates that the
393      nibfile was loaded successfully.</p>
395      <div class="section-head">
396        <h2>What About Unloading Nibfiles?</h2> 
397      </div>
399      <p>Cocoa provides no general nibfile-unloading API. Instead, if
400      you want to unload a nib, the accepted approach is to close all
401      the windows associated with a nibfile and release all the
402      toplevel objects. This is one reason that you might want to use
403      the <code>"NSNibTopLevelObjects"</code> key with the dictionary
404      object that you pass
405      to <code>loadNibFile:externalNameTable:withZone:</code>&mdash;to
406      obtain a collection of toplevel objects that you release when
407      the nibfile is no longer needed.</p>
409      <p>In document-based Cocoa applications, the main nibfile is
410      usually owned by the application object, and is never unloaded
411      while the application runs. Auxliliary nibfiles are normally
412      owned by controller objects, usually instances of
413      <code>NSWindowController</code> subclasses. When you
414      use <code>NSWindowController</code> objects to load nibfiles,
415      they take responsibility for loading and unloading nibfile
416      objects.</p>
418      <p>When you're experimenting interactively with nibfile loading,
419      you may not start out by
420      creating <code>NSWindowController</code> objects to load
421      nibfiles, and so you may need to do more of the object
422      management yourself. On the one hand, loading nibfiles by hand
423      is not likely to be the source of major application problems. On
424      the other hand, if you experiment with nib-loading for a long
425      time in an interactive session, it's possible that you'll end up
426      with numerous discarded objects cluttering memory, along with
427      various references to live and possibly released objects. Keep
428      this in mind when using the Listener to explore Cocoa. You can
429      always restore your Lisp system to a clean state by restarting
430      it, but of course you then lose whatever state you have built up
431      in your explorations. It's often a good idea to work from a text
432      file rather than directly in the Listener, so that you have a
433      record of the experimenting you've done. That way, if you need
434      to start fresh (or if you accidentally cause the application to
435      crash), you don't lose all the information you gained.</p>
437    </div>
439  </body>
Note: See TracBrowser for help on using the repository browser.