Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning REALbasic - From Novice To Professional (2006)

.pdf
Скачиваний:
233
Добавлен:
17.08.2013
Размер:
18.51 Mб
Скачать

146

C H A P T E R 5 S T O R I N G A N D R E T R I E V I N G A P P L I C A T I O N D A T A

The following statement demonstrates how to work with string manipulation functions.

Dim strSampleMsg As String =

" A long time ago in

a galaxy far, far away

"

MsgBox(Replace(strSampleMsg,

"galaxy", "universe"))

 

 

MsgBox(Uppercase(strSampleMsg))

MsgBox(Trim(strSampleMsg) + " where no one boldly dared go before!")

Note In the section “Supplying Application Code,” where you’ll supply the program code required to create the RBCalculator application, you have the opportunity to use both the Mid and InStr functions.

The first statement declares a variable name strSampleMsg and assigns it a text string. The second statement uses the Replace function to replace the first occurrence of the string “galaxy” with the string “universe,” found in strSampleMsg before displaying the resulting value of the string in a pop-up dialog. The third statement uses the Uppercase function to convert the value stored in strSampleMsg to all uppercase characters before displaying the resulting string in a pop-up dialog. The last statement uses the Trim function to remove any leading and trailing blank spaces from the value stored in strSamplemsg before appending the variable’s value to another string.

Note When used with two strings, the + character adds together or concatenates the strings to create a new string. Visual Basic programmers should note that, in REALbasic, the + character is used instead of the & character to perform concatenation.

Storing Data in Arrays

The more variables your REALbasic applications have to manage, the more complicated your code becomes. In many cases, data managed by your applications may be closely related. For example, an application might need to collect customer names or IDs. In these cases, you can simplify things by storing data in an array.

An array is an indexed collection of data that can be processed as a unit. Individual pieces of data stored in an array are referred to as elements. The first element in an array is assigned an index number of zero. As each additional piece of data is added to an array, it is assigned an incremental index number. Once loaded, you can reference any piece of data in the array by specifying its index number.

Tip When creating an array name, try to find a name that describes the array’s purpose or contents. For example, an array whose purpose is to hold user names might be named strNamesArray. Note, in this example, a three-letter prefix was added to the beginning of the array name to identify the type of data stored. Also, note, the word “Array” was added to the end of the array name to identify it as an array.

C H A P T E R 5 S T O R I N G A N D R E T R I E V I N G A P P L I C A T I O N D A T A

147

REALbasic supports single dimensional and multidimensional arrays. A single dimensional array is a single list of data, such as a list of grocery items you might write down before visiting the supermarket. A multidimensional array is like a table made up of rows and columns that can be likened to an Excel spreadsheet. Just like variables, you use the Dim keyword to declare arrays. The syntax for declaring an array is outlined in the following.

Dim ArrayName(dimensions) As DataType

ArrayName represents the name of the array. Dimensions is a comma-separated list of numbers that specifies the number of dimensions the array has and the highest-defined element in the array. DataType tells REALbasic what type of data will be stored in the array. For example, the following statement declares a single dimension array that can hold ten elements.

Dim strNamesArray(9) As String

Because the first element in a REALbasic array has an index of 0, the previous examples can store elements using index numbers 0 through 9. The following statement demonstrates how to declare a two-dimensional array.

Dim strNamesArray(4,9) As String

In this example, an array named strNamesArray, which is made up of five rows (0 through 4) and ten columns (0 through 9), was defined.

Tip REALbasic also provides a built-in function called Array, which you can use to quickly set up small arrays. The Array function takes a list of comma-separated values and turns them into an array. For example, the following statements are all that is necessary to define an array named strNamesArray and populate it with five elements.

Dim strNamesArray() As String

strNamesArray = Array("Molly", "William", "Alexander", "Jerry", "Mary")

Loading Data into Arrays

Once an array is defined, you can load data into it. To do so, you specify the index location for each element assigned to the array, as shown here.

Dim strNamesArray(4) As String

strNamesArray(0) = "Molly" strNamesArray(1) = "William" strNamesArray(2) = "Alexander" strNamesArray(3) = "Jerry" strNamesArray(4) = "Mary"

148

C H A P T E R 5 S T O R I N G A N D R E T R I E V I N G A P P L I C A T I O N D A T A

Retrieving Data from Arrays

