REALbasic University Resources:

RBU: Glossary Defines common REALbasic programming terms
  Archives Previously published columns
Translations: Dutch Courtesy of Floris van Sandwijk
  Japanese Courtesy of Kazuo Ishizuka
  Chinese Courtesy of Dong Li
  RBU Translation Guide Information on Translating RBU into other languages
Books: Matt's Book (2nd Edition!) Ideal for experienced programmers
  Erick's Book Best for beginning programmers
Websites: Mother Ship The publisher of REALbasic
  RB Webring Links to hundreds of REALbasic websites
  RESExcellence Another REALbasic programming column
  REALbasic Developer Magazine The premiere source for REALbasic instruction.

REALbasic University is Sponsored by

Make your Mac do what YOU want it to. Create games, utilities, cool Mac OS X tricks. Download REALbasic now and create your own software.


Print This Article

REALbasic University: Column 082

OOP University: Part Six

Last time we explored the difference between classes and instances: today we continue that lesson with some practical examples.

A New Way of Seeing Things

Those of you quick on the uptake will realize that our last lesson's explanation of objects makes clear (finally!) one of the most confusing commands offered in REALbasic: the new command.

I'm sure you've noticed how sometimes you must "new" something before it will work (such as new date) while other times you don't have to do that. Why do you sometimes have to do it and not others?

