TweetFollow Us on Twitter

Nov 97 - Getting Started

Volume Number: 13 (1997)
Issue Number: 11
Column Tag: Getting Started

VerySimpleText, Version 2

by Dave Mark , Copyright1997, All Rights Reserved

Three months ago, the August Getting Started column featured a program called VerySimpleText. We built this first version of VerySimpleText using ProjectBuilder and InterfaceBuilder. We started off by editing the nib file (the first version of VerySimpleText wrapped its entire user interface into a single nib file).

We added a Format submenu to the application's default menu, thus adding a series of powerful font, text, and page manipulation features to VerySimpleText. This was done by dragging a Format menu from the menu palette in the palette window.

We also added a scrollable text area (implemented by the NSScrollView class) to the default application window. We did this by dragging a scrollable text view from the DataViews portion of the palette window. We used the NSScrollView inspector to set the autosizing for this view so the scrollable text view grew and shrank along with its containing window. We used InterfaceBuilder's Test Interface feature to test out the window, making sure it looked and behaved as we wanted it to.

Next, we added an info panel (an about box) to VerySimpleText, along with a menu item to bring up the info panel. We edited an existing menu item (Info Panel...) to create our "About VerySimpleText..." item. We used the NSMenuItem inspector to enable the item (unchecking the disabled checkbox, actually). To create the panel itself, we used the Windows portion of the palette window and dragged out our new window, changing the name of the window instance in the nib window and the window's title in the inspector. We also used the palette window to drag some default text into the new info panel.

Once the about panel was built, we created an AboutPanelController class which brought up the about panel when the "About VerySimpleText..." item was selected. Working in the Classes tab within the nib window, we first subclassed NSObject, then created one outlet (abtWindow) and one action (show:). As a reminder, think of an outlet as a variable or object you want associated with your class. When InterfaceBuilder generates the source code for this class, outlets are declared in the header file as type id. An action is a method. In this case, the show: method will bring up the about panel.

Once we were done with our nib file, we told InterfaceBuilder to generate the source files for this project and to add them to the project.

Our next step was to link the "About VerySimpleText..." menu item to the AboutPanelController so when it was selected, the show: method would get called and the panel would appear. First, we instantiated our newly created AboutWindowController class. The instance appeared in the nib window's Instances tab. We then control-dragged from the "About VerySimpleText..." menu item (it's in the menu itself) to the AboutWindowController instance in the nib window. In the inspector window, we clicked the connect button to establish this link. Now, when the "About VerySimpleText..." item is selected, the AboutWindowController's show: method will be called.

Next, we control-dragged from the AboutWindowController instance to our AboutWindow instance. When the link appeared, we moved to the inspector window and clicked on the abtWindow outlet and clicked the Connect button to establish the link. This links the AboutWindowController's abtWindow variable to the AboutWindow. We added a line to the show: method to bring up the window:

- (void)show:(id)sender
{
	[abtWindow makeKeyAndOrderFront:self];
}

The Model, View, Controller Paradigm

Before we move on to this month's additions to VerySimpleText, I thought it might be useful to talk about the Model, View, Controller paradigm, described in Discovering OpenStep: A Developer Tutorial. The Model, View, Controller paradigm is also known as MVC. MVC originated with Smalltalk-80. It categorizes objects as either models, views, or controllers.

Models are objects that emulate some process or represent some knowledge-base. For example, an Employee object represents the knowledge or data associated with an employee. It is a model of an employee. A waterworks object might model the process of converting waste water to clean water and might include the data associated with that process. In general, a model object does not have a user interface. A model object may be distributable and persistent. A model class may be reusable and portable.

View objects are the user interface of your application. Anything displayed by your application is displayed in a view. For example, a window, editable, static, or scrolling text area, button, and scroll bar are all examples of view objects. View objects have no special knowledge of the data they display. In OpenStep, the Application Kit contains a complete set of view objects, all of them designed independent of any model objects. As is evidenced by the Application Kit, view objects are reusable.