Once an array is populated with data, you can refer to any element in the array by specifying its index position. For example, the following statement retrieves the value assigned to the third element in the strNamesArray and assigns it to a variable.

Dim strCurrentName As String

StrCurrentName = strNamesArray(2)

Rather than accessing individual array elements one at a time, you can set up a loop that enables you to programmatically process every element in an array. In this way, you can process an array containing dozens, hundreds, or many thousands of elements using a relatively small amount of code, as the following shows.

Dim strNamesArray(4) As String

Dim intCounter As Integer

strNamesArray(0) = "Molly" strNamesArray(1) = "William" strNamesArray(2) = "Alexander" strNamesArray(3) = "Jerry" strNamesArray(4) = "Mary"

For intCounter = 0 To Ubound(strNamesArray)

MsgBox("Now processing " + strNamesArray (intCounter))

Next intCounter

When this example runs, the For…Next loop will read and display the name of each array element one at a time in a series of pop-up dialog windows. Note the use of the Ubound function in the previous example. This function returns the index number of the last element stored in the specified array, which in this example would be 4. The Ubound function is designed to help set up loops that process arrays whose length may not be known in advance. Loops provide the capability to iterate through collections of data-like arrays. More information on the For…Next loop is available in Chapter 7.

Changing the Size of Your Arrays

You may not always know in advance exactly how many elements you need to store in an array. In these circumstances, declaring your array as a null array (or an empty array) is best. You can do this either by specifying a –1 as the array’s index number or by simply not specifying anything at all. For example, both of the following statements are functionally equivalent.

Dim strNamesArray(-1)

Dim strNamesArray()

When defined in this manner, you can wait until later in your application to redefine the array when you know how big it needs to be. You do this using the Redim statement, as the following shows.

Redim strNamesArray(9)

C H A P T E R 5 S T O R I N G A N D R E T R I E V I N G A P P L I C A T I O N D A T A

149

In this example, the strNamesArray is resized to allow it to hold up to ten elements. Once an array is resized, you can begin assigning new elements to it.

Note Visual Basic programmers should take note that in REALbasic, the Redim statement behaves differently than it does in Visual Basic. Unlike Visual Basic, redimensioning an array in REALbasic does not cause the loss of all the elements already defined in it.

Incrementing an Array Size an Element at a Time

In addition to redimensioning an array, REALbasic also lets you dynamically append data to the end of an array without first changing its size. This is accomplished through the Append method, as shown in the following.

strNamesArray.Append "Dolly"

This statement automatically increases the size of the strNamesArray by one and adds a new element to the end of the array. The Append method only works with single-dimension arrays.

Inserting Data into the Middle of an Array

REALbasic also enables you to insert new elements into any index position you choose within an array. This is accomplished by using the Insert method, as the following shows.

strNamesArray.Insert 2, "Dolly"

In this example, a new array element is inserted into the third index position of the array. The previously stored data in the array’s third index position is reassigned to the fourth index position. Likewise, all other data stored above index position 3 automatically have their index number shifted up by one. The Insert method only works with single-dimension arrays.

Deleting Array Elements

REALbasic also provides the capability to selectively remove individual array elements using the Remove method. The Remove method works by deleting the data stored in the specified index position. The following statement demonstrates how to remove the third element from an array.

strNamesArray.Remove 2

Once an element is deleted, all remaining array elements have their index position shifted down by one position. The Remove method only works with single-dimension arrays.

Working with Dictionaries

One drawback of working with arrays is you are limited to accessing array elements only by their index position within the array. REALbasic provides an alternative to arrays in the form of dictionaries. A dictionary is an object made up of key-value pairs. What this means is, in

150

C H A P T E R 5 S T O R I N G A N D R E T R I E V I N G A P P L I C A T I O N D A T A

addition to retrieving items using an index position number, you can also retrieve an item using its associated key. The best way to learn about the dictionary object is to see one in action. The following statements define a dictionary object named strNamesDictionary, and then populate it with data.

Dim strNamesDictionary As New Dictionary strNamesDictionary.Value("Molly") = "Mollisa Lee Ford" strNamesDictionary.Value("William") = "William Lee Ford" strNamesDictionary.Value("Alexander") = "Alexander Lee Ford"