The explanation is simple. Since catObjectClass is a class, it doesn't exist as an object, so new doesn't apply. However, once you've created an instance of catObjectClass, that instance must be "newed" or it won't work. (The new command reserves memory for the object: the object can't exist without a home!)

Thus you'll often find situations where you write code like this:

  
dim mayhemInstance as catObjectClass

mayhemInstance = new catObjectClass
mayhemInstance.legs = 4
mayhemInstance.mammal = true
mayhemInstance.species = "Tabby"
mayhemInstance.theColor = "Yellow"
mayhemInstance.thePicture = mayhem

But here's the kicker: objects dragged to your window have already been "newed" -- that is, REALbasic has gone ahead and taken care of that step automatically. That's why you don't have to "new" a listBox or canvas or other controls you place on windows. (But if you create controls dynamically, you must new them manually.)

In Detail

If window objects weren't instantiated automatically, your program would crash even before the initial window could open, since opening the window would mean looking at the objects on it. Think about it: in order to draw the window, the window must include the objects on it. To do so, it must examine them, and if one of those objects doesn't exist, the window is accessing a non-existent object. So the program immediately crashes with a nilObjectException error. What a pain!

Worse, where would you look to fix this error? After all, it's not caused by a specific line of code. Finding and fixing such a thing would be horrible. Therefore REALbasic automatically handles instantiating ("newing") objects on windows (as well as the windows themselves). But it's up to us to remember to do it in all other cases.

The Cat Object Demo

This week I'm including a simple demo project using the cat structure talked about so far. You'll notice a few differences, but it's generally what I've described. All it does right now is display the appropriate cat's picture when you click on the cat's button.

We'll be extending this project in future lessons. For instance, right now the cats are not very object-oriented: they should know how to draw themselves. We'll be doing that in the future.

Note that by default the project is set to crash when you run it: you must figure out why and fix it! (It's very easy as I explain exactly what to do within comments. :-) But it should help reinforce today's lesson.

If you would like the complete REALbasic project file (including resources), you may download it here.

Instance References

Now the way REALbasic works you might be misled into believing that mayhemInstance (from the previous example) is actually the instance of catObjectClass. In truth, it is not. The instance of the object itself is a structure somewhere in memory. Where is unimportant -- REALbasic handles all the dirty details behind the scenes for you.

The actual variable mayhemInstance isn't really an instance, it's a reference to the instance. What does that mean?

Well, if you're familiar with traditional programming languages, you've probably dealt with pointers. A pointer is simply a reference to a specific location of memory. Remember, to a computer, all memory is the same -- there's simply a long sequential list of memory addresses. Imagine a huge post office with a few million (or billion) P.O. boxes. A pointer is the equivalent of a P.O. box number.

Most programming languages include a pointer data type. REALbasic doesn't seem to, but it really does: any object data type is really just a pointer to that object. That's why objects can be nil -- nil means a nil pointer, a pointer that's pointing at nothing.

Why do I bother to explain this? Because it's important. REALbasic's an awesome language, and the way it hides the ugly details of pointers behind an elegant language is wonderful, but when the metaphor breaks down, it causes problems.

For example, have you ever tried something like this?

  
dim d1, d2 as date

d1 = new date
d2 = new date

if d1 = d2 then
beep
end if

The above code doesn't work, at least not how you're expecting it to work. You're expecting that you can compare two date objects -- but d1 and d2 are not date objects! Remember, they are just references (pointers) to the real objects.

Go back to our P.O. box metaphor. Let's say the system puts the date object referred to by d1 into box number 1074 and the date object referred to by d2 into box number 4383. So what the above code is saying is this:

  
if [pointer to box 1074] equals [pointer to box 4383] then...

Of course that makes no sense at all!

The real way to solve this comparison problem is like this:

  
dim d1, d2 as date

d1 = new date
d2 = new date

if d1.TotalSeconds = d2.totalSeconds then
beep
end if

This works because we're not comparing instance references, but actual scalar data types (doubles).

The problem of confusing instance references with the actual instance of an object is also what causes the following incorrect code:

  
dim object1, object2 as myObject

object1 = new myObject
object2 = new myObject

object1.text = "No text yet"
object2 = object1

Again, the programmer is misunderstanding the way objects work in REALbasic. The references object1 and object2 are not objects -- only pointers. By saying object2 = object1 you aren't copying object1.text to object2.text, you're saying that object2 should point the same P.O. box as object1!

Let's look closer at this with a practical example.

I've created a simple project (you can download it here). It uses a custom class called myClass which contains a single string property called theContents. When the program runs two instances of myClass are instantiated, and the contents of those are drawn within the main window:

Play around with this: when you change the content of a text field on the left and push the corresponding button on the right, that object's contents gets updated.

However, once you click the "Copy" button (which executes a simple anObject2 = anObject1, which does not copy the object only the reference to the object), the updated contents of the instances are always the same.

This happens because there's now only one instance! Before we had two references, each pointing to a different P.O. box (instance). After clicking the "Copy" button there are still two references, but they now point to the same P.O. box (instance)! So the two references appear to have the same contents and act the identically.

In Detail

Did you notice in the above I mentioned there was only one instance? Didn't we start out with two?

Well, yes. But since REALbasic handles all the complicated memory allocation stuff for us behind the scenes, it noticed that as soon as we made the two reference variables the same (both pointing to a single instance) that one instance had nothing pointing at it. There was no reference to that second instance, and therefore no way to access it ever again (remember, you never actually get to see what the P.O. it referred to, all you have is the reference variable itself, and once you change what "P.O. box" it points to the original reference is gone forever). Therefore REALbasic frees up the memory that instance uses by deleting it from memory.

This type of memory management is called "garbage collection" (unreferred-to instances are garbage since they can't be used). You can actually manually tell REALbasic to delete an object simply by setting the only reference to it to nil. But remember, this only works if the reference is the only reference to the object: if other variables or properties refer to the object, the object is still alive and won't be automatically deleted.

For the most part within RBU I'll refer to instance reference as instances. It's just easier that way and it makes sense 90% of the time. Just occasionally, though, like when you assume you can copy one object to another, the metaphor doesn't work, so it's very important that you understand the distinction between an instance reference and an instance.

Whew! Lots of complicated stuff. I hope your brain's catching all this properly. We're just getting to the good stuff.

Next Week

We add actions to our objects!

News

Thanks to Dong Li for managing the Chinese RBU website. Note that it has moved to a new location, so update your bookmarks!

By the way, though I can't read Japanese or Chinese, the sites sure look cool under Mac OS X: instead of gibberish you usually get when visiting a foreign character site, the Japanese and Chinese characters are displayed properly. They look awesome. Check them out!

Letters

Today we've got a simple but intriguing question from Judy. She writes:

Well I have a simple and specific question... I think it should be simple IF I knew the answer ! :)

Here goes... I have been working with REALbasic now for almost a year, and have finished two decent (I think) programs.

So, tonight, after all this time, I realize there are two ways to save a project! (Well, two I am confused about.)

Save as... a REALbasic document (which seems to be the default, so it is what I have done) OR Save as...a standard project (which is what I thought I had been doing all this time)

What on Earth is the difference?

Thanks!

Judy

An intriguing question, Judy! I honestly didn't know the answer, so I asked REAL Software engineer Joe Strout, who's on the REALbasic Developer Editorial Board and frequent contributor, and he had this to say:

"REALbasic Document" just means "the default format." The three lines below the separator in the pop-up are specific formats. And the reader is correct, the default format (i.e. "REALbasic Document") is "Standard Format".

So there you have it!


About the Column
REALbasic University is a weekly instructional column on programming with REALbasic and is brought to you by REALbasic Developer, the magazine for REALbasic programmers.

Each week we answer select reader questions, and we're always open to ideas for future columns. Send your questions to . (Keep your questions simple and specific. General queries like "How do I write my own web browser?" will be neglected.) Your question won't be answered immediately, but will be answered in a future column. (If you don't want your correspondence published, just be sure to indicate that when you write. Otherwise it's fair game.)

About the Author
is an author, philosopher, graphic designer, photographer, film director, soccer fanatic, and programmer (among other things). He writes for MacOpinion, runs his own software company, Stone Table Software, which sells the revolutionary Z-Write word processor, and is Publisher and Editor of REALbasic Developer. He lives in Northern California with his cats, Mischief and Mayhem, and is rapidly running out of free time.

See the REALbasic University Archives


REALbasic University contents ©2001-2004 by Marc Zeedar and REALbasic Developer. All Rights Reserved.

Email This Article - Comment On This Article

.

Reader Specials

Server Racks Online:
Apple Xserve CompatibleServer Racks and Universal Network Racks
42U KVM Switch Solutions:
High-End Mac and Multi-Platform KVM Matrix switching solutions!
Digital Camera Online:
Great prices on Digital Cameras and accessories!
KVM Switches Online:
Great prices on Mac KVM Switches from the leading manufacturers!
LCD Monitors Online:
Great prices on LCD Monitors from the leading manufacturers!
LCD Projectors Online:
Shop online for LCD Projectors from the leading manufacturers!
USB 2.0 Online:
Great prices on USB 2.0 products from the leading manufacturers

Serious Business Software:
Accounting, Sales, Inventory, CRM, Shipping, Payroll & more!

KVM Switch solutions for MACs:
DAXTEN is a KVM switch, KVM extender and monitor splitter specialist for PC, SUN and MAC applications from name brand manufacturers - offices worldwide.

The "Think Different Store: The iPod Accessories Store - iPod cases, iPod mini, iPod photo, speakers, itrip, inMotion, Soundstage and all other iPod accessories

Earn Cash with the ThinkDifferent Store Affiliates Program

Need A Web Site?
Applelinks Web Hosting Starting at 19.95 a Month

iTunes_RGB_9mm

.

iTunes_RGB_9mm

Cool Mac Gear


iPod 1G-2G
iPod 3G
iPod 4G
iPod Mini
PowerBook-iBook
Keyboard Skins
Garageband