Controller objects are the mediators between model objects and view objects. Typically, you'll have one controller object per window (or, possibly, a single controller for your entire application). Your controller object communicates between a model object and its representative view object. For example, an employeeController might use data from an employee object and use that data to create a visible representation of that employee within a view object. At the application level, a controller object would take care of tasks such as loading nib files and acting as a delegate for a window or application.

Delegates

Delegates allow you to provide methods that get called by a class without actually having to subclass the class. Classes which allow delegates feature a set of delegation methods. For example, the NSWindow class features a delegation method called windowWillClose. In this month's sample program, we're going to create a class called Document which will act as an NSWindow delegate. When the NSWindow object gets ready to close, it first calls the delegate's windowWillClose method (assuming the delegate provides such a method). When we define the Document class, we'll provide a windowWillClose method so you can see how this works. You might want to take a look at the NSApplication and NSWindow classes. Their delegation methods are listed at the end of their respective files.

Loading A Nib File

As you've already seen, every application comes with at least one nib file. The nib file is similar to a Macintosh resource file, though it has much more of an object orientation. In fact, one of the primary things stored in a nib file is a set of archived objects. The information in the nib file includes information about each object (like object size and location). It also reflects the position of each object in the overall object hierarchy as well as details about connections between objects in the hierarchy (connections such as the ones we created in the August version of VerySimpleText).

An important part of the object hierarchy is the File's Owner object. Figure 1 shows VerySimpleText's main nib file with the icon representing the File's Owner object in the upper left corner of the Instances tab. The File's Owner sits at the top of each nib file's archived object hierarchy and comes into play when you want to load a nib file other than the main nib file (which is loaded for you automatically).

Figure 1. VerySimpleText's main nib file, showing the File's Owner object.

This line of code:

[NSBundle loadNibNamed:@"NEXTSTEP_Document" owner:self]

loads a nib file named "NEXTSTEP_Document.nib" and sets the File's Owner of the loaded nib file to point to the specified File's Owner. For example, in this month's sample program, we'll define a Document class and we'll tell InterfaceBuilder that the Document class will act as the File's Owner in "NEXTSTEP_Document.nib". Before the nib file can be loaded, we instantiate a Document object. In the Document's init method, we'll call the method loadNibNamed, passing in the nib file name "NEXTSTEP_Document.nib", as well as the object reference self, which refers to the Document object. This second parameter is used as the newly opened nib file's owner.

And Now, Addint to Verysimpletext

Hopefully, the quick review above brought you back up to speed on the overall structure of the August version of VerySimpleText and gave you enough background to follow this month's changes. This month, we're going to add the ability to handle multiple documents to VerySimpleText. We'll tie this functionality to the Document menu's New item. You'll want to start off with a copy of the August version of VerySimpleText. Be sure to keep a copy of the original around just in case. I named my original folder VerySimpleText.01 and named the copy VerySimpleText.02. Once you've made your copy, open the ProjectBuilder project in the duplicate.

  • Find the file PB.project in the duplicate directory and double-click it to launch ProjectBuilder.
  • Next, we're going to create a new nib file.
  • Click the ProjectBuilder Interfaces item, then double-click the NEXTSTEP_VerySimpleText.01.nib file.
  • The selected nib file will be opened in InterfaceBuilder. Now to create the new file:
  • In InterfaceBuilder, select Document/New Module/New Empty.

A new, untitled nib window will appear (See Figure 2). If you click on the Instances tab, you'll see two instances. One is the File's Owner. If you click on the File's Owner icon, the inspector window (attributes popup) will list a set of classes and the NSObject class will be selected. We'll revisit this a bit later in the column.

Figure 2. The new, untitled nib file.

  • Click on the Classes tab in the new nib window.
  • Select NSObject.
  • Select Classes/Subclass.
  • Rename the new subclass from MyNSObject to Document.
  • Save the new nib file.