Look at the first statement in the previous list. It uses the Dim keyword to declare the new dictionary object. Notice it also uses the New keyword. The New keyword is required whenever you are creating a new instance of an object. More information about working with objects is available in Chapter 8. The last three statements populate the dictionary object using its Value method. The first argument passed to the Value method is a key, which is followed by the equals sign and the data to be associated with that key. Note, unlike arrays, you needn’t worry about defining the size of your dictionary objects in advance.

Once loaded with data, you can use any of the dictionary object’s properties and methods to access and modify its contents. For example, the following statement uses the dictionary object’s Count property to display the number of items currently stored in the strNamesDictionary dictionary, as Figure 5-3 shows.

MsgBox "There are " + Str(strNamesDictionary.Count) + " key-value pairs in the dictionary"

Figure 5-3. Counting the number of items stored in a dictionary, as shown on Windows

If you want, you can retrieve the value of any element in the dictionary by specifying its index location, as the following shows.

MsgBoxstrNamesDictionary.Value(strNamesDictionary.Key(0))

In this example, the first element stored in the dictionary object is displayed. The real power and convenience of working with a dictionary object is you can work with its data without having to specify index numbers. Instead, you can, for example, retrieve a value from the dictionary by specifying its key, as the following shows.

MsgBox strNamesDictionary.Value("Alexander")

The dictionary object provides a number other helpful methods that you can use to manage its contents. For example, you can use its Remove method to delete a specified element from the dictionary, as the following shows.

strNamesDictionary.Remove("Molly")

C H A P T E R 5 S T O R I N G A N D R E T R I E V I N G A P P L I C A T I O N D A T A

151

Similarly, you could delete all the elements stored in a dictionary using the Clear method, as shown here.

strNamesDictionary.Clear

Note Compared to working with arrays, dictionaries provide a more efficient means of storing large amounts of data. Just as important, if your applications need to process large amounts of data, such as thousands of customer records, the dictionary object provides significantly faster lookup and retrieval when compared to arrays.

Constants

As useful as variables may be for storing individual pieces of data that don’t belong to a specific object, at times, you may want to consider using constants instead. A constant is a known value that does not change during the execution of your application. For example, the value of pi is a perfect example of such a value.

Placing data that does not change in a constant instead of a variable provides you with several advantages. REALbasic can compile your application more efficiently because constants require less memory than variables. In addition, by storing data in a constant instead of a variable, you eliminate the possibility of accidentally changing the value of the data when your application runs.

REALbasic’s Built-In Constants

REALbasic provides your application with access to all sorts of constants. One such constant is DebugBuild. DebugBuild returns a Boolean value of True or False, depending on whether your application is being tested within REALbasic’s IDE or running as a standalone application. By checking the value returned by DebugBuild, you can add code to your applications that executes conditionally based on the current execution environment, as the following shows.

If DebugBuild = True Then //The application is running in the IDE

...

End If

Another constant you may find useful is RBVersion, which returns a number indicating the major and minor version number of REALbasic. This information comes in handy if you are working with REALbasic functionality tied to a specific version of REALbasic. This might be the case if you previously developed REALbasic programs for a previous release of REALbasic that used features no longer supported by the current version of REALbasic. For example, the following statements can be used to display a warning message if you attempt to run a REALbasic application running REALbasic version 5 or later.

If RBVersion > 5 Then

MsgBox "This application uses features not supported after REALbasic 5." End If

152

C H A P T E R 5 S T O R I N G A N D R E T R I E V I N G A P P L I C A T I O N D A T A

Defining Your Own Constants

Like variables, REALbasic constants have different scopes depending on how and where they are defined. Specifically, a constant defined within application code stored in an application’s window has a local scope, whereas a constant stored in windows or classes can have any of the following scopes, depending on how it is defined:

Protected. Accessible only within the window in which it is defined.

Private. Accessible only within the window in which it is defined, but not by any windows subclassed from the window.

Public. Available throughout your application.

Note Classes and subclasses are discussed later in Chapter 8.

In addition, constants defined within a module are global in their scope, allowing them to be accessed throughout an application. More information on modules and classes is available in Chapter 8.

Working with Local Constants

To declare a local constant, you need to use the CONST keyword, which has the following syntax.

Const ConstName = Value

For example, to define the value of pi as a local constant, you could add the following statement to the code belonging to a window or one of its controls.

Const PI = 3.141592

