TweetFollow Us on Twitter

TinyViewer

Volume Number: 19 (2003)
Issue Number: 5
Column Tag: Programming

Getting Started

TinyViewer

by Dave Mark

When I first started programming the Mac, lo those many years ago, one of the earliest programs I wrote was a teeny app called PictViewer. PictViewer put up a standard document window, with scroll bars and a grow box, and drew a pict image, centered in the window. The first version just displayed the image, clipping it to the window FrameRect as needed. The scroll bars were mere decoration. When I tackled a more advanced version of PictViewer, I added the callback routines and other code to bring the scroll bars to life. In still a later incarnation, I added the ability to drag and drop an image on a PictViewer window.

As I was putting the finishing touches on this project, I remember thinking, "gee, it sure would be nice if all this was just a bit easier." Frameworks like PowerPlant did go a long way towards stringing all the pieces together, but there was still a lot of hand-coding to be done and lots of room for error.

As you'll see in this month's program, TinyViewer, the combination of the Objective-C runtime and tools like Interface Builder and Project Builder take working with objects to the next level.

Getters, Setters, and Key Value Coding

Before we dig into TinyViewer, I'd like to take a moment to emphasize a point I made in my March column. The issue was a naming convention for accessor functions. I suggested that you name your getter methods to match the name of the instance variable being retrieved, then put the word "set" in front of that (be sure to cap the first letter after the word "set") to name the setter function. Here's the example I gave:

- (int)height;        // Returns the value of the height field
- (void)setHeight:(int)h;    // Sets the height field to
                                     // the value in h

Bill Cheeseman, famous ex-attorney (remember the John Travolta movie A Civil Action? Bruce Norris played Bill in the movie. True.) and Cocoa aficionado (I highly recommend his most excellent book, Cocoa Recipes for Mac OS X: The Vermont Recipes), took the time to discuss the importance of this convention with me.

In a nutshell, consider this naming convention mandatory, not optional. In Bill's words:

    "The -height and -setHeight: getter and setter naming conventions are expected by many features of the AppKit and Foundation. While these are optional naming "conventions" from the perspective of Objective-C as a language, they are effectively mandatory if you want to use the Cocoa frameworks. You will lose a lot of important Cocoa framework functionality if you don't follow these naming conventions.

    The most important aspect of the Cocoa frameworks that depends on following these naming conventions is the key-value coding protocol. Look up key-value coding in the Cocoa documentation, and read the class reference document for the NSKeyValueCoding informal protocol in the Foundation frameworks. Several important Cocoa technologies use key-value coding, such as AppleScript. If you don't follow this naming convention for your accessors, you will not be able to take advantage of Cocoa's automatic support for AppleScriptability. There are several other areas where similar dependence on key-value coding requires you to follow these naming conventions.

    Basically, key-value coding lets you write code that calls methods by giving the names of instance variables as strings. This enables you to write a single method which will call other methods based on the strings you provide, rather than having to make actual method calls (er, "to send actual messages") in a long case statement. Because of this, the actual method calls ("messages") can be determined at run time, not hard-coded at compile time. Furthermore, key-value coding gives the separate, added benefit of providing the data in the correct type without your having to code type coercions in a case statement."

Thanks, Bill! As you develop more confidence with Objective-C and Cocoa, spend some time digging through the key-value coding doc and examples. Here's a good link to start with:

http://developer.apple.com/techpubs/macosx...

OK, let's get back to this month's program...

TinyViewer

Every time I sit down to tackle a new Mac programming environment or methodology, I always seem to find myself coming back to PictViewer. How am I going to get PictViewer up and running with this new setup. As soon as I had my first working version of Project Builder installed, the first thing I did was dig through the Cocoa doc, looking for the classes I'd need to master to create a resizable window, with scrollbars, I could usein which I could display an image. Once I figured that out, I'd then tackle some drag-and-drop classes so I could add that feature to the program.

Little did I know how easy (and cool) this would turn out to be.

Create the TinyViewer Project

Launch Project Builder and create a new project of type Cocoa Application. Name the app TinyViewer and save. In the Project Builder Files pane, click to open the triangle to the left of Resources, then open the triangle to the left of MainMenu.nib. This will reveal an item named English (assuming you are on an English-based Mac).

The .nib file is an Interface Builder file. Interface Builder is sort of like ResEdit on steroids. With it, you can customize all your favorite objects and encode them for later decoding when your program is actually run. The item named English in the Project Builder Files tab refers to the English-localized nib file. Figure 1 shows the Finder listing of my version of TinyViewer. Notice the directory named English.lproj and the file MainMenu.nib within that directory. That's the English version of the nib file, the one we'll be working with in this column.