You'll name your new nib file as NEXTSTEP_Document.nib (you can leave off the .nib if you like). Be sure to save the new nib file in the same directory as the main nib file, NEXTSTEP_VerySimpleText.01.nib (Figure 3).

Figure 3. Saving the new nib file.

  • When asked, say yes to insert the file in the project.

You will now be in ProjectBuilder.

  • Go back to InterfaceBuilder.
  • Be sure the Document line in the nib file's Classes tab is hilited.
  • Click on the outlet icon (the left of the two icons).
  • Be sure that the Outlets line is highlighted.
  • Select Classes/Add Outlet.
  • Change the outlet name myOutlet to window.
  • Click on the outlet icon to get out of outlet mode.
  • Select Classes/Create Files.
  • When asked whether we want to create a Document.h and .m file, click Yes.
  • When asked to insert files in project, click Yes.
  • We'll be back in Project Builder.

Go back to InterfaceBuilder.

  • Back in the nib window, click on the Instances tab.
  • Click on File's Owner.

In the inspector window, the class NSObject will be selected.

  • Scroll up to Document and select it.

Document will now be highlighted when you click on File's Owner.

  • Bring the original nib file to the front.
  • In the Instances tab, select the MyWindow icon.
  • Select Edit/Cut.
  • When you are asked Do you really want to delete the window?", click Delete.
  • Bring the new nib file to the front.
  • Select Edit/Paste.

The MyWindow icon should appear in the new nib window and the window itself should reappear.

  • Hold down the control key and drag from File's Owner icon to MyWindow icon.
  • When you let go, go to the inspector window and click Connect.