The following provides another example of how to use local constants within your applications.

Dim intResults As Integer

Const cAppName = "The Happy Holiday Calendar"

intResults = MsgBox("Welcome. Click on OK to Continue", 64, cAppName)

Note In the previous example, the name of the constant was preceded with the letter c to label it as a constant. This makes the constant stand out better in your code.

C H A P T E R 5 S T O R I N G A N D R E T R I E V I N G A P P L I C A T I O N D A T A

153

Here, a constant named cAppName is defined and assigned a string of text. The constant is then used to display the name of the application in a pop-up dialog box generated by the MsgBox function, as Figure 5-4 shows. Once defined, a constant can be referred to over and over again.

Figure 5-4. Constants provide a way to define data within your applications that cannot be changed during program execution, as shown on Windows.

Adding a Constant to a Window

Constants defined within a window can have a public, protected, or private scope. The following procedure outlines the steps involved in adding a constant to a window.

Note The procedure you follow to declare a constant within a module and a class is practically identical to the procedure used to declare one within a window. The only difference is this: with modules, your choices for scope are Global, Public, and Protected, instead of Public, Protected, and Private.

1.Open the Code Editor for the appropriate window.

2.Click the Add Constant button or click Project Add Constant. The Add Constant declaration field is displayed.

3.Enter a name, data type, and value for the constant.

4.Click one of the three scope buttons located to the right of the Declaration field, as shown in Figure 5-5.

Figure 5-5. REALbasic lets you select a scope by clicking the Public, Protected, or Private buttons, as shown on Linux.

154

C H A P T E R 5 S T O R I N G A N D R E T R I E V I N G A P P L I C A T I O N D A T A

Reserved Keywords

REALbasic reserves a collection of keyword terms that makes up its programming language. You cannot use these keywords when naming variables, arrays, modules, constants, and so on within your applications. Table 5-2 provides a complete listing of REALbasic’s reserved keywords.

Table 5-2. REALbasic Reserved Keywords

And

Array

As

Boolean

ByRef

ByVal

Call

Case

Catch

Class

Color

Const

DebugPrint

Declare

Dim

Do

Double

Downto

Each

Else

ElseIf

End

Event

Exception

Exit

False

Finally

For

Function

GoTo

Handles

If

Implements

In

Loop

Me

Mod

Module

Namespace

New

Next

Nil

Not

Object

Of

Or

Private

Protected

Public

Raise

ReDim

REM

Return

Select

Self

Shared

Single

Static

Step

String

Sub

Then

To

True

Try

Until

Wend

 

 

 

 

 

 

 

 

 

 

 

Creating a Starter Desktop Calculator

To help further reinforce the information you learned in this chapter, this section shows you how to create a new desktop application called RBCalculator, which is a relatively simple implementation of a desktop calculator. The programming logic required to create a fullfeatured calculator application is too extensive to replicate here. Instead, the programming logic implemented in this application is limited to solving basic addition, subtraction, multiplication, and division, and equations consisting of two numbers.

As a desktop calculator, all key functionality is provided via PushButton controls and an EditField located on the application window. In addition, the application has a small menu system made up of File and Help menus, as Figure 5-6 shows.

C H A P T E R 5 S T O R I N G A N D R E T R I E V I N G A P P L I C A T I O N D A T A

155

Figure 5-6. RBCalculator is a basic desktop calculator application, as shown on Macintosh.

Note As you work your way through the creation of this application, you should be able to follow along and understand the interaction that occurs when the application accesses properties and variables. For pieces of code that have not yet been explained, go ahead and enter them exactly as shown. Once you finish reading Chapter 6, you may want to revisit this example. By that time, you should be ready to take another look at how this application works.

Designing the User Interface

Users interact with the RBCalculator application through PushButton controls placed on the main application window. Calculations and their results are displayed in an EditField control placed at the top of the window. In addition, a small menu system is available that enables the user to close the application or display additional information about it.

To begin the development of this application, open a new project in REALbasic, add the controls listed in Table 5-3, and then modify the window and control properties as shown.

Table 5-3. Window and Property Modifications for the RBCalculator Application

Object

Property

Value

Window1

Name

MainWindow

 

Title

RBCalculator

EditField1

Name

OutputField

 

ReadOnly

Enabled

 

Alignment

Right

 

Bold

Enabled