Figure 1. The English.lproj folder inside the project folder.

Figure 2 shows a Terminal listing showing a localized application on my hard drive. I start by going into the /Applications directory, the doing a cd into the sub-directory Clock.app. If I looked at /Applications in a Finder window, Clock.app would just appear as a single application file. In reality, your packaged applications are a series of files, all rolled under a single directory, in this case named Clock.app. As Figure 2 shows, if you make your way down into /Applications/Clock.app/Contents/, you'll see a number of different files and directories, including a directory for each localized version of the app. You should definitely fire up Terminal and try this for yourself. Dive down into your favorite app, then look for English.lproj.


Figure 2. Follow the terminal commands to find your way to the localized .nib files

Editing the .nib File

Double-click on TinyViewer/Resources/MainMenu.nib/English in the project window Files tab. This will open your .nib file in Interface Builder. You'll likely see 4 Interface Builder windows appear. The window labeled Window (Figure 3) represents your app's main window. The window labeled MainMenu.nib - MainMenu (Figure 4) contains your app's menu bar. The window labeled MainMenu.nib (Figure 5) acts as a central repository for the resources/instances you'll be creating. And the window labeled Cocoa - Other (Figure 6) is a palette window.


Figure 3. The default TinyViewer window, shrunk for convenience.


Figure 4. The default application menubar.


Figure 5. The main .nib file navigation window.


Figure 6. The palettes window.

Note the row of icons at the top of the palette window (Figure 6). Clicking on one of the icons changes the set of items available from that section of the palette. Currently, there are 10 palette icons. In order, they are Menus, Views, Other, Windows, Data, Containers, GraphicsViews, AppleScript, MSFFormatterPalette, and Sherlock. Our focus will be on the third icon from the left, the Other palette. Click on the Other icon and your palette window should look like the one shown in Figure 6.

Click and drag an NSImageView out of the palette window into the window named Window. If you hover your cursor over an item in the palette window, a "tool tip" will appear that tells you the item type. Drag the NSImageView towards the upper-left corner of the Window window until a pair of crossed blue lines appear (see Figure 7).


Figure 7. Dragging an NSImageView onto your main window.

Next, click on the NSImageView icon to select it. 8 grow handles will appear. Drag the lower right grow handle to grow the NSImageView until the crossed blue lines appear as you approach the lower right corner of the window. The net result will be an NSImageView inset in the window about the thickness of a scrollbar on all four sides.

Now, let's bring up an inspector window and customize our NSImageView. Select Show Info from the Tools menu. The NSImageView Info window will appear (Figure 8). The Info window allows you to modify the currently selected object. In this case, we're inspecting our NSImageView object.


Figure 8. The Info window for our NSImageView.

Take a look at Figure 8. Your settings should look like this. Be sure the Editable checkbox is checked. This will enable "drag and drop". In fact, when you take the interface for a spin, try testing the interface with and without the Editable checkbox checked.

Next, select Size from the popup menu and compare your settings to those shown in Figure 9. Note that the Layout Rect fields will not necessarily match. Not to worry. It's just the difference between our window sizes. What's important is the Autosizing settings. To change those, click on the two lines in the inner square till each line turns into a pair of springs. Again, when you test the interface, play with these settings. Try it with one line and one spring, just to see what affect this has.


Figure 9. The NSImageView Info window, this time showing the Size settings.

Testing the Interface

OK, now let's take the interface for a spin. Select Test Interface from the File menu. Your window will appear, with an NSImageView area centered in the window. Click on a picture and drag it to the NSImageView field. The image should appear centered in the window. When you resize the window, the image should resize until it reaches its full size.

Play, play, play. Drag the image back out of the window and onto the desktop. A clipping file should appear. Double-click it and you can view your image directly in the Finder. Cool!

To exit the application, just select Quit from the File menu.

You should now be back in Interface Builder. Select Save from the File menu to save the .nib file. Now go back into Project Builder and run TinyViewer. Notice that TinyViewer appears in the dock as an icon, the main menu is titled "TinyViewer", your window appears, and is fully functional. Very cool!!

    There's a terrific new Cocoa book out there you should definitely check out. It's called Cocoa Programming by Scott Anguish, Erik M. Buuck, and Donald A. Yacktman, published by Sams. You can find it at http://www.devdepot.com/books.html.

    I can't say enough about Cocoa Programming. Chapter 1 has one of the clearest breakdowns of the Mac OS X development universe I've yet read. There's great coverage of Objective C, design patterns, memory management, strings, encoding/decoding, exhaustive coverage of the Cocoa frameworks, and just about anything else you might think of. And there, nestled in Chapter 3 you'll find the Cocoa Programming treatment of an NSImageView app. Great stuff. My highest recommendation.