You've just connect MyWindow to the File Owner's outlet (in this case, the Document classes' window variable).

  • In the NEXTSTEP_Document.nib window, control drag from MyWindow to File's Owner.
  • Select the word delegate in the left-hand column.
  • Click the Connect button.

You've just made Document MyWindow's delegate.

  • Select Document/Save.

We are now done with this nib window.

  • Bring the old nib file to the front.
  • Click on the nextstep menu to bring it to the front.
  • Select Tools/Palettes/Palettes.
  • Select the leftmost palette (Menus).
  • Drag a Document menu into the nextstep menu, just below Info

The new Document menu will appear, just to the right of the nextstep menu.

  • In the Document menu, click on New.
  • In the inspector window, select attributes from the popup menu.
  • Click the Disabled checkbox so it is unchecked.
  • In the Document menu, click on Close.
  • In the inspector window, click the Disabled checkbox so it is unchecked.
  • Click on the old nib window and select the Classes tab.
  • Click on NSObject.
  • Select Classes/Subclass.
  • Rename subclass to AppDelegate.
  • Click on action icon (on right).
  • Click on Actions line, select Classes/Add Action.
  • Rename new Action to new:.
  • Click off the Actions icon.
  • Click Classes/CreateFiles.
  • Create the files (answer yes to create files and add to project).

We are now back in ProjectBuilder.

  • Go back to InterfaceBuilder.
  • In the old nib file's classes tab, select AppDelegate line.
  • Select Classes/Instantiate.
  • In the instances tab, control-drag from File's Owner to AppDelegate.
  • In the inspector window, be sure delegate is selected, then click Connect.

We have just marked AppDelegate as the NSApplication delegate. We won't implement any of the NSApplication delegate methods in our AppDelegate code, but we could. Take a look at NSApplication and take a few of the delegation methods for a spin.

  • Go to the nextstep menu and control-drag from New to AppDelegate in the old nib window.
  • In the inspector window, select new from the actions list, then click Connect.

We've just connected the new menu item to the AppDelegate's new: method.

  • Select Document/Save.

OK. That's it for the nib files. Now all we need to do is add a bit of code and we are on our way.

  • Go to ProjectBuilder.
  • Under Classes, select Document.m.

Here's what the code looks like now:

#import "Document.h"

@implementation Document

@end
  • Edit the code so it looks like this:
#import "Document.h"

@implementation Document

- init
{
	//Find the nib and load it in.  This instance will be the
	//File's Owner object, so we pass ourself as owner
	if (![NSBundle loadNibNamed:
					@"NEXTSTEP_Document" owner:self])
	{
		//for whatever reason, we failed.  Clean up and go
		NSLog(@"Failed to load Document.nib");
		[self release];
		return nil;
	}
	return self;
}

//Since the Document is the Windows's delegate,
//it will get the following
//method called whenever the window closes.  
- (void)windowWillClose:(NSNotification *)aNotification
{
	//We remove ourself as the delegate as
	//we are going to release ourselves
	[window setDelegate:nil];
	//Let garbage collection do the actual deletion
	[self autorelease];
}

@end
  • Under Classes, select AppDelegate.m.

Here's what the code looks like now:

#import "AppDelegate.h"

@implementation AppDelegate

- (void)new:(id)sender
{
}

@end

Edit the code so it looks like this:

#import "AppDelegate.h"

@implementation AppDelegate

- (void)new:(id)sender
{
}

@end

Change it to look like this:

#import "AppDelegate.h"
#import "Document.h"

@implementation AppDelegate

- (void)new:(id)sender
{
	//Just instantiate a Document. It will know what to do.
	[[Document alloc] init];
}

@end
  • Click on the hammer icon to bring up the project build window.
  • Click on the hammer again to build the project.
  • When prompted with the Save Modified Files dialog, click Save and build.
  • Assuming the build succeeds, click on the monitor icon to bring up the launch window.
  • Click on the monitor icon in the launch window to run the application.

When the application runs, select Document/New to create new windows.

Till Next Month...

Between delegates, File's Owner, and nib file loading, you've learned a lot this month. Be sure to spend some time looking at NSWindow and NSApplication to get a feel for the power of delegation. This will give you something to chew on until we have releases of Rhapsody and Rhapsody developer tools.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Whitethorn Games combines two completely...
If you have ever gone fishing then you know that it is a lesson in patience, sitting around waiting for a bite that may never come. Well, that's because you have been doing it wrong, since as Whitehorn Games now demonstrates in new release Skate... | Read more »
Call of Duty Warzone is a Waiting Simula...
It's always fun when a splashy multiplayer game comes to mobile because they are few and far between, so I was excited to see the notification about Call of Duty: Warzone Mobile (finally) launching last week and wanted to try it out. As someone who... | Read more »
Albion Online introduces some massive ne...
Sandbox Interactive has announced an upcoming update to its flagship MMORPG Albion Online, containing massive updates to its existing guild Vs guild systems. Someone clearly rewatched the Helms Deep battle in Lord of the Rings and spent the next... | Read more »
Chucklefish announces launch date of the...
Chucklefish, the indie London-based team we probably all know from developing Terraria or their stint publishing Stardew Valley, has revealed the mobile release date for roguelike deck-builder Wildfrost. Developed by Gaziter and Deadpan Games, the... | Read more »
Netmarble opens pre-registration for act...
It has been close to three years since Netmarble announced they would be adapting the smash series Solo Leveling into a video game, and at last, they have announced the opening of pre-orders for Solo Leveling: Arise. [Read more] | Read more »
PUBG Mobile celebrates sixth anniversary...
For the past six years, PUBG Mobile has been one of the most popular shooters you can play in the palm of your hand, and Krafton is celebrating this milestone and many years of ups by teaming up with hit music man JVKE to create a special song for... | Read more »
ASTRA: Knights of Veda refuse to pump th...
In perhaps the most recent example of being incredibly eager, ASTRA: Knights of Veda has dropped its second collaboration with South Korean boyband Seventeen, named so as it consists of exactly thirteen members and a video collaboration with Lee... | Read more »
Collect all your cats and caterpillars a...
If you are growing tired of trying to build a town with your phone by using it as a tiny, ineffectual shover then fear no longer, as Independent Arts Software has announced the upcoming release of Construction Simulator 4, from the critically... | Read more »
Backbone complete its lineup of 2nd Gene...
With all the ports of big AAA games that have been coming to mobile, it is becoming more convenient than ever to own a good controller, and to help with this Backbone has announced the completion of their 2nd generation product lineup with their... | Read more »
Zenless Zone Zero opens entries for its...
miHoYo, aka HoYoverse, has become such a big name in mobile gaming that it's hard to believe that arguably their flagship title, Genshin Impact, is only three and a half years old. Now, they continue the road to the next title in their world, with... | Read more »

Price Scanner via MacPrices.net

B&H has Apple’s 13-inch M2 MacBook Airs o...
B&H Photo has 13″ MacBook Airs with M2 CPUs and 256GB of storage in stock and on sale for up to $150 off Apple’s new MSRP, starting at only $849. Free 1-2 day delivery is available to most US... Read more
M2 Mac minis on sale for $100-$200 off MSRP,...
B&H Photo has Apple’s M2-powered Mac minis back in stock and on sale today for $100-$200 off MSRP. Free 1-2 day shipping is available for most US addresses: – Mac mini M2/256GB SSD: $499, save $... Read more
Mac Studios with M2 Max and M2 Ultra CPUs on...
B&H Photo has standard-configuration Mac Studios with Apple’s M2 Max & Ultra CPUs in stock today and on Easter sale for $200 off MSRP. Their prices are the lowest available for these models... Read more
Deal Alert! B&H Photo has Apple’s 14-inch...
B&H Photo has new Gray and Black 14″ M3, M3 Pro, and M3 Max MacBook Pros on sale for $200-$300 off MSRP, starting at only $1399. B&H offers free 1-2 day delivery to most US addresses: – 14″ 8... Read more
Department Of Justice Sets Sights On Apple In...
NEWS – The ball has finally dropped on the big Apple. The ball (metaphorically speaking) — an antitrust lawsuit filed in the U.S. on March 21 by the Department of Justice (DOJ) — came down following... Read more
New 13-inch M3 MacBook Air on sale for $999,...
Amazon has Apple’s new 13″ M3 MacBook Air on sale for $100 off MSRP for the first time, now just $999 shipped. Shipping is free: – 13″ MacBook Air (8GB RAM/256GB SSD/Space Gray): $999 $100 off MSRP... Read more
Amazon has Apple’s 9th-generation WiFi iPads...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Discounted 14-inch M3 MacBook Pros with 16GB...
Apple retailer Expercom has 14″ MacBook Pros with M3 CPUs and 16GB of standard memory discounted by up to $120 off Apple’s MSRP: – 14″ M3 MacBook Pro (16GB RAM/256GB SSD): $1691.06 $108 off MSRP – 14... Read more
Clearance 15-inch M2 MacBook Airs on sale for...
B&H Photo has Apple’s 15″ MacBook Airs with M2 CPUs (8GB RAM/256GB SSD) in stock today and on clearance sale for $999 in all four colors. Free 1-2 delivery is available to most US addresses.... Read more
Clearance 13-inch M1 MacBook Airs drop to onl...
B&H has Apple’s base 13″ M1 MacBook Air (Space Gray, Silver, & Gold) in stock and on clearance sale today for $300 off MSRP, only $699. Free 1-2 day shipping is available to most addresses in... Read more

Jobs Board

Medical Assistant - Surgical Oncology- *Apple...
Medical Assistant - Surgical Oncology- Apple Hill Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Business Analyst | *Apple* Pay - Banco Popu...
Business Analyst | Apple PayApply now " Apply now + Apply Now + Start applying with LinkedIn Start + Please wait Date:Mar 19, 2024 Location: San Juan-Cupey, PR Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.