Till Next Month...

Next month, we'll do more with Interface Builder, including exploring the details of the Info window and customizing the menu bar. See you then...


Dave Mark is a long-time Mac developer and author and has written a number of books on Macintosh development, including Learn C on the Macintosh, Learn C++ on the Macintosh, and The Macintosh Programming Primer series. Be sure to check out Dave's web site at http://www.spiderworks.com.

 
AAPL
$116.36
Apple Inc.
+0.05
MSFT
$48.36
Microsoft Corpora
-0.34
GOOG
$539.50
Google Inc.
+4.67

MacTech Search:
Community Search:

Software Updates via MacUpdate

Cyberduck 4.6 - FTP and SFTP browser. (F...
Cyberduck is a robust FTP/FTP-TLS/SFTP browser for the Mac whose lack of visual clutter and cleverly intuitive features make it easy to use. Support for external editors and system technologies such... Read more
Maya 2015 - Professional 3D modeling and...
Maya is an award-winning software and powerful, integrated 3D modeling, animation, visual effects, and rendering solution. Because Maya is based on an open architecture, all your work can be scripted... Read more
Evernote 6.0.1 - Create searchable notes...
Evernote allows you to easily capture information in any environment using whatever device or platform you find most convenient, and makes this information accessible and searchable at anytime, from... Read more
calibre 2.11 - Complete e-library manage...
Calibre is a complete e-book library manager. Organize your collection, convert your books to multiple formats, and sync with all of your devices. Let Calibre be your multi-tasking digital... Read more
Herald 5.0.1 - Notification plugin for M...
Note: Versions 2.1.3 (for OS X 10.7), 3.0.6 (for OS X 10.8), and 4.0.8 (for OS X 10.9) are no longer supported by the developer. Herald is a notification plugin for Mail.app, Apple's Mac OS X email... Read more
Firetask 3.7 - Innovative task managemen...
Firetask uniquely combines the advantages of classical priority-and-due-date-based task management with GTD. Stay focused and on top of your commitments - Firetask's "Today" view shows all relevant... Read more
TechTool Pro 7.0.6 - Hard drive and syst...
TechTool Pro is now 7, and this is the most advanced version of the acclaimed Macintosh troubleshooting utility created in its 20-year history. Micromat has redeveloped TechTool Pro 7 to be fully 64... Read more
PhotoDesk 3.0.1 - Instagram client for p...
PhotoDesk lets you view, like, comment, and download Instagram pictures/videos! (NO Uploads! / Image Posting! Instagram forbids that! AND you *need* an *existing* Instagram account). But you can do... Read more
SuperDuper! 2.7.3 - Advanced disk clonin...
SuperDuper! is an advanced, yet easy to use disk copying program. It can, of course, make a straight copy, or "clone" -- useful when you want to move all your data from one machine to another, or do... Read more
MacJournal 6.1.5 - Create, maintain, and...
MacJournal is the world's most popular journaling software for the Mac. MacJournal 6 adds a calendar mode that show entries from any journal, geolocation, word count, and progress tracking, as well... Read more

Latest Forum Discussions

See All

Quest for Revenge (Games)
Quest for Revenge 1.0.0 Device: iOS Universal Category: Games Price: $4.99, Version: 1.0.0 (iTunes) Description: The great Kingdom of the west has fallen. The gods ignore the prayers of the desperate. A dark warlord has extinguished... | Read more »
Threadz is a New Writing Adventure for Y...
Threadz is a New Writing Adventure for You and Your Friends Posted by Jessica Fisher on November 21st, 2014 [ permalink ] In the tradition of round-robin storytelling, | Read more »
SteelSeries Stratus XL Hardware Review
Made by: SteelSeries Price: $59.99 Hardware/iOS Integration Rating: 4 out of 5 stars Usability Rating: 4.5 out of 5 stars Reuse Value Rating: 4.25 out of 5 stars Build Quality Rating: 4.5 out of 5 stars Overall Rating: 4.31 out of 5 stars | Read more »
ACDSee (Photography)
ACDSee 1.0.0 Device: iOS iPhone Category: Photography Price: $1.99, Version: 1.0.0 (iTunes) Description: Capture, perfect, and share your photos with ACDSee. The ACDSee iPhone app combines an innovative camera, a powerful photo... | Read more »
ProTube for YouTube (Entertainment)
ProTube for YouTube 2.0.2 Device: iOS Universal Category: Entertainment Price: $1.99, Version: 2.0.2 (iTunes) Description: ProTube is the ultimate, fully featured YouTube app. With it's highly polished design, ProTube offers ad-free... | Read more »
Weather or Not - Reports and Forecasts...
Weather or Not - Reports and Forecasts for your Calendar 1.0.0 Device: iOS iPhone Category: Weather Price: $2.99, Version: 1.0.0 (iTunes) Description: Weather or Not is a beautiful and intuitive way to check the weather and... | Read more »
Sago Mini Road Trip (Education)
Sago Mini Road Trip 1.0 Device: iOS Universal Category: Education Price: $2.99, Version: 1.0 (iTunes) Description: Go for a fun-filled drive with Jinja the cat. Pick a destination, select a vehicle and hit the road. What will Jinja... | Read more »
New Tower Defense Game, Kingdom Rush: Or...
New Tower Defense Game, Kingdom Rush: Origins, is Available Today Posted by Jessica Fisher on November 20th, 2014 [ permalink ] iPad Only App - Designed for the iPad | Read more »
Sunburn! (Games)
Sunburn! 1.0.0 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0.0 (iTunes) Description: Your ship is gone. Your crew is scattered. One option remains. Gather your crew... and jump into the sun. Reunite your... | Read more »
Tapventures Review
Tapventures Review By Jennifer Allen on November 20th, 2014 Our Rating: :: ODDLY COMPELLINGUniversal App - Designed for iPhone and iPad Tapventures is an increasingly hands-off one-tap RPG, but expect it to hook you despite your... | Read more »

Price Scanner via MacPrices.net

Apple Expected to Reverse Nine-Month Tablet S...
Apple and Samsung combined accounted for 62 percent of the nearly 36 million branded tablets shipped in 3Q 2014, according to early vendor shipment share estimates from market intelligence firm ABI... Read more
Stratos: 30 Percent of US Smartphone Owners t...
Stratos, Inc., creator of the Bluetooth Connected Card Platform, has announced results from its 2014 Holiday Mobile Payments Survey. The consumer survey found that nearly one out of three (30 percent... Read more
64GB iPod touch on sale for $249, save $50
Best Buy has the 64GB iPod touch on sale for $249 on their online store for a limited time. Their price is $50 off MSRP. Choose free shipping or free local store pickup (if available). Sale price for... Read more
15″ 2.2GHz Retina MacBook Pro on sale for $17...
 B&H Photo has the 2014 15″ 2.2GHz Retina MacBook Pro on sale for $1799.99 for a limited time. Shipping is free, and B&H charges NY sales tax only. B&H will also include free copies of... Read more
New Logitech AnyAngle Case/Stand Brings Flexi...
Logitec has announced the newest addition to its suite of tablet products — the Logitech AnyAngle. A protective case with an any-angle stand for iPad Air 2 and all iPad mini models, AnyAngle is the... Read more
2013 15-inch 2.0GHz Retina MacBook Pro availa...
B&H Photo has leftover previous-generation 15″ 2.0GHz Retina MacBook Pros available for $1499 including free shipping plus NY sales tax only. Their price is $500 off original MSRP. B&H will... Read more
16GB Retina iPad mini on sale today for $199,...
 Staples has 2nd generation 16GB Retina iPad minis on sale for $199 on their online store for a limited time. Their price is $100 off MSRP. Choose free shipping or free local store pickup (if... Read more
Developers Start Designing Apps for Apple Wat...
Apple has announced the availability of WatchKit, software that gives developers a set of tools to easily create experiences designed specifically for Apple Watch. Apple’s developer community can now... Read more
C Spire Launches iPad Air 2 and iPad Mini 3 o...
C Spire has announced that iPad Air 2 with Wi-Fi + Cellular and iPad mini 3 with Wi-Fi + Cellular are now available on its 4G LTE network. C Spire offers both new iPads with a range of data plans... Read more
Are You On Your Last PC? – The ‘Book Mystique
Will your current PC be your last? Quite possibly so if you define “personal computer” as a traditional desktop or laptop form factor machine according to some commentators. So then, the upshot that... Read more

Jobs Board

*Apple* Solutions Consultant (ASC)- Retail S...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
Project Manager, *Apple* Financial Services...
**Job Summary** Apple Financial Services (AFS) offers consumers, businesses and educational institutions ways to finance Apple purchases. We work with national and Read more
*Apple* Store Leader Program - College Gradu...
Job Description: Job Summary As an Apple Store Leader Program agent, you can continue your education as you major in the art of leadership at the Apple Store. You'll Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
Senior Event Manager, *Apple* Retail Market...
…This senior level position is responsible for leading and imagining the Apple Retail Team's global event strategy. Delivering an overarching brand story; in-store, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.