Xojo Reference Guide
Xojo Reference Guide
Xojo
Threading
Table of Contents
Xojo Dev Center ......................................................................................................................................... 1
iOS Guide ................................................................................................................................................... 2
Getting Started with iOS ...................................................................................................................... 3
Using the iOS Simulator ................................................................................................................ 9
Launch Images and App Icons .................................................................................................... 11
Device Deployment for Testing .................................................................................................. 15
Submitting to the App Store ....................................................................................................... 19
Migrating to iOS ................................................................................................................................. 21
The New Xojo Framework ......................................................................................................................... 27
Reference Guide ....................................................................................................................................... 30
Language ........................................................................................................................................... 31
Commands ................................................................................................................................. 32
AddHandler .......................................................................................................................... 33
Array .................................................................................................................................... 35
As ........................................................................................................................................ 37
Assigns ................................................................................................................................ 38
ByRef ................................................................................................................................... 39
ByVal ................................................................................................................................... 40
Break ................................................................................................................................... 41
Call ...................................................................................................................................... 42
Case .................................................................................................................................... 43
Catch ................................................................................................................................... 44
Const ................................................................................................................................... 45
Continue .............................................................................................................................. 47
End ...................................................................................................................................... 48
CurrentMethodName ........................................................................................................... 49
Declare ................................................................................................................................ 50
iOS Declare Example Projects ...................................................................................... 53
OS X Declare Samples .................................................................................................. 54
Windows Declare Samples ........................................................................................... 56
Dim ...................................................................................................................................... 57
Do ........................................................................................................................................ 59
Do...Loop ............................................................................................................................. 60
DownTo ............................................................................................................................... 63
Each .................................................................................................................................... 64
Exit ...................................................................................................................................... 65
False .................................................................................................................................... 67
Finally .................................................................................................................................. 68
For ....................................................................................................................................... 69
For...Next ............................................................................................................................. 70
For Each...Next .................................................................................................................... 73
Global .................................................................................................................................. 76
If .......................................................................................................................................... 78
Else ...................................................................................................................................... 79
Page
Threading
ElseIf .................................................................................................................................... 80
If...Then...Else ...................................................................................................................... 81
In ......................................................................................................................................... 83
Lib ....................................................................................................................................... 84
Loop .................................................................................................................................... 85
Me ....................................................................................................................................... 86
Next ..................................................................................................................................... 87
Nil ........................................................................................................................................ 88
Optional ............................................................................................................................... 90
ParamArray ......................................................................................................................... 91
Raise ................................................................................................................................... 92
RaiseEvent .......................................................................................................................... 93
ReDim .................................................................................................................................. 94
Rem ..................................................................................................................................... 95
RemoveHandler ................................................................................................................... 96
Return ................................................................................................................................. 98
Select ................................................................................................................................ 100
Select...Case ...................................................................................................................... 101
Self .................................................................................................................................... 103
Soft .................................................................................................................................... 104
Static ................................................................................................................................. 105
Step ................................................................................................................................... 107
Super ................................................................................................................................. 108
Then .................................................................................................................................. 109
To ...................................................................................................................................... 110
True ................................................................................................................................... 111
Try ..................................................................................................................................... 112
Try...Catch ......................................................................................................................... 113
Until ................................................................................................................................... 115
Using ................................................................................................................................. 116
Wend ................................................................................................................................. 118
While ................................................................................................................................. 119
While...Wend ..................................................................................................................... 120
Compiler Constants .................................................................................................................. 122
Conditional Compilation ........................................................................................................... 124
Data Types ............................................................................................................................... 125
Arrays ................................................................................................................................ 126
Auto ................................................................................................................................... 133
Boolean ............................................................................................................................. 135
Color .................................................................................................................................. 136
Currency ............................................................................................................................ 138
Double ............................................................................................................................... 140
Single ................................................................................................................................ 143
Integer ............................................................................................................................... 145
Structure ........................................................................................................................... 149
Text ................................................................................................................................... 150
Advanced Data Types ........................................................................................................ 166
Page
Threading
CFStringRef ................................................................................................................
CString .......................................................................................................................
Delegate .....................................................................................................................
Ptr ...............................................................................................................................
WString .......................................................................................................................
Literals ......................................................................................................................................
Operators .................................................................................................................................
Addition (+) .......................................................................................................................
AddressOf ..........................................................................................................................
And ....................................................................................................................................
CType ................................................................................................................................
Division (/) .........................................................................................................................
Division, Integer () .............................................................................................................
Equals (=) ..........................................................................................................................
Not Equals .........................................................................................................................
Exponentiation (^) ............................................................................................................
If ........................................................................................................................................
Greater Than .....................................................................................................................
Is .......................................................................................................................................
IsA .....................................................................................................................................
Less Than ..........................................................................................................................
Mod ...................................................................................................................................
Multiplication (*) ................................................................................................................
New ...................................................................................................................................
Not .....................................................................................................................................
Or ......................................................................................................................................
Subtraction (-) ...................................................................................................................
Xor .....................................................................................................................................
WeakAddressOf .................................................................................................................
Operator Overloading ........................................................................................................
Pragma Directives ....................................................................................................................
Reserved Words .......................................................................................................................
Framework ......................................................................................................................................
Exceptions ................................................................................................................................
FunctionNotFoundException ..............................................................................................
NilObjectException ............................................................................................................
ObjCException ...................................................................................................................
OutOfBoundsException ......................................................................................................
OutOfMemoryException ....................................................................................................
RuntimeException .............................................................................................................
StackOverflowException ....................................................................................................
TypeMismatchException ....................................................................................................
iOS Framework .........................................................................................................................
iOSApplication ...................................................................................................................
iOSBitmap .........................................................................................................................
iOSBlock ............................................................................................................................
iOSButton ..........................................................................................................................
167
168
169
171
174
175
177
179
180
181
183
185
186
188
190
192
193
194
196
197
199
201
203
204
206
208
210
212
214
215
223
225
226
227
228
229
230
231
232
233
235
236
237
240
242
244
246
Page
Threading
iOSCanvas .........................................................................................................................
iOSControl .........................................................................................................................
iOSEventInfo ......................................................................................................................
iOSFont ..............................................................................................................................
iOSGraphics .......................................................................................................................
iOSHTMLViewer .................................................................................................................
iOSImage ...........................................................................................................................
iOS Image Formats .....................................................................................................
iOSImageView ...................................................................................................................
iOSLabel ............................................................................................................................
iOSLayoutConstraint ..........................................................................................................
iOSLine ..............................................................................................................................
iOSMessageBox .................................................................................................................
iOSOval ..............................................................................................................................
iOSPath ..............................................................................................................................
iOSProgressBar ..................................................................................................................
iOSProgressWheel .............................................................................................................
iOSRectangle .....................................................................................................................
iOSScreen ..........................................................................................................................
iOSScreenContent .............................................................................................................
iOSSegmentedControl .......................................................................................................
iOSSegmentedControlItem ................................................................................................
iOSSeparator .....................................................................................................................
iOSSound ...........................................................................................................................
iOSSlider ............................................................................................................................
iOSSplitContent .................................................................................................................
iOSSplitView ......................................................................................................................
iOSSwitch ..........................................................................................................................
iOSTabBar .........................................................................................................................
iOSTabContent ..................................................................................................................
iOSTable ............................................................................................................................
iOSTableCellData ...............................................................................................................
iOSTableDataSource ..........................................................................................................
iOSTextArea ......................................................................................................................
iOSTextField ......................................................................................................................
iOSToolbar .........................................................................................................................
iOSToolButton ....................................................................................................................
iOSUserControl ..................................................................................................................
iOSView .............................................................................................................................
iOSViewController ..............................................................................................................
SQLiteDatabase .................................................................................................................
Example Projects ........................................................................................................
SQLiteDatabaseField .........................................................................................................
SQLiteException ................................................................................................................
SQLiteRecordSet ................................................................................................................
Xojo ..........................................................................................................................................
Core ...................................................................................................................................
248
251
254
256
260
270
271
274
276
278
280
284
285
287
288
293
295
296
297
298
299
301
303
304
306
308
309
311
312
314
315
322
324
325
327
330
332
337
338
345
346
351
352
355
356
359
361
Page
Threading
Date ............................................................................................................................
DateInterval ...............................................................................................................
Dictionary ...................................................................................................................
DictionaryEntry ...........................................................................................................
Iterable .......................................................................................................................
Iterator .......................................................................................................................
Locale .........................................................................................................................
MemoryBlock ..............................................................................................................
MutableMemoryBlock .................................................................................................
Point ...........................................................................................................................
Rect ............................................................................................................................
Size .............................................................................................................................
StackFrame ................................................................................................................
TextEncoding ..............................................................................................................
Timer ..........................................................................................................................
TimeZone ...................................................................................................................
WeakRef .....................................................................................................................
Exceptions ..................................................................................................................
BadDataException ...............................................................................................
ErrorException .....................................................................................................
InvalidArgumentException ..................................................................................
IteratorException .................................................................................................
LogicException ....................................................................................................
UnsupportedOperationException .........................................................................
Crypto ................................................................................................................................
CryptoException .........................................................................................................
Data ...................................................................................................................................
InvalidJSONException .................................................................................................
Introspection .....................................................................................................................
AttributeInfo ...............................................................................................................
ConstructorInfo ...........................................................................................................
MemberInfo ................................................................................................................
MethodInfo .................................................................................................................
ParameterInfo .............................................................................................................
PropertyInfo ................................................................................................................
TypeInfo .....................................................................................................................
IO .......................................................................................................................................
BinaryStream .............................................................................................................
FolderItem ..................................................................................................................
IOException ................................................................................................................
SpecialFolder ..............................................................................................................
TextInputStream .........................................................................................................
TextOutputStream ......................................................................................................
Math ..................................................................................................................................
Net .....................................................................................................................................
HTTPSocket ................................................................................................................
NetException ..............................................................................................................
362
369
371
376
378
379
381
384
391
397
401
405
407
408
412
416
417
419
419
420
422
423
424
425
426
430
431
433
434
435
437
439
441
443
444
446
449
450
456
461
462
464
467
470
478
479
482
Page
Threading
SSLSettings ................................................................................................................
TCPSocket ..................................................................................................................
System ..............................................................................................................................
Threading ..........................................................................................................................
CriticalSection ............................................................................................................
IllegalLockingException ..............................................................................................
Semaphore .................................................................................................................
Thread ........................................................................................................................
483
485
488
490
491
492
493
494
Page
Popular Topics
Reference Guide
Data Types
iOS Framework
Xojo.Core
Xojo.Crypto
Xojo.Data
Xojo.Introspection
Xojo.IO
Xojo.Math
Xojo.Net
iOS Info
Videos
iOS QuickStart
iOS Overview
Xojo Framework
Creating an iOS App
Deploying iOS Apps
Hour of Code with iOS
Questions?
Ask the Community
forum.xojo.com
Documentation
Contact Paul
Technical Support
Contact Jason
Licensing/Purchasing
Contact Alyssa
Page 1
iOS Guide
This section contains topics about creating iOS apps with Xojo.
Getting Started with iOS
Using the iOS Simulator
Launch Images and App Icons
Device Deployment for Testing
Submitting to the App Store
Migrating to iOS
The New Xojo Framework
You can also watch these videos about Xojo iOS development
iOS QuickStart
iOS Overview
Hour of Code with iOS
Page 2
iOS Guide
App: The Application object works similarly to how it works for desktop and web projects. In the App Inspector,
you can set the Screen to use for iPhone and iPad-sized devices. Leave a device screen blank if you do not want
it to have a native UI for the device. For example, to prevent an app from working on iPhone, do not assign an
iPhone Screen. If you do not want the app to run natively on an iPad, leave off an iPad Screen. The app will still
run on the iPad, but will do so in the OS "scaled" mode.
iPhoneScreen: Specifies the intial screen display when the app is started on iPhone-sized devices.
iPadScreen: Specifies the initial screen display when the app is started on iPad-sized devices.
View1: This the main layout where you place controls. It is roughly equivalent to a Window or WebPage in
desktop and web projects.
App Icon: This folder is where you place the various size app icons for the app. Use the ImageMaker utility to
create and name the files.
Launch Images: This folder contains the various size launch images for the app. Launch images are used kind of
like a "splash screen" while the app is actually launching. Typically these are screen shots of your empty View
so that it makes it look like your app is starting quickly, but they can be almost anything. There are a variety of
sizes for all the devices. In particular, the iPhone 5 size is required in order for an iOS app to fill the screen on
iPhone 5 and larger devices.
Screens
You can change the preview mode for the screen by using the toolbar buttons to change the orientation (portrait or
Page 3
iOS Guide
landscape) and the device type. These settings affect the preview only and do not affect how the app runs.
The Inspector for a Screen has two sections of importance: Screen Layout and Supported Orientations.
The Screen Layout setting allows you to specify the Content property, which determines how the display looks and
works. There are three choices: View, Split and Tabs.
View
By default, Screen Layout simply points to View1. This is the view that will be displayed on the screen, filling it
entirely.
Split
A Split layout (SplitView) allows you to split the screen into two sections (a master on the left and a detail on the
right). Each of these sections is its own View. This layout is only available on iPad-sized devices running in landscape
orientation. The Mail app included with iOS is an example of a SplitView in action. It displays the email messages on
the left and the selected message in the detail area on the right. You can also have each section of a Split be a Tab.
Tabs
Much like with a desktop app, the tabs layout allows you to have multiple views that the user can select by using the
tab control. In the case of iOS apps, the tab control is displayed at the bottom of the screen. For an example, the iOS
Clock app uses tabs at the bottom to select the type of clock you want to use. Use the Edit button for the Tabs
property to add or remove tabs. Use the Tab Content property to specify the initial View to display in each tab. You'll
need to click on each tab on the Screen to change the tab so that you can set the Tab Content property for it.
Views
Views are where you design the layout of the iOS screen by adding controls. This is similar to a Window in desktop
Page 4
iOS Guide
projects or a WebPage in web projects. You simply drag controls from the Library onto the View, positioning them as
appropriate. Note that iOS uses a feature called Auto-Layout to determine how the controls move on the screen as
the device size changes. Auto-Layout is discussed in more detail below.
Add event handlers to the controls the same way you do in desktop and web projects: choose the "+" button in the
Layout Editor toolbar and select "Add Event Handler".
The Behavior section of the View Inspector has three properties you can use: BackButtonTitle, Title and
TitleBarVisible.
The BackButtonTitle is the title that appears on a subsequent view to get back to this view. For example, if this view
contains Notes, then you might set BackButtonTitle to "Notes" so that if a later view displays details for a note, its
back button will show "Notes" instead of just "Back".
The Title property is the title of the view. The Title and BackButton are only displayed if the TitleBarVisibleProperty is
ON (True).
Auto-Layout
Auto-Layout is a new way specify how controls appear on the layout. It consists of a collection of rules that allow you
to specify controls in relationship to other controls, making it possible to have layouts that work in all these
situations:
Different device screen sizes
Changing device orientations
Language translations
User-specific settings such as font size
OS changes such as control sizes, fonts and spacing
Without Auto-Layout, you typically would have to create multiple UI screens to account for different possibilities and
then also add code to handle other situations. With AutoLayout, you can more easily design a single UI whose
controls have contraints that allow them to adjust for the above situations.
For example, the Auto-Layout rules for a button could indicate the following:
the Left margin of the button should match the Left margin of the TitleLabel control (at the same scale with no
offset)
The Top of the button should be 10 points below the bottom of NoteTitleField (at the same scale).
The Height is fixed at 40 points
The Width is fixed at 100 points
Should you adjust the layout to change the position of TitleLabel or NoteTitleField, the button will be repositioned on
the screen as defined by the rules. This is handy when designing you layout, but is even more important when you
want your layouts to appropriately use the available screen area of the many different size iOS devices.
Page 5
iOS Guide
Some Auto-Layout rules are set for you automatically as you move and drag the control on the layout. But you can
also set any of the rules manually. To edit a rule, click on its name and then click the Edit button. To add a new rule,
click the "+" button and choose the rule from the list.
The following Auto-Layout rules can be added, although not all controls have every rule available:
Left: The left position of the control.
Right: The right position of the control.
Top: The top position of the control.
Bottom: The bottom position of the control.
Horizontal Center: The centered horizontal position for the control.
Vertical Center: The centered vertical position for the control.
Width: The width of the control.
Height: The height of the control.
Baseline
Leading
Trailing
You do not need to specify every rule for a control. In fact, sometimes that would be confusing. For example, if you
specify a Left and Right rule for a control, then also specifying a Width is not necessary.
Auto-Layout Rules
Each Auto-Layout rule has the following properties that can be set:
Is (Equal To, Min or Max)
Relative To (None, Containing View, TopLayoutGuide, BottomLayoutGuide or any other control on the layout)
Edge (None, Left, Right, Top, Bottom, Horizontal Center, Vertical Center, Width, Height, Leading, Trailing,
Baseline, Top Constraint, Bottom Constraint)
Scale %: The percentage of the Edge property to use.
Offset (points): The offset to use with the Edge property.
Priority (Low, Auto, Manual, High, Required): Specifies the importance of the Auto-Layout rule.
This picture gives you an idea of how the various Edge settings are used:
Page 6
iOS Guide
In left to right writing systems Left is the same as leading and Right is the same as trailing. In right
to left writing systems, like Arabic, Right is Leading and Left is trailing as the normal flow of layout
is from right to left or from the leading edge to the trailing edge.
Examples/iOS/Auto-Layout/LayoutConstraintExample
Examples/iOS/Auto-Layout/NoCodeProportionalSpaced
New Framework
The iOS framework is all-new, but it should feel familiar if you've created desktop or web apps. There are two main
sections for the iOS framework. There is the iOS Framework itself, which contains all the iOS controls and other iOSspecific classes available to you. Some of the items available include: iOSButton, iOSTable, iOSCanvas, etc.
There is also the Xojo framework which contains other classes (which will eventually be available across all Xojo
targets). The Xojo framework contains classes such as Dictionary and TCPSocket. Everything in the Xojo framework
is grouped into a collection of namespaces, which helps make it easier to find things based on their functionality.
However, you do not really have to worry about the namespaces in iOS projects. By default the Shared Build Setting
"Simple Preferences" is set to ON which means you can just refer to things by their class name, such as Dictionary
instead of Xojo.Core.Dictionary.
The Xojo Framework namespaces are: Core, Crypto, Data, Introspection, IO, Math and Net. Expect many additions to
this framework in upcoming releases.
You can read all about the iOS and Xojo frameworks in the Reference Guide.
In addition, there are a few other key points to mention:
Text: There is a new data type, called Text, for dealing with text. It replaces the String data type you may have
previously used.
Exceptions: The Xojo framework raises exceptions for error situations rather than setting error codes.
Example Projects
I encourage you to try out each of the example projects included in the iOS folder to get a feel for how all this works.
And check the examples with each Beta, as new examples will be added often. There are examples that show how
Page 7
iOS Guide
Page 8
The easiest way to install Xcode is to download it from the Mac App Store. Before you try to use the iOS Simulator
with Xojo, you should be sure to start Xcode at least once so that you can agree to its license screen and install
necessary components. If you do not do that, then the iOS Simulator will not start. However, you do not need to
keep Xcode running in order to use the iOS Simulator.
To run your iOS app in the iOS Simulator, you simply click the Run button on the Xojo toolbar. By default, your app
will run on an iPhone 4S, but you can change the type of device in the Simulator Device property in the Inspector for
the iOS Build Setting. Note that for iPhone 5 and larger, you will also want to have the appropriate Launch Images in
place in order for you app to use the entire screen.
When you run the app in the SImulator, you have full access to the Xojo debugger. Breakpoints will stop at the line
of code and everything should work the way you would expect.
Running in the Simulator is fast and convenient, but you should also always test your apps on actual devices. Some
differences when running in the Simulator include:
Page 9
Apps built for the Simulator use the x86 compiler, not the ARM compiler.
Not all device features are available in the Simulator.
Keyboard may work differently in the Simulator.
You may have noticed that the iOS entry in Build Settings has a built step called "Sign". This build step is
used when you build your iOS apps for deployment. You cannot change its properties and you should not
remove it.
Two Finger
Drag
1. Place the pointer where you want the two-finger drag to occur.
2. Hold down the Option key.
3. Move the circles that represent finger touches to the start position.
4. Move the center of the pinch target by holding down the Shift key, moving the circles to the
desired center position, and releasing the Shift key.
5. Hold down the Shift key and the mouse button, move the circles in the direction you want to
drag, and release both the Shift key and the mouse button.
Pinch
Rotate
Page 10
Launch Images
A Launch Image is a placeholder image that appears while the app is loading. When you create a new iOS project,
an empty Launch Images folder is added to your project. You can add your own images to the folder (use PNG), but
the sizes and names must match exactly. You can also use the ImageMaker tool to create new launch images (in
different colors) for inclusion in your projects (see below).
The table below describes all the various launch image sizes.
Pixel Size
Device
Scale
Orientation
Filename
640x960
iPhone
2x
Portrait
iPhonePortrait2x
640x1136
iPhone
2x
Portrait
iPhone5Portrait
750x1334
iPhone
2x
Portrait
iPhone6Portrait
1242x2208
iPhone
3x
Portrait
iPhone6PlusPortrait
2208x1242
iPhone
3x
Landscape
iPhone6PlusLandscape
768x1024
iPad
1x
Portrait
iPadPortrait
1536x2048
iPad
2x
Portrait
iPadPortrait2x
1024x768
iPad
1x
Landscape
iPadLandscape
2048x1536
iPad
2x
Landscape
iPadLandscape2x
You must include the iPhone5Portrait size launch image if you want your app to launch in full
screen on an actual iPhone 5-sized device (including 5c, 5s and some iPod touch models). Without
this image, the app will have black bars at the top and bottom when run on iPhone 5, 6 and 6 Plus
screen sizes.
The Launch Images folder must be at the top level of your iOS project.
For more information, refer to the iOS HIG on Launch Images from Apple.
App Icons
There are also a wide variety of app icon sizes for the various iOS devices. When you create a new iOS project, an
empty App Icons folder is created. You can put your app icons in this folder. As with launch images, the icons have
to have very specific sizes, be PNG files and have specific names. You can use the ImageMaker tool to create all the
icon files for you from a single image or you can create them yourself (see below).
The table below describes all the various app icon sizes.
Pixel Size
Device
Scale
Point Size
Filename
58x58
iPhone
2x
29x29
iPhone29
87x87
iPhone
3x
29x29
iPhone293x
Page 11
80x80
iPhone
2x
40x40
iPhone40
120x120
iPhone
3x
40x40
iPhone403x
120x120
iPhone
2x
60x60
iPhone60
180x180
iPhone
3x
60x60
iPhone603x
29x29
iPad
1x
29x29
iPad29
58x58
iPad
2x
29x29
iPad292x
40x40
iPad
1x
40x40
iPad40
80x80
iPad
2x
40x40
iPad402x
76x76
iPad
1x
76x76
iPad76
152x152
iPad
2x
76x76
iPad762x
ImageMaker Tool
The ImageMaker tool included with Xojo can be used to quickly create all the file sizes you need for your App Icon
and Launch Images.
On the App Icons tab, choose the icon image to scale to the other sizes. For best results, select an icon that is
180x180 or larger. Then select the icons sizes you want and click the Create Icons buttons. The tool will create a
folder containing the icon files that you can then drag into your iOS project.
Page 12
Creating Launch Images works similarly, but only a blank image of the selected color is created. These can serve as
placeholders that you can update in image editing software if necessary. Simply choose the color for the launch
image, the sizes you want and click Create Launch Images to get a folder that you can drag into your iOS project.
Page 13
Page 14
3. Add the Apple ID you used for your iOS developer account.
4. Select the account for the Apple ID and click the "View Details" button.
5. Click the "+" button and select "iOS Development" to request and create necessary certificates.
6. Click the Refresh button at the bottom of this window to load other files.
2. Add your devices to the Devices section. Click on "All" in the Devices section and then click "+" to add the
device. You'll need to supply the UDID any devices you want to deploy to. This UDID is displayed in the Xcode
Devices window (Windows->Devices) where you can copy it to the clipboard.
Page 15
With the devices added, you can now request the provisioning proflie from Xcode, which will also create a default
wildcard App ID.
1. Go back to Xcode Preferences and select your account, click "View Details" and then Refresh. This loads the
provisioning profile for Xcode, which is usually called "iOSTeam Provisioning Profile" and followed by the
wildcard App ID. You may be prompted by Xcode to request a distribution certificate, but you can click Cancel
on that for now.
2. Wildcard App IDs are typically of the form "com.company.*". If you are having trouble getting Xojo to
recognize the provisioning profile, you may want to instead create a wildcard ID of just "*".
5. In the dialog, click "+" and select the profile file that you just downloaded.
6. Click Done.
If you would rather use Apple Configurator instead of Xcode, you can click the "Install Profiles" button on the Prepare
Settings screen to add the profile you downloaded and then click the Prepare button.
Page 16
4. Click the "+" button (In the Installed Apps section) and select the app you previously built (or drag the app into
the Installed Apps section). This immediately installs it on the iOS device.
5. On the device, tap on the app to launch it.
Page 17
Apple TestFlight
For iOS 8 apps, you can also use the new TestFlight service from Apple to more easily deploy beta builds to a large
number of testers. For more information:
Page 18
Identifiers
This step is optional, since you can use the same App ID you have used for device deployments.
Log in to the iOS Developer Center at http://developer.apple.com.
Select "Certificates, Identifiers & Profiles" in the iOS Developer Program sidebar.
In the Identifiers section, click App ID and then the "+" to register a new Application ID. It is easiest to specify a
"Wildcard App ID" of the format "com.mycompany.*", which can be used with all your apps.
Click Continue and then Submit.
Now you can create your Distribution Provisioning Profile.
In Xojo, set "Build for App Store" property to ON in the iOS Build Settings. Note: This setting is always set to
False when the project is opened.
Select the appropriate Code Signing team and optionally specify any entitlements (as a plist file).
Verify that the bundle ID matches your wildcard app ID. For example if your wildcard ID is "com.mycompany.*",
then your bundle ID must start with "com.mycompany" and be followed with the app name. So a final bundle ID
Page 19
might be "com.mycompany.myapp".
In Shared Build Settings, ensure that all version fields are correct and that "Short Version" has a value. If you
have to submit an update to the App Store, you will need to increase the version information.
Click Build. This creates an IPA (iOS App Archive) file.
iTunes Connect
If you have not already created the app details in iTunes Connect, you'll need to go do that now.
Upload App
When everything is filled out, you are now ready to upload the build you created.
Launch Application Uploader (from Xcode, in the Xcode menu, select Open Developer Tools->Application
Loader).
Follow the steps to select the IPA file and send it to iTunes connect for verification.
If there were errors, you'll need to correct them and resubmit. Don't forget to update the version information!
Page 20
iOS Guide
Migrating to iOS
The Xojo programming language (commands and core data types) is largely the same with only a few changes.
But iOS uses an all-new framework. This means existing Xojo code you have in desktop or web apps will not be able
to work as-is. This section provides information that will help you understand the new framework and how it
resembles the older framework.
Controls
This is a list of common desktop and web controls along with the equivalent iOS control.
Desktop Control
Web Control
iOS Control
Application
WebApplication
iOSApplication
PushButton
WebButton
iOSButton
Picture
WebPicture
iOSBitmap, iOSImage
Canvas
WebCanvas
iOSCanvas
Graphics
WebGraphics
iOSGraphics
HTMLViewer
WebHTMLViewer
iOSHTMLViewer
ImageWell
WebImageView
iOSImageView
Label
WebLabel
iOSLabel
Line
iOSLine
Oval
iOSOval
Page 21
iOS Guide
Desktop Control
Web Control
iOS Control
ProgressBar
WebProgressBar
iOSProgressBar
ProgressWheel
WebProgressWheel
iOSProgressWheel
Rectangle
WebRectangle
iOSRectangle
SegmentedControl
WebSegmentedControl
iOSSegmentedControl
Separator
WebSeparator
iOSSeparator
Sound
iOSSound
Slider
WebSlider
iOSSlider
CheckBox
WebCheckBox
iOSSwitch
TabPanel
iOSTabBar
ListBox
WebListBox
iOSTable
TextArea
WebTextArea
iOSTextArea
TextField
WebTextField
iOSTextField
Window
WebPage
iOSView
iOSSplitView
Timer
WebTimer
Xojo.Core.Timer
Toolbar
WebToolbar
iOSToolbar
Framework Classes
Classic Framework Class
Date
Xojo.Core.Date
Dictionary
Xojo.Core.Dictionary, Xojo.Core.DictionaryEntry
MemoryBlock
Xojo.Core.MemoryBlock
Xojo.Core.MutableMemoryBlock
Realbasic.Point
Xojo.Core.Point
Realbasic.Rect
Xojo.Core.Rect
Realbasic.Size
Xojo.Core.Size
Thread
Xojo.Threading.Thread
Timer
Xojo.Core.Timer
WeakRef
Xojo.Core.WeakRef
Page 22
iOS Guide
Crypto
Xojo.Crypto
Introspection
Xojo.Introspection
BinaryStream
Xojo.IO.BinaryStream
FolderItem
Xojo.IO.FolderItem
SpecialFolder
Xojo.IO.SpecialFolder
TextInputStream
Xojo.IO.TextInputStream
TextOutputStream
Xojo.IO.TextOutputStream
Xojo.Math
HTTPSocket
Xojo.Net.HTTPSocket
TCPSocket
Xojo.Net.TCPSocket
String to Text
In iOS projects, you use the Text data type as a replacement for String. Text is a modern replacement for String,
which did not require an encoding. By using Text instead of String, you can be assured that your text data always
has a known encoding and is never treated as just a collection of raw data. All classes, methods and properties in
the Xojo framework use the Text type.
In non-iOS projects, you can convert Text data to a String, if necessary, simply by assigning the Text value to a
String like this:
Dim t As Text = "Hello"
Dim s As String = t
You can also convert a String to a Text:
Dim s As String = "Hello"
Dim t As Text
t = s.ToText
String-related methods are now accessible through the Text type with some methods being renamed.
Asc
Text.Codepoints
Chr
Text.FromUnicodeCodepoint
Page 23
iOS Guide
EndOfLine
&uA
Text.FromUnicodeCodepoint(10)
InStr
Text.IndexOf
Join
Text.Join
Left
Text.Left
Len
Text.Length
Mid
Text.Mid
NthField
Text.Split
Replace/ReplaceAll
Text.Replace, Text.ReplaceAll
StrComp
Text.Compare
Str
CStr
Integer.Parse
Databases
Only SQLiteDatabase is available for iOS projects. Here are some of the differences.
Old SQLiteDatabase
New SQLiteDatabase
SQLiteDatabase
SQLiteDatabase
SQLiteDatabase.Commit
SQLiteDatabase.SQLExecute("COMMIT")
SQLiteDatabase.DBError
RecordSet
SQLiteRecordSet
DatabaseField
SQLiteDatabaseField
Global Functions
This table describes some of the methods and their equivalents in the iOS Framework:
Old Global Function
MD5
Page 24
iOS Guide
Color
Color methods are now on the type.
RGB
Color.RGB
Math Functions
All math functions are now in the Math namespace, but can still be accessed just by using their name.
Ticks
System.Ticks
Microseconds
System.Microseconds
JSONItem
JSON usages is done through two simple methods: Data.GenerateJSON and Data.ParseJSON. All JSON data is
processed through Dictionaries. To create JSON data, you populate a Dictionary and then GenerateJSON from it.
To load JSON data into a Dictionary, you call ParseJSON.
Graphics
These classes are used when dealing with graphics: iOSGraphics, iOSBitmap, iOSImage and iOSPath.
DrawString
DrawTextBlock
DrawTextLine
DrawImage
Scale
Page 25
iOS Guide
StringHeight
StringWidth
TextBlockSize
TextLineSize
DrawPolygon,
FillPolygon
DrawPath
FillPath
MsgBox
On iOS, you cannot show a modal MsgBox. Instead you use the iOSMessageBox class to display a message and
asynchronously get an event when a button is clicked. Your code is not stopped while an iOSMessageBox is
displayed and you have to use its Action event handler to determine which button was pressed.
Variant to Auto
To avoid the many bugs associated with implicitly converting between types using Variant, the Auto data type has
been added. Auto is a type that can contain a value of any type. This means it can hold intrinsic types such as
Integer or Text, but also classes such as FolderItem or any of your own.
Auto does not do any implicit conversions. In order to use a value that is in Auto, you will want to assign it to a
variable of the specific type first. You can use Introspection to get the type of any value that is in an Auto variable.
Page 26
iOS Guide
Xojo Language
Console Framework
Classic Framework: The existing framework
Xojo Framework: The new Xojo framework
UI Frameworks
Desktop
Web
iOS
Xojo Language
The Xojo Language has not significantly changed. In order to support the new Xojo Framework, a few small changes
consisting of a several new keywords have been added:
Text data type
Auto data type
Global keyword
Using keyword
These keywords are available for all project types, including iOS, desktop, web and console.
The language is otherwise the same with the same object-oriented programming model you have always used.
Console Framework
The console framework is the collection of classes and methods that supplement the language and that are not
related to the user interface. These are things like Date, Dictionary, FolderItem, etc. The Console Framework that
has always been a part of Xojo is now called the Classic Framework. It remains available for desktop, web and
console projects. However, iOS projects can only use the new Xojo Framework.
The Xojo Framework has a wide variety of classes, such as Dictionary, FolderItem, Date, TCPSocket, etc., that are
organized into namespaces. Namespaces are simply modules that are used as a way to collect related funtionality.
All the Xojo Framework features are contained in the Xojo namespace, which itself contains these namespaces:
Core
Crypto
Data
Introspection
IO
Math
Page 27
iOS Guide
Net
System
Threading
So to use a class in the Core namespace, such as Date, you would typically refer to it as "Xojo.Core.Date". But iOS
has a Shared Build Setting (it is ON by default) that enables "Simple References". When this is ON, you can simply
refer to the classes by their name, without having to use the namespace prefix.
Initially, the Core namespace is also available to desktop, web and console projects. Other namespaces will be
made available in upcoming releases.
You can use both the Classic and the Xojo framework (Core namespace only) in your desktop, web and console
projects. But because many classes in the Xojo Framework share the same name as classes in the Classic
Framework, you will need to be specific about the one you want to use.
For example, in a desktop project if you want to use the new Date class in Xojo.Core, you could refer to it like this:
Dim d As New Xojo.Core.Date</code>
This can be a bit long to write often, so you can use the Using command to simplify this:
Using Xojo.Core
Dim d As Date // actually uses Xojo.Core.Date
You can also set up Using for an entire class or module by choosing "Insert->Using Clause" and entering the
namespace name in the Inspector.
Keep in mind that you can mix and match Classic Framework classes and Xojo Framework classes in the same
method. For cases when you need to do this, you will need to either use the full namespace for the Xojo Framework
class or use the Using command in a local scope. Here are some examples:
Dim d1 As Date // Classic framework Date
Dim d2 As Xojo.Core.Date // Xojo framework Date
If True Then
Using Xojo.Core
d = Date // Xojo framework Date
End If
UI Frameworks
The UI frameworks are the specific UI controls and related classes for creating the UI of your desktop, web and iOS
apps. This framework is specific to each target, so the UI Framework for desktop projects is not the same as the UI
Framework for web or iOS projects.
You'll notice that the class names differ between targets. For example, a button on the desktop is called
PushButton, on web is called WebButton and on iOS is called iOSButton. These controls often operate similarly,
but they may have different events, properties and methods.
Page 28
iOS Guide
The UI framework for desktop and web apps has not changed. For iOS apps, you need to use the new classes in the
iOS Framework.
Page 29
iOS Guide
Topics
Language
Data Types
Framework
iOS Framework
Xojo
Page 30
Reference Guide
Language
The Xojo Programming Language is described in this section.
Data Types
Keywords
Operators
Compiler Constants
Conditional Compilation
Pragma Directives
Page 31
Language
Keywords
This section describes keywords that have been newly added to the Xojo language or that are particularly useful
with iOS projects. Remember, all Xojo language keywords are available in iOS projects.
Page 32
Commands
AddHandler (Keyword)
Directs the handling of an event to a delegate method.
Keyword Summary
Name
AddHandler
Type
Keyword
Targets
All
Platforms
All
Related
RemoveHandler
Syntax
AddHandler eventName, delegateMethod
Parameters
eventName
delegateMethod
The name of the method that will be used to handle the event.
Notes
Generally you will create a subclass to expose event handlers for you to implement. AddHandler is provides a way
for you to instantiate a class in code and still have access to its event handlers.
The delegateMethod method declaration must consist of:
A reference to the object being handled. This is the sender object and it must be the first parameter in the
delegate and must be the correct type.
The same parameters of the event you are handling should follow next in the same order with the same types.
The parameter names can be changed.
If the event you are handling returns a value, then the delegate method must also return the same value type.
handler can handle any number of events, but an event can only have one event handler. To change the event
A
handler for an event after you have added one, you must first remove the existing handler with RemoveHandler.
You can then add the new handler.
Exceptions
RuntimeException
If you implement and event handler that is already implemented without first removing it
using RemoveHandler.
Page 33
Commands
Sample Code
This example lets you handle the Timer.Action event without creating a Timer subclass.
Start by adding a property to the layout:
MyTimer As Xojo.Core.Timer
Next, add a ProgressBar to the layout. The Timer will simply update the ProgressBar.
In the Open event handler of the layout, instantiate the Timer and indicate that its Action event handler should be
handled by a method, TimerAction, that you will add to the layout:
MyTimer = New Xojo.Core.Timer
MyTimer.Period = 1000
MyTimer.Mode = Xojo.Core.Timer.Modes.Multiple
AddHandler MyTimer.Action, AddressOf TimerAction
Now add the TimerAction method to the layout:
Sub TimerAction(sender As Xojo.Core.Timer)
If ProgressBar1.CurrentValue < ProgressBar1.MaxValue Then
ProgressBar1.CurrentValue = ProgressBar1.CurrentValue + 1
Else
// Stop Timer and Remove the handler
sender.Mode = Xojo.Core.Timer.Mode.Off
RemoveHandler MyTimer.Action, AddressOf TimerAction
End If
End Sub
Remember that the first parameter to TimerAction must be of the type of the original object, in this case a Timer.
When you run the project, the ProgressBar is updated once per second.
Page 34
Commands
Array (Keyword)
Assigns a list of values to consecutive elements of a one-dimensional array.
Keyword Summary
Name
Array
Type
Keyword
Targets
All
Platforms
All
Related
Dim, Arrays
Syntax
arrayResult = Array(elementList)
Parts
arrayResult
elementList
Notes
Only one-dimensional arrays can be populated by Array.
Array provides the same functionality as separate assignment statements for each element of the array, beginning
with element zero and proceeding consecutively. If there are more elements in the array than items in elementList,
then the "extra" items in the array are not modified.
Type Considerations
If elementList contains numeric data of different types and/or a mixture of signed and unsigned integers, Array will
use the lowest common data type that accomodates all the elements.
For example, because hexadecimal numbers are unsigned integers (UInteger), the following code generates a Type
Mismatch error:
Dim hexNums() As Integer
hexNums = Array(&h1, &h2)
Page 35
Commands
You need to be careful about the size of the array and whether or not the integer is signed. Instead you should
declare the array as UInt32:
Dim hexNums() As UInt32
hexNums = Array(&h1, &h2)
You can also choose to cast the elements to a specific type:
Dim hexNums() As Integer
hexNums = Array(Int32(&h1), &h2) // Once you convert one value type, the rest will
follow
Similarly, this will work:
Dim hexNums() As integer
hexNums = Array(1, &h2)
Sample Code
Dim teams() As Text = Array("Red Sox", "Yankees", "Orioles", "Rays", "Blue Jays")
Dim names() As Text
names = Array("Bob", "Bill", "Brad", "Ben")
Page 36
Commands
As (Keyword)
Declares a variable or parameter name to be of a particular data type. Used as part of these commands:
Dim
For...Next
For Each...Next
Keyword Summary
Name
As
Type
Keyword
Targets
All
Platforms
All
Related
Sample Code
For i As Integer = 1 To 10
...
Next
Dim value As Integer = 10
Page 37
Commands
Assigns (Keyword)
Used to indicate that a value will be passed via a parameter to a method with the Assignment operator.
Keyword Summary
Name
Assigns
Type
Keyword
Targets
All
Platforms
All
Related
Function, Sub
Syntax
Assigns parameter As dataType
Notes
Use the Assigns command when you want to assign a value to a parameter of a method with the equals sign rather
than supply it as an argument.
The Assigns command can appear in a Method declaration dialog box for the only parameter passed to the method
or for the last parameter, if more than one parameter is being passed. When Assigns is used, you use a different
syntax when calling the method. The value for the Assigns parameter must be passed using the assignment
operator rather than as an argument.
Sample Code
The follow declaration requires the last parameter to be assigned rather than supplied in the parameter list:
Sub ChangeVolumn(a As Integer, b As Integer, Assigns c As Integer)
// Usage
ChangeValue(5, 4) = 10
// ChangeValue(5, 4, 10) would result in a syntax error
Page 38
Commands
ByRef (Keyword)
Used to pass a parameter by reference.
Keyword Summary
Name
ByRef
Type
Keyword
Targets
All
Platforms
All
Related
Syntax
ByRef parameter
Notes
To pass a parameter by reference, you precede a parameter name with the ByRef keyword in the parameter
declaration for the method. When you pass information by reference, you actually pass a pointer to the object
containing the information. The practical advantage of this technique is that any changes to the value of the
parameter by the method are available to the method that called it.
ByRef and ByVal are only applicable to simple data types (Integer, String, Double, etc.) All arrays and
object types are reference types, effectively behaving as if ByRef was used with a simple data type.
Sample Code
// A Powers method that multiplies a number it itself
Sub Powers(ByRef d As Double)
d = d * d
End Sub
// use this in code like so
Dim value As Double = 3
Powers(3) // value now equals 9
Page 39
Commands
ByVal (Keyword)
Used to pass a parameter by value. This is the default for parameters so this is completely optional.
Keyword Summary
Name
ByVal
Type
Keyword
Targets
All
Platforms
All
Related
Syntax
ByValue parameter
Notes
Parameters passed by value (the default) are treated as local variables inside the method, just like variables that
are created using the Dim statement. This means that you can modify the values of the parameters themselves
rather than first assigning the parameter to a local variable. For example, if you pass a value in the parameter "x",
you can increment or decrement the value of x rather then assigning the value of x to a local variable that is
created using Dim.
ByRef and ByVal are only applicable to simple data types (Integer, String, Double, etc.) All arrays
and object types are reference types, effectively behaving as if ByRef was used with a simple data
type.
Page 40
Commands
Break (Keyword)
When running in debug mode (from the IDE), this command stops code execution and displays the debugger. It has
no effect in a built application.
Keyword Summary
Name
Break
Type
Keyword
Targets
All
Platforms
All
Related
Syntax
Break
Notes
The Break command has the same effect as setting a breakpoint in the Code Editor.
A common use of the Break command to display the debugger when a specific condition is met.
Sample Code
For i As Integer = 1 To 10
If i = 5 Then Break // Display debugger
Next
Page 41
Commands
Call (Keyword)
Allows you to ignore the return value from a function call.
Keyword Summary
Name
Call
Type
Keyword
Targets
All
Platforms
All
Related
Function
Syntax
Call functionName
Notes
Use the Call command only when you want to call a function without using the value it returns. This should not often
be the case since the return value is often useful, but it does enable you to call the function without having to create
a local variable to store its result.
Sample Code
Call CalculateSomeValueIgnoringReturnValue
Page 42
Commands
Case (Keyword)
Identifies a specify value that is matched in a Select...Case statement.
Keyword Summary
Name
Case
Type
Keyword
Targets
All
Platforms
All
Related
Select...Case
Sample Code
Dim i As Integer = 5
Dim output As Text
Select Case i
Case Is < 4
output = "Less than four"
Case 5
output = "Five"
Else
output = "Greater than five"
End Select
Page 43
Commands
Catch (Keyword)
Starts the Catch section of a Try...Catch code block.
Keyword Summary
Name
Catch
Type
Keyword
Targets
All
Platforms
All
Related
Try...Catch
Sample Code
Try
Dim a(5) As Integer
a(6) = 45 // Raises an OutOfBoundsException
Catch e As OutOfBoundException
// The above exception is caught here for you to handle
ErrorLabel.Text = "Exceeded size of array"
End Try
Page 44
Commands
Const (Keyword)
Declares a value as a local constant.
Keyword Summary
Name
Const
Type
Keyword
Targets
All
Platforms
All
Related
Dim
Syntax
Const constantName [As datatype] = value
Notes
Constants are assigned once and can never change. Local constants are only available within the method where
there are declared.
You can optionally specify a data type for the constant value.
You can use Const anywhere within the method and can also declare constants within code blocks (such a
For...Next, If...Then, etc.). Constants declared within code blocks are not accessible outside the code block.
You can also assign constants using expressions that consist of other constants or literal values.
Sample Code
Const kAnswer As Integer = 42
Const kPi As Double = 3.14159265358979323846264338327950
// Constants declared from expressions
Page 45
Commands
Page 46
Commands
Continue (Keyword)
Used to to continue execution with the next iteration of a loop, skipping any other code.
Keyword Summary
Name
Continue
Type
Keyword
Targets
All
Platforms
All
Related
Syntax
Continue
Continue [For | While | Do]
Continue forLoopCounter
Notes
The Continue statement enables you to jump to the end of a loop and continue execution without executing the
lines of code between the Continue statement and the end of the loop. If there is ambiguity concerning which loop
you mean, you can use the second or third syntaxes to clarify the situation. For example, if you have nested For
loops and want to jump from a line in the innermost loop to the outermost loop, you can use the last syntax to
identify the loop variable that controls the outermost loop.
Sample Code
// Count the sum from 1 to 100, skipping the number 2 and 31
Dim sum As Integer
For i As Integer = 1 To 100
If i = 2 Or i = 31 Then Continue
sum
Next
= sum + i
Page 47
Commands
End (Keyword)
Indicates the end of a variety of code blocks.
Keyword Summary
Name
End
Type
Keyword
Targets
All
Platforms
All
Related
If...Then...Else, Try...Catch
Syntax
End [If | Function | Select | Sub | Try]
Notes
The type of block is an optional part of the command but if usually included for clarity.
Sample Code
If True Then
// Your code
End If
Page 48
Commands
CurrentMethodName (Constant)
Indicates that an object is Nil (has no value).
Method Summary
Name
CurrentMethodName
Type
Constant
Targets
All
Platforms
All
Related
Syntax
result = CurrentMethodName
Notes
Page 49
Commands
Declare (Keyword)
Used to call OS APIs.
Keyword Summary
Name
Declare
Type
Keyword
Targets
All
Platforms
All
Related
Syntax
[Soft] Declare Sub|Function name Lib libraryName [Alias aliasName] [Selector selectorName]
([Parameters]) [As returnType]
name
libraryName
aliasName
(Optional) Used to give the library an alternative name to refer to in your Xojo code. This is useful
when name happens to also match a built-in Xojo name.
selectorName
(OS X and iOS) Used to specify the parameters to uniquely identify a Cocoa method. The
parameters are separated by colons (no spaces) and must end in a colon. This is mutually
exclusive with the Alias.
parameters
The parameters to pass to the name/selectorName. You can pass Nil to a parameter of type Ptr.
returnType
Notes
For iOS, you can Declare into Cocoa Touch APIs.
Sub/Function names are always case-sensitive. For example, SetLocalTime works on Win32, but SetlocalTime does
not.
You can use constants for in place of libraryName.
Declare can be used to call external functions that return structure values.
You can pass Nil to a parameter of type Ptr, but passing Nil is not the same as passing a Nil MemoryBlock. The
former is a constant and the latter requires a conversion at run-time. If the MemoryBlock is Nil, the conversion will
raise a NilObjectException.
Page 50
Commands
Cocoa
The libraryname is automatically expanded to the full path of the library. For example, CoreMIDI would expand to
"/System/Library/Frameworks/CoreMIDI.framework/CoreMIDI".
Soft Declares
Soft declare statements are resolved at run-time only when your application tries to use the Declare.
In most cases, you should use a Soft declare in order to prevent your app from launching due to missing libraries or
library functions.
For example rather than creating a declare to a specific version of LibC (on Linux) like this:
Declare Function getpid Lib "libc-2.3.2.so" () as Integer
You can instead use a soft declare and allow it to resolve to the appropriate version at run-time:
Soft Declare Function getpid Lib "libc" () as Integer
By default, all Cocoa declares are "soft" even if you do not specify the Soft keyword.
Sample Code
This code can be used to set the focus on a control:
Declare Sub becomeFirstResponder Lib "Foundation.Framework" Selector
"becomeFirstResponder:" (obj_id As Ptr)
becomeFirstResponder(TextField1.Handle)
This code clears the focus:
Sub ClearFocus(extends c As iOSControl)
Declare Sub resignFirstResponder lib "Foundation.Framework" Selector
"resignFirstResponder:" (obj_id As Ptr)
resignFirstResponder(c.Handle)
End Sub
Open a URL in the default app that can handle it:
Function ShowURL(url As Text) As Boolean
// NSString* launchUrl = @"http://www.xojo.com/";
// [[UIApplication sharedApplication] openURL:[NSURL URLWithString: launchUrl]];
Declare Function NSClassFromString Lib "Foundation" (name As CFStringRef) As Ptr
Declare Function sharedApplication Lib "UIKit" Selector "sharedApplication" (obj As
Ptr) As Ptr
Page 51
Commands
Page 52
Declare
AlertSheet
Demonstrates declares to show an iOS Alert Sheet.
IconBadgeNumber
Demonstrates how to add a badge number to your app icon.
iOSAlerts
Demonstrates how to show all the different types of iOS alerts, including text, password, login and more.
SetFocus
Demonstrates how to set focus in a specific control.
ShowURL
Demonstrates how to use the iOS URL handling to open URLs in Safari, Maps, Mail and Phone.
Speak
Demonstrates how to use Text to Speech.
UIButtonDeclares
Demonstrates how to access additional settings for Buttons.
UIDatePicker
Demonstrates how to add and use the UIDatePicker control.
Page 53
Declare
OS X Declare Samples
Current Logged-In User
Declare Function NSFullUserName Lib "Foundation" As CFStringRef</code>
Center a Window
Declare Sub center Lib "Cocoa" Selector "center" (windowRef As Integer)
center(Self.Handle) // The Handle property of the Window</code>
Declare
"orderFrontStandardAboutPanel:" _
(receiver As Ptr, ID As Ptr)
OrderFrontStandardAboutPanel(sA, Nil)
Page 55
Declare
Page 56
Commands
Dim (Keyword)
Declares a local variable for a specific data type.
Keyword Summary
Name
Dim
Type
Keyword
Targets
All
Platforms
All
Related
Arrays, ReDim
Syntax
Dim variableName As dataType [= initialValue]
Dim variableName As New dataType
Dim variableName, variableNameN As dataType [= initialValue]
Notes
Variable names can be any length, but must begin with a letter and can contain alphanumeric characters [A-Z, a-z,
0-9], an underscore or any Unicode character. All variable names are case-insensitive, so the names "FirstName"
and "firstName" would refer to the same variable.
You can declare variables anywhere within the method. Some people prefer to declare all variables at the top of the
method. Others prefer to declare variables near where they will be used. All variables are local to the specific
method in which they are defined can cannot be accessed outside the method.
Variables declared within a code block (If...Then, For...Next, etc.) are unavailable (out of scope) outside of the code
block.
Sample Code
Dim
Dim
Dim
Dim
Dim
a As Integer
value As Integer = 42
percent As Double = 0.50
t As Text = "Hello"
c As Color = &cFF4B51
Page 57
Commands
Page 58
Commands
Do (Keyword)
Indicates the start of a Do...Loop loop.
Keyword Summary
Name
Do
Type
Keyword
Targets
All
Platforms
All
Related
Do...Loop
Sample Code
Dim x As Integer
Do
x = x + 1
Loop Until x >= 100
Page 59
Commands
Do...Loop (Keyword)
Repeatedly executes a series of statements until the specified condition is True.
Keyword Summary
Name
Do...Loop
Type
Keyword
Targets
All
Platforms
All
Related
Syntax
Do [Until condition]
statements
[Continue]
[Exit]
statements
Loop [Until condition]
condition
Any valid boolean expression. When the expression evaulates to True, the loop exits. When the
expression is False, the statements in the loop are executed.
Continue
The Continue keyword causes the execution of code to skip directly to the Loop statement, skipping
over any lines in between.
Exit
The Exit keyword immediately exits the loop so that the statement immediately following the Loop
statement is executed.
Notes
The Do...Loop statement continues to execute the statements within it until an Until condition evaluates to True or
an Exit statement is reached.
The Until condition parts of the loop are optional, but if you do not include it you *have* to include an Exit statement
somewhere within the loop or you will have an infinite loop, causing your app to appear to get stuck or hang.
Page 60
Commands
Variables declared within the Do...Loop are local to the loop and go out of scope when the loop ends.
Sample Code
Dim x As integer
Do
x = x + 1
Loop Until x = 100
// x = 100
x = 0
Do
x = x + 1
If x >= 100 Then Exit
Loop
// x = 100
Using Exit:
Const kAttempts = 10
Dim attempt As Integer = 1
Dim output As Text
Do Until attempt > kAttempts
Dim randomValue As Integer = Math.RandomInt(1, 10)
If randomValue > 5 Then
output = "Found a random value above 5 after " + attempt.ToText + " iterations."
Exit
End If
attempt = attempt + 1
Loop
If attempt > kAttempts Then
output = "Found NO random value above 5 after " + kAttempts.ToText + " iterations."
End If
Using Continue:
Const kAttempts = 100
Dim matchCount As Integer
Dim attempt As Integer
Do
attempt = attempt + 1
Dim randomValue As Integer = Math.RandomInt(1, 10)
If randomValue <= 5 Then
Continue
Page 61
Commands
End If
matchCount = matchCount + 1
Loop Until attempt >= kAttempts
Dim output As Text
output = "Found " + matchCount.ToText + " random values above 5 within " +
kAttempts.ToText + " iterations."
Page 62
Commands
DownTo (Keyword)
Separates the beginning and ending values of a For...Next loop counter that counts down from the start value to the
end value.
Keyword Summary
Name
DownTo
Type
Keyword
Targets
All
Platforms
All
Related
For...Next
Sample Code
For i As Integer = 1 DownTo 10
...
Next
Page 63
Commands
Each (Keyword)
Specifies a value from the array in a For Each...Next statement.
Keyword Summary
Name
Each
Type
Keyword
Targets
All
Platforms
All
Related
For Each...Next
Sample Code
For Each i As Integer In values()
...
Next
Page 64
Commands
Exit (Keyword)
Exits the current loop or method.
Keyword Summary
Name
Exit
Type
Keyword
Targets
All
Platforms
All
Related
Syntax
Exit [For | Do | While]
Exit [forLoopCounter]
Exit [Sub | Function]
Notes
If you use Exit without any optional keywords, it exists the current loop. If the Exit is not within a loop, it exits the
method.
If you use Exit with the Do keyword, the Do loop it is in, even if it is also inside another type of loop, is exited.
If you use Exit with the While keyword, the While loop it is in, even if it is also inside another type of loop, is exited.
If you use Exit with the For keyword without passing a parameter, it exits the innermost For loop it is in, even if it is
also inside another loop.
If you have nested For statements, you can pass the For keyword the variable that controls the loop you want to
exit. For example, if you are testing all the elements of a two-dimensional array with nested For statements, you can
use the loop variable for the outermost loop to exit at that point.
For i = 0 to 255
For j = 0 to 255
If myArray(i, j) = 23 then
Exit For i
End if
Next
Next
Page 65
Commands
If you use Exit with the Sub or Function keywords, then it will exit the entire method or function as if you used
Return. Exit Function cannot specify a return value, so if you use it to exit a function, the function will return the
default value for the data type of the function.
Sample Code
// Searches a ListBox for a specific value in the first column and
// when found, selects it and exits the loop
Dim search As Text = "text to find"
For i As Integer = 0 To ListBox1.ListCount - 1
If ListBox.Cell(i, 0) = search Then
ListBox1.Selected(i) = True
Exit
End If
Next
Page 66
Commands
False (Keyword)
Assigns or tests the boolean value False. A comparison of two values that are not equal results in False.
Keyword Summary
Name
True
Type
Keyword
Targets
All
Platforms
All
Related
Syntax
expression = False
Sample Code
Dim b As Boolean
b = True
b = False
Page 67
Commands
Finally (Keyword)
Starts the Finally section of a Try...Catch code block.
Keyword Summary
Name
Finally
Type
Keyword
Targets
All
Platforms
All
Related
Try...Catch
Sample Code
Try
Dim a(5) As Integer
a(6) = 45 // Raises an OutOfBoundsException
Catch e As OutOfBoundException
// The above exception is caught here for you to handle
ErrorLabel.Text = "Exceeded size of array"
Finally
// This code always runs
a(0) = 100
End Try
Page 68
Commands
For (Keyword)
Starts a For...Next or For Each...Next loop.
Keyword Summary
Name
For
Type
Keyword
Targets
All
Platforms
All
Related
Sample Code
For i As Integer = 1 To 10
...
Next
Page 69
Commands
For...Next (Keyword)
Loops over a collection of statements a specific number of times.
Keyword Summary
Name
For...Next
Type
Keyword
Targets
All
Platforms
All
Related
Syntax
For counterValue [As datatype] = startValue To | DownTo endValue [Step stepValue]
[Statements]
[Continue [For]]
[Exit [For]]
[Statements]
Next [counterValue]
counterValue
A variable that is incremented or decremented every time through the loop. It can be an Integer,
Single or Double. By default the counterValue is changed by 1 at the end of each loop (when the
Next statement is reached or a Continue is invoked within the loop.
datatype
Specifies an optional datatype for the counterValue. This declares the variable for use only during
the loop. The value goes out of scope when the loop ends.
startValue
To | DownTo
Indicates whether the counterValue is incremented (To) or decremented (DownTo) each time
through the loop.
Page 70
Commands
endValue
The final value of counterValue. The loop ends if counterValue reaches a value beyond endValue
at the time the Next or Continue is reached.
This means that the loop ends once counterValue > endValue if counterValue is being
incremented; the loop ends once counterValue < endValue if counterValue is being decremented.
The endValue is re-evaluated in every loop interation, so avoid invoking functions that return a
value. If the function has a time-consuming operation, this could significantly delay the processing
of your loop. Instead save the function result in its own variable and use that for endValue.
stepValue
The optional amount to increment or decrement counterValue each time through the loop. This
defaults to 1.
Using To indicates counterValue will be incremented; DownTo indicates counterValue will be
decremented.
If stepValue is negative, it causes counterValue to decrement, providing the same functionality as
the DownTo keyword.
Continue
The Continue keyword causes the execution of code to skip directly to the Next statement,
skipping over any lines in between.
Exit
The Exit keyword immediately exits the loop so that the statement immediately following the Next
statement is executed.
Notes
For...Next statements can be nested, but each For...Next statement must have its own counter variable.
When a For...Next loop is running, it blocks the user interface for your app. This prevents the user from being able to
interact with the UI. For long-running tasks, use Threading to run the task in the background and allow the UI to
remain responsive.
Troubleshooting
When looping through lists (such as ListBoxes or arrays) where you plan to remove some of the items, you should
loop from the end of the list to the beginning to avoid the countValue no longer matchning the expected position in
the new, smaller list.
Sample Code
Dim days() As Text = Array("One", "Two", "Three", "Four", "Five")
Dim output As Text
For counter As Integer = 0 To days.UBound
output = output + days(counter)
Next
// output = "OneTwoThreeFourFive"
Dim days() As Text = Array("One", "Two", "Three", "Four", "Five")
Dim output As Text
For counter As Integer = days.UBound DownTo 0
output = output + days(counter)
Next
Page 71
Commands
// output = "FiveFourThreeTwoOne"
Counting by Steps:
Dim output As Text
For i As Integer = 1 To 6 Step 2
output = output + i.ToText + " "
Next
// output = "1 3 5 "
Using Exit:
Const kAttempts = 10
Dim output As Text
For attempt As Integer = 1 To kAttempts
Dim randomValue As Integer = Math.RandomInt(1, 10)
If randomValue > 5 Then
output = "Found a random value above 5 after " + attempt.ToText + " iterations."
Exit
End If
Next
If attempt > kAttempts Then
output = "Found NO random value above 5 after " + kAttempts.ToText + " iterations."
End If
Using Continue:
Const kAttempts = 100
Dim matchCount As Integer
For attempt As Integer = 1 To kAttempts
Dim randomValue As Integer = Math.RandomInt(1, 10)
If randomValue <= 5 Then
Continue
End If
matchCount = matchCount + 1
Next
Dim output As Text
output = "Found " + matchCount.ToText + " random values above 5 within " +
kAttempts.ToText + " iterations."
Page 72
Commands
Keyword Summary
Name
For Each...Next
Type
Keyword
Targets
All
Platforms
All
Related
Syntax
For Each element [As datatype] = startValue To | DownTo endValue [Step stepValue]
[Statements]
[Continue [For]]
[Exit [For]]
[Statements]
Next [counterValue]
element
array A variable of the same data type as array that refers to an element of array. The loop
processes each value in array, but the specific order is not guaranteed.
datatype
array
Continue
The Continue keyword causes the execution of code to skip directly to the Next statement, skipping
over any lines in between.
Exit
The Exit keyword immediately exits the loop so that the statement immediately following the Next
statement is executed.
Page 73
Commands
Notes
A For...Each loop does not guarantee that it will loop through the values in the array in index order. Do not make
any assumptions of the traversal order as it is subject to change in the future.
As with other block statements, variables declared within the For...Each loop go out of scope when the loop finishes
or exits.
Sample Code
// Iterate
Dim days()
Dim output
For Each d
output =
Next
through an array
As Text = Array("One", "Two", "Three", "Four", "Five")
As Text
As Text In days
output + d
Page 74
Commands
Page 75
Commands
Global (Keyword)
Identifies the global scope, making it possible to refer to items that might otherwise be ambiguous.
Keyword Summary
Name
Global
Type
Keyword
Targets
All
Platforms
All
Related
Using
Syntax
Global.identifier
Notes
Global works similarly to Self, Me and Super and is most useful when working with namespaces. You use it to refer
to a global identifier (such as a module or namespace) that might otherwise be inaccessible because they are
hidden by local identifiers (i.e. methods or variables) in the current scope.
Sample Code
Declare a local variable that
Access the classic Dictionary class within a method that has used Using to access Dictionary in Xojo.Core
Using Xojo.Core
Dim d As New Dictionary // Uses Xojo.Core.Dictionary
Dim d2 As New Global.Dictionary // Uses classic Dictionary class
This is a more advanced example that shows how a local variable can make a module inaccessible:
Module Utility
Protected Version As Integer
End Module
Module AppStuff
Protected Version As String
Page 76
Commands
Page 77
Commands
If (Keyword)
Starts an If...Then...Else command.
Keyword Summary
Name
If
Type
Keyword
Targets
All
Platforms
All
Related
If...Then...Else
Sample Code
If True Then
// Your code
End If
Page 78
Commands
Else (Keyword)
Indicates the Else part of an If...Then...Else command.
Keyword Summary
Name
Else
Type
Keyword
Targets
All
Platforms
All
Related
If...Then...Else
Sample Code
If True Then
// Your code
Else
// Your code
End If
Page 79
Commands
ElseIf (Keyword)
Indicates an ElseIf part of an If...Then...Else command.
Keyword Summary
Name
ElseIf
Type
Keyword
Targets
All
Platforms
All
Related
If...Then...Else
Sample Code
If True Then
// Your code
ElseIf False Then
// Your code
End If
Page 80
Commands
If...Then...Else (Keyword)
Conditionally executes a group of statements depending on the value of boolean conditions.
Keyword Summary
Name
If...Then...Else
Type
Command
Targets
All
Platforms
All
Related
If, #If...#EndIf
Syntax
If condition Then
statements
[ElseIf condition Then]
statements
[Else]
statements
End [If]
If condition Then statement [Else statement]
condition
statements
Notes
The statements after the If are run if the If condition evaluates to True.
The statements after the optional ElseIf are run if the ElseIf condition evaluates to True.
The statements after the optional Else are run if all the other conditions evaluated to False.
Only the first section of an If...Then...Else that evaluates to True is run. So if both an If and an ElseIf evaluates to
True, then only the statements in the If portion will run.
Page 81
Commands
You can have a single-line If...Then...Else statement, but when doing so only a single statement is allowed for the If
and Else portions.
Variables declared within sections of an If...Then...Else statement go out of scope when leaving the section.
Sample Code
Dim i As Integer = 6
If i > 5 Then
i = i * 10
Else
i = i - 1
End If
// i = 60
If i < 5 Then
i = i * 10
ElseIf i = 6 Then
i = 100
Else
i = i - 1
End If
// i = 100
Dim t As Text = "Hello, World!"
If t.BeginsWith("Hello") Then
Label1.Text = t
Else
Label1.Text = "Goodbye!"
End If
i = 100
If i >= 10 And i <= 100 Then
Label1.Text = "In range"
Else
Label1.Text = "Out of range"
End If
If i < 10 Or i > 100 Then
Label1.Text = "Out of range"
Else
Label1.Text = "in range"
End If
Page 82
Commands
In (Keyword)
Specifies the array in a For Each...Next statement.
Keyword Summary
Name
In
Type
Keyword
Targets
All
Platforms
All
Related
For Each...Next
Sample Code
For Each i As Integer In values()
...
Next
Page 83
Commands
Lib (Keyword)
Specifies the library to use with a Declare statement.
Keyword Summary
Name
Lib
Type
Keyword
Targets
All
Platforms
All
Related
Declare
Sample Code
Declare Sub becomeFirstResponder Lib "Foundation.Framework" Selector
"becomeFirstResponder" (obj_id As Ptr)
becomeFirstResponder(TextField1.Handle)
Page 84
Commands
Loop (Keyword)
Indicates the end of a Do...Loop loop.
Keyword Summary
Name
Loop
Type
Keyword
Targets
All
Platforms
All
Related
Do...Loop
Sample Code
Dim x As Integer
Do
x = x + 1
Loop Until x >= 100
Page 85
Commands
Me (Keyword)
Refers to the control that owns (or contains) the current event handler.
Keyword Summary
Name
Me
Type
Keyword
Targets
All
Platforms
All
Related
Self
Syntax
Me.MemberName
Notes
In an event handler of a class (usually a control) that was added to a Window, WebPage, iOSView, ContainerControl
or WebContainer, you use the Me prefix to refer to its own members rather than the members of the parent Window,
WebPage, iOSView, ContainerControl or WebContainer.
For example, in the Open event handler of a Label, if you wanted to change the Label Text property, you would write
this code:
Me.Text = "Hello"
If, in the Label's Open event handler, you tried to access the Text property without the Me prefix, your code would
actually instead be refering to a (non-existent) Text property of its container (the Window, WebPage, etc.).
If you use Me outside of an event handler of a control in this manner, Me behaves as if you used
"Self". For clarity, you should limit your use of Me to only within event handlers used on containers
as described above.
Sample Code
// Code in the Open event handler of a Label that sets its Text property
Event Open()
Me.Text = "Hello"
End Event
Page 86
Commands
Next (Keyword)
Defines the end of For..Next or For Each...Next loops.
Keyword Summary
Name
Next
Type
Keyword
Targets
All
Platforms
All
Related
Sample Code
For i As Integer = 1 To 10
...
Next
Page 87
Commands
Nil (Keyword)
Indicates that an object is Nil (has no value).
Keyword Summary
Name
Nil
Type
Keyword
Targets
All
Platforms
All
Related
Is
Syntax
expression = Nil
Notes
Nil means no value. When an object variable is first declared, it is automatically initialized to Nil. Some functions
return a Nil value under certain circumstances.
Nil is a constant of its own datatype, not an Object. It can convert itself to any object class, any array type, or any of
the pointer types (Ptr, WindowPtr, CString, PString, WString, and CFStringRef).
You can pass Nil for any of the string parameter types above (CString, PString, WString), but not for String or Text.
Passing Nil is not the same as passing the empty string, "". Passing Nil means you want to pass a null pointer.
Passing "" means you want to pass a non-null pointer to the representation of "" for the declared format.
If you try to access an object that has a Nil value, a NilObjectException error is raised. If you don't handle the
exception, your app will terminate. If you are testing the application in the IDE, you can turn on Project Break on
Exceptions to display the Debugger at the line of code that caused the runtime exception (even if the exception is
handled).
An unhandled exception will display a generic error message before the application terminates. You can use the
generic UnhandledException event handler in the App object in order to attempt to recover for otherwise unhandled
exceptions.
You should use Try..Catch to handle possible exceptions in your code so that your app does not terminate
unexpectedly.
Page 88
Commands
Sample Code
Dim f As New FolderItem("test.txt")
If f <> Nil Then
// use the FolderItem
End If
Page 89
Commands
Optional (Keyword)
Used in a method parameter to indicate that the parameter is optional and may be excluded from the method call.
Keyword Summary
Name
Optional
Type
Keyword
Targets
All
Platforms
All
Related
Function, Sub
Syntax
Optional parameterName As dataType
Notes
Optional parameters must be defined at the end of the parameter list, after any required parameters. If the method
call provides an argumemt for any one of a succession of optional parameters, it must provide arguments for all
preceding optional parameters as well. Comma-separated gaps in the argument list are not allowed.
Optional does not provide a default value, so the default value becomes the default for the type or Nil.
Sample Code
Sub MyMethod(a As Integer, b As Integer, Optional c As Integer)
// You can call the above method with or without the last parameter
MyMethod(5, 42, 10)
MyMethod(5, 42) // c will default to 0
// If you want to specify a default value, do that instead of using Optional
Sub MyMethod(a As Integer, b As Integer, c As Integer = 10)
Page 90
Commands
ParamArray (Keyword)
Used in a method parameter to indicate that an arbitrary number of parameters can be passed.
Keyword Summary
Name
ParamArray
Type
Keyword
Targets
All
Platforms
All
Related
Syntax
ParamArray parameterName As dataType
Notes
This keyword allows you to have a method call that can take an arbitrary number of parameters. The parameters
are available to the method in an array.
Sample Code
Function AddNumbers(ParamArray nums As Integer) As Integer
Dim i, total As Integer
For Each i In nums
total = total + i
Next
Return Total
End Function
// This function can now be called like this:
Dim sum As Integer
sum = AddNumbers(1, 2, 3, 4, 5)
// sum = 15
Page 91
Commands
Raise (Keyword)
Used to raise an exception to the next level in the calling chain.
Keyword Summary
Name
Raise
Type
Keyword
Targets
All
Platforms
All
Related
Try...Catch, Exceptions
Syntax
Raise exceptionInstance
Notes
The exceptionInstance must be an object that is a subclass of RuntimeException.
You can create your own subclasses of RuntimeException and use Raise to raise them for error conditions.
Sample Code
Raise New RuntimeException
Dim e As New MyRuntimeException // subclass of RuntimeException
e.Message = "My error message."
Raise e
Page 92
Commands
RaiseEvent (Keyword)
Calls an event definition on a class.
Keyword Summary
Name
RaiseEvent
Type
Keyword
Targets
All
Platforms
All
Related
Event
Syntax
RaiseEvent eventDefinitionName[(parameters)]
Notes
If the event definition requires parameters, they are included after eventDefinitionName.
This statement is optional as you can always call an event definition by its name. It is useful for situations where you
have an event definition with the same name as a method on the class.
The only place you can use RaiseEvent (or call an Event) is on the class that contains the event definition. In
particular, you cannot raise an event from an subclass, an instance of a control on a layout or from outside the
class. If you need to be able to call an event, you will have to create a companion method on the initial class that
raises the event.
Sample Code
RaiseEvent MyEvent // MyEvent is an Event Definition on the class
Page 93
Commands
ReDim (Keyword)
Resizes an array previously declared with Dim.
Keyword Summary
Name
ReDim
Type
Keyword
Targets
All
Platforms
All
Related
Arrays, Dim
Syntax
ReDim arrayName(upperBound)
ReDim arrayName(upperBoundDimension1, ...upperBoundDimensionN)
Notes
The ReDim command can be used to increase or decrese the number of elements in a previously declared array.
When you ReDim an array to an unbounded size (using -1 as the upperBound), then all its elements are removed. It
is faster to use ReDim in this manner to clear any array rather than looping through the array and calling the
Remove method on each element.
When you increase the size of an array, any existing values are retained.
When you decrease the size of an array, existing values are retained if they are still within the new array bounds.
Sample Code
Dim names() As Text // Create empty array
ReDim names(10) // Set its upper bound to 10
ReDim names((names.UBound + 10) // Add 10 additional array elements
ReDim names(-1) // Clear the array, removing all elements
Page 94
Commands
Rem (Keyword)
Used to add comments (remarks) to your code. You can also use the symbols // and '.
Keyword Summary
Name
Rem
Type
Keyword
Targets
All
Platforms
All
Related
Notes
All comments are ignored by the compiler and are not included in your built apps.
Comments can appear on separate lines or on the same line as code, provided they are to the right of the code.
Sample Code
Rem This is a comment
// This is a comment
' This is a comment
Dim tax1 As Double // contains the tax rate
Dim tax2 As Double ' contains the tax rate
Dim tax2 As Double Rem contains the tax rate
Page 95
Commands
RemoveHandler (Keyword)
Removes an event handler that was added by AddHandler.
Keyword Summary
Name
RemoveHandler
Type
Keyword
Targets
All
Platforms
All
Related
AddHandler
Syntax
RemoveHandler eventName, delegateMethod
Parameters
eventName
delegateMethod
Notes
Always remove any handlers added with AddHandler when you are finished with them.
Sample Code
This example lets you handle the Timer.Action event without creating a Timer subclass.
Start by adding a property to the layout:
MyTimer As Xojo.Core.Timer
Next, add a ProgressBar to the layout. The Timer will simply update the ProgressBar.
In the Open event handler of the layout, instantiate the Timer and indicate that its Action event handler should be
handled by a method, TimerAction, that you will add to the layout:
MyTimer = New Xojo.Core.Timer
MyTimer.Period = 1000
MyTimer.Mode = Xojo.Core.Timer.Modes.Multiple
Page 96
Commands
Page 97
Commands
Return (Keyword)
Exits the current method, returning to the calling method.
Keyword Summary
Name
Return
Type
Keyword
Targets
All
Platforms
All
Related
Syntax
Return [value]
Notes
Methods automatically return when you reach the end of the code in the method. You can use the Return command
to exit a method early based on a condition.
You must specify a return value for functions and events that are declared to have a return value. The return value
must match the type in the declaration.
The return value can be an array or a single value. If you want to return an array, put empty parentheses after the
name of the data type in the Return Type area for the declaration in the Inspector. For example, if you want to
return an array of Integers, this would be the return type:
Integer()
If you need to return a multi-dimensional array, place one fewer commas in the parentheses than dimensions. For
example, to return a two-dimensional array of Doubles, use this as the return type:
Double(,)
Sample Code
// Exit early from a method
Sub Test(value As Text)
If value = "Hello" Then Return
Label1.Text = value
Page 98
Commands
End Sub
// Return from a function
Function calc(value As Integer) As Integer
value = value * 2
Return value
End Sub
Page 99
Commands
Select (Keyword)
Starts a Select...Case statement.
Keyword Summary
Name
Select
Type
Keyword
Targets
All
Platforms
All
Related
Select...Case
Sample Code
Dim i As Integer = 5
Dim output As Text
Select Case i
Case Is < 4
output = "Less than four"
Case 5
output = "Five"
Else
output = "Greater than five"
End Select
Page 100
Commands
Select...Case (Keyword)
Used to execute one set of statements out of a group based on the value of an expression.
Keyword Summary
Name
Select...Case
Type
Command
Targets
All
Platforms
All
Related
If...Then...Else
Syntax
Select Case expression
Case [Is] expression-n | Case expression-n, expression-n | Case expression-n To expression-n
statements
[Else]
statements
[Case Else]
statements
End [Select]
expression
expression-n
An expression or list of expressions that are compared to expression. The data type must match
expression.
This can be a single value, a comma-delimited list of values, function(s) that returns a value, a
range of values using the To keyword, or an expression that uses the Is or IsA keywords.
statements
Notes
Select...Case is useful when there are several possible conditions to check. Unlike an If statement, Select...Case
exists as soon as it finds a matching Case expression to use. If there are no Case expressions that match, then the
Page 101
Commands
Case
Case
Case
Case
Case
Case
Case
2, 4, 6, 8 // several values
2 To 5 // range of values from 2 to 5 (inclusive)
2 To 5, 7,9,11 // Both separate values and range
myFunction(x) // a Function
Is >= 42 // greater than/equal to operator
Is <19 // less than operator
IsA Label // tests whether an object is a Label
Sample Code
Dim dayNumber As Integer
Dim day As Text
dayNumber = 3
Select Case dayNumber
Case 2
day = "Monday"
Case 3
day = "Tuesday"
Case 4
day = "Wednesday"
Case 5
day = "Thursday"
Case 6
day = "Friday"
Else
day = "Weekend."
End Select
// day = "Tuesday"
Page 102
Commands
Self (Keyword)
Refers to the primary (main) class containing the code.
Keyword Summary
Name
Self
Type
Keyword
Targets
All
Platforms
All
Related
Me
Syntax
Self.MemberName
Notes
By default, references to members (properties, methods, etc.) of a class use the Self prefix by default. For example,
to call a method on a class, you can just use the method name:
MyMethod(123)
Alternatively, you can also use the Self prefix if you need additional clarity:
Self.MyMethod(123)
Self is related to the Me prefix, which is specifically used to refer to members within the event handler of a class
added to a Window, WebPage, iOSView, ContainerControl or WebContainer.
Sample Code
// Code in the Open event handler of an iOSView that sets its Title property
Event Open()
Self.Title = "Hello"
End Event
Page 103
Commands
Soft (Keyword)
Indicates that a Declare should be resolved when used at run-time rather than when the app is launched.
Keyword Summary
Name
Soft
Type
Keyword
Targets
All
Platforms
All
Related
Declare
Page 104
Commands
Static (Keyword)
Declares a local variable for a specific data type. When using Static, the value for the variable is remembered when
the method that declared it is called again.
Keyword Summary
Name
Static
Type
Keyword
Targets
All
Platforms
All
Related
Arrays, Dim
Syntax
Static variableName As dataType [= initialValue]
Static variableName As New dataType
Static variableName, variableNameN As dataType [= initialValue]
Notes
Essentially, Static creates a locally-scoped global variable. The variable you create retains its value permanently,
but it can only be accessed from within the method that declared it.
Use of Static can result in a performance improvement for a value that is assigned by a function that takes noticable
time to calculate.
Sample Code
Static age As integer
age = 33
Static firstName, lastName As Text
// This function returns an ever-increasing number
Function SerialNumber As Integer
Static currentSerialNumber As Integer = 0
currentSerialNumber = currentSerialNumber + 1
Return currentSerialNumber
Page 105
Commands
End Function
Page 106
Commands
Step (Keyword)
Specifies the counting increment (or decrement) in For...Next loops.
Keyword Summary
Name
Step
Type
Keyword
Targets
All
Platforms
All
Related
For...Next
Sample Code
For i As Integer = 1 To 10 Step 2
...
Next
Page 107
Commands
Super (Keyword)
Used in a subclass to access methods in its superclass that have been overridden by the subclass.
Keyword Summary
Name
Super
Type
Keyword
Targets
All
Platforms
All
Related
Class
Syntax
Super.methodname
Notes
Super can only be used to access methods of the superclass, not properties, because only methods can be
overridden.
If you add a Constructor to a control subclass, the Code Editor will automatically add a call to the Constructor of the
Super. Do not remove this as it may cause the control subclass to not work as expected.
Page 108
Commands
Then (Keyword)
Indicates the Then part of an If...Then...Else statement.
Keyword Summary
Name
Then
Type
Keyword
Targets
All
Platforms
All
Related
If...Then...Else
Sample Code
If True Then
// Your code
End If
Page 109
Commands
To (Keyword)
Separates the beginning and ending values of a For...Next loop counter or a value of a match range in a
Select...Case.
Keyword Summary
Name
To
Type
Keyword
Targets
All
Platforms
All
Related
For...Next, Select...Case
Sample Code
For i As Integer = 1 To 10
...
Next
Dim value As Integer = 10
Select Case value
Case 1 To 5
...
Case 10 To 20
...
Else
End Select
Page 110
Commands
True (Keyword)
Assigns or tests the boolean value True. A comparison of two values that are equal results in True.
Keyword Summary
Name
True
Type
Keyword
Targets
All
Platforms
All
Related
Syntax
expression = True
Sample Code
Dim b As Boolean
b = True
Page 111
Commands
Try (Keyword)
Starts a Try...Catch code block.
Keyword Summary
Name
Try
Type
Keyword
Targets
All
Platforms
All
Related
Try...Catch
Sample Code
Try
Dim a(5) As Integer
a(6) = 45 // Raises an OutOfBoundsException
Catch e As OutOfBoundException
// The above exception is caught here for you to handle
ErrorLabel.Text = "Exceeded size of array"
End Try
Page 112
Commands
Try...Catch
Used to handle exceptions raised in your code.
Keyword Summary
Name
Try...Catch
Type
Command
Targets
All
Platforms
All
Related
Syntax
Try
// Your code
Catch [exceptionParameter] [As exceptionType]
// Your code
[Catch [exceptionParameter] [As exceptionType]
[Finally]
End Try
You can specify an exception parameter and exception type so that you can catch specific exceptions.
Notes
Only exceptions that are raised in code within the Try statement can be caught by the Catch statement. If you do
not catch an exception that was raised, the exception is passed up the calling stack until it eventually reaches the
UnhandledException event for the application (if implemented). If the exception is left completely unhandled, then
your application terminates.
You can have multiple Catch blocks to catch different types of exceptions
You can nest Try...Catch commands. If an inner Try...Catch does not handle an exception, then the next outer
Try...Catch block will attempt to handle it.
You can also have an optional Finally block (after all the Catch blocks). A Finally block executes regardless of
whether an exception was raised. Note that the Finally block does not get called if your method returns or exits in
the Try or Catch blocks.
Page 113
Commands
You should try to avoid catching the RuntimeException superclass as this could cause prevent threads from properly
being killed or apps from quitting if an exception is raised during those events. If you must catch RuntimeException,
then be sure to re-raise the exception if it is not one that you need. For example:
Try
Dim d As Date
Dim t As Text = d.ToText
Catch e As RuntimeException
If e IsA NilObjectException Then
// your code
Else
// Re-raise the exception for the framework
Raise e
End If
End Try
Sample Code
Try
Dim a(5) As Integer
a(6) = 45 // Raises an OutOfBoundsException
Catch e As OutOfBoundException
// The above exception is caught here for you to handle
ErrorLabel.Text = "Exceeded size of array"
End Try
Page 114
Commands
Until (Keyword)
Specifies a condition that ends a Do...Loop loop.
Keyword Summary
Name
Until
Type
Keyword
Targets
All
Platforms
All
Related
Do...Loop
Sample Code
Dim x As Integer
Do
x = x + 1
Loop Until x >= 100
Page 115
Commands
Using (Keyword)
Makes all of the public declarations in a module (or namespace) available for inside the scope of the code as if it
were defined there.
Keyword Summary
Name
Using
Type
Keyword
Targets
All
Platforms
All
Related
Global
Syntax
Using [Global.]identifier1.identifier2
Using [Global.]identifier
Notes
The only legal target for a Using statement is a module (namespace). The first identifier will be resolved recursively,
from inner to outer scope as usual. If you would rather skip the recursive search, you may use the Global variable.
When Using is used in code, it obeys code block scoping rules.
You can also use Using with classes and modules (Insert->Using Clause). When used in this manner, the Using
applies to the entire class or module and all code contained within it.
Sample Code
Access the Dictionary without using its full namespace:
Using Xojo.Core
Dim d As New Dictionary
Avoid the Xojo namespace:
Using Xojo
Dim d As New Core.Dictionary
Code block scoping:
Page 116
Commands
If True Then
Using Xojo.Core
Dim d As New Dictionary
End If
Dim d As Xojo.Core.Dictionary // Using statement is out of scope here
Page 117
Commands
Wend (Keyword)
Indicates the end of a While...Wend loop.
Keyword Summary
Name
Wend
Type
Keyword
Targets
All
Platforms
All
Related
While...Wend
Sample Code
Dim x As Integer
While x < 100
x = x + 1
Wend
Page 118
Commands
While (Keyword)
Starts a While...Wend loop.
Keyword Summary
Name
While
Type
Keyword
Targets
All
Platforms
All
Related
While...Wend
Sample Code
Dim x As Integer
While x < 100
x = x + 1
Wend
Page 119
Commands
While...Wend (Keyword)
Repeatedly executes a series of statements while the specified condition is True.
Keyword Summary
Name
While...Wend
Type
Keyword
Targets
All
Platforms
All
Related
Syntax
While condition
Statements
[Continue]
[Exit [While]]
Wend
condition
Any valid boolean expression. When the expression evaulates to True, the statements in the loop are
executed. When the condition evaluates to False, the loop ends and any code following the Wend
command is executed.
Continue
The Continue keyword causes the execution of code to skip directly to the Wend statement, skipping
over any lines in between.
Exit
The Exit keyword immediately exits the loop so that the statement immediately following the Wend
statement is executed.
Notes
While statements can be nested to any level, with each Wend statement matching its corresponding While
statement.
Variables declared within a While loop are local to the While loop and go out of scope when the loop ends.
Page 120
Commands
Sample Code
Dim x As integer
While x < 100
x = x + 1
Wend
// x = 100
Using Exit:
Const kAttempts = 10
Dim attempt As Integer = 1
Dim output As Text
While attempt <= kAttempts
Dim randomValue As Integer = Math.RandomInt(1, 10)
If randomValue > 5 Then
output = "Found a random value above 5 after " + attempt.ToText + " iterations."
Exit
End If
attempt = attempt + 1
Wend
If attempt > kAttempts Then
output = "Found NO random value above 5 after " + kAttempts.ToText + " iterations."
End If
Using Continue:
Const kAttempts = 100
Dim matchCount As Integer
Dim attempt As Integer
While attempt < kAttempts
attempt = attempt + 1
Dim randomValue As Integer = Math.RandomInt(1, 10)
If randomValue <= 5 Then
Continue
End If
matchCount = matchCount + 1
Wend
Dim output As Text
output = "Found " + matchCount.ToText + " random values above 5 within " +
kAttempts.ToText + " iterations."
Page 121
Language
Compiler Constants
You can use Compiler Constants to isolate code for target-specific or other reasons.
Target32Bit
Target64Bit
TargetARM*
True if building an app for an ARM-compatible CPU or the app is running on an ARMcompatible CPU.
TargetBigEndian
TargetCocoa
TargetConsole
TargetDesktop
TargetiOS
TargetLinux
TargetLittleEndian
TargetMacOS
TargetRemoteDebugger
TargetWeb
TargetWin32
True if building a Windows 32-bit app or the 32-bit app is running on any version of
Windows (even 64-bit).
TargetX86
True if building an app for an Intel x86-compatible CPU or the app is running on an Intel
x86-compatible CPU.
TargetXojoCloud
True if building a web app for Xojo Cloud or for a web app that is running on Xojo Cloud.
DebugBuild
XojoVersion
The major and minor version of Xojo as a Double in the form 20xx.yy, where xx is the
2-digit year and yy is the release number.
For example, Xojo 2014 Release 3.2 would return 2014.32.
XojoVersionString
CurrentMethodName
Contains the fully-qualified name of the method (or event) where it is used. For
example, in Window1's Open event handler it contains "Window1.Open". In the Action
event handler of Button1 on Window1, it is "Window1.Button1.Action".
Page 122
Language
Sample Code
#If TargetDesktop Then
Dim c As New Clipboard
#Endif
#If DebugBuild Then
// Do extra logging
#Endif
// Save settings
If TargetWin32 Then
// Use the Registry
ElseIf TargetMacOS Then
// Use a plist
ElseIf TargetLinux
// Use XML
End If
Label1.Text = "Made with Xojo " + XojoVersionString
Page 123
Language
Syntax
#If constantExpression [Then]
// target-specific code
[#Else]
// other target-specific code
[#ElseIf constantExpression]
// other target-specific code
#Endif
#If TargetBoolean Then <one line of target-specific code>
Notes
You can use any of the built-in Compiler Constants or any of your own constants with conditional compilation.
#If statements can be written on one line (without a #Endif) if there are no #Else or #ElseIf statements. When
written on one line, the "Then" keyword is required.
Use conditional compilation to isolate target-specific code such as API calls, file handling, UI, etc.
The block of code that is evaluated by conditional compilation is included in the build. The rest of the code that is
not evaluated is not included in the build.
Sample Code
// Set path separator
Dim separator As Text
#If TargetWin32 Then
separator = "\"
#Else
separator = "/"
#Endif
Page 124
Language
Data Types
This section contains the intrinsic data types. These are data types that are part of the Xojo language and are not
classes.
Arrays
Auto
Boolean
Color
Currency
Double
Integer
Single
Structure
Text
Page 125
Data Types
Arrays
An array is an indexed collection of data for a specific data type. Arrays themselves are not a data type, but any
data type can be defined as an array using the Dim statement.
Item Summary
Name
Arrays
Type
Concept
Methods
Targets
All
Platforms
All
Related
Syntax
Dim arrayName() As dataType
Dim arrayName(), arrayNameN() As dataType [= Array(value1, value2, ..., valueN)]
Notes
All arrays are indexed starting at position 0.
Arrays are created by specifying the upper bound for the array when you Dim it. Because arrays all start at position
0, an array has one more element than the number you use as the upper bound. For example, this creates an array
with 5 elements, which you can then access using the index:
Dim aNames(4) As Text
aNames(0) = "Bob"
aNames(1) = "Bill"
aNames(2) = "Ben"
aNames(3) = "Brad"
aNames(4) = "Bart"
Constants can be used when declaring the upper bound of an array:
Const kBound As Integer = 4
Dim aNames(kBound)
You can also create empty arrays that do not specify a size. At run-time, your code can add elements to it or you
can choose to ReDim it to a specific size. These are the two ways to create an empty array:
Page 126
Data Types
Multi-Dimensional Arrays
A multi-dimensional array has elements in 2 or more dimensions. A table would be an example of a 2-dimensional
array because it has columns and rows.
Most of the array methods are not supported for multi-dimensional arrays.
You declare multi-dimensional arrays by specifying the upper bound for each dimension:
// A 5x5 table
Dim table(4, 4)
Methods
Append(value)
Appends a new element to the end of a one-dimensional array, increasing the size of the array by one. The value
must match the data type of the array.
Sample Code
IndexOf(value, startingIndex = 0)
Searches sequentially through a one-dimensional array and returns the index of the specified value. The value must
match the data type of the array. Specify a startingIndex to start the search at the specified index in the array.
Exceptions
OutOfBoundsException
Page 127
Data Types
Sample Code
Sample Code
Pop As value
Removes the last element of the array and returns its value. The return type is the same data type as the array.
Notes
Append and Pop can be used together to treat an array as a stack. The Append method pushes a new element onto
the end of the array/stack and the Pop method removes the last element from the array/stack and returns its value.
Exceptions
OutOfBoundsException
Sample Code
// Push three values onto an array and then Pops off the values
Dim stack() As Text
stack.Append("One")
stack.Append("Two")
stack.Append("Three")
Page 128
Data Types
Remove(index As Integer)
Removes the element at postiion index from a one-dimensional array, adjusting down all elements after it. The size
of the array is reduced by one.
Exceptions
OutOfBoundsException
Sample Code
Shuffle
Randomly rearranges the elements of an array.
Notes
A Fisher-Yates shuffle is used. There is no ability to control the seed. An element of the original array has a roughly
equal chance of appearing in any position of the array after the shuffle, regardless of the size and number of
dimensions of the array.
Sample Code
Page 129
Data Types
Sort
Does an ascending sort of the elements of a one-dimensional array.
Notes
You can only use Sort with arrays for these data types: Text, Single, Double, Integer (and all related Integer types)
and String.
Sample Code
// Sort an array
Dim names() As Text = Array("Jim", "Bob", "Jack")
names.Sort
// names = "Bob", "Jack", "Jim"
// For a descending sort, simply access the array in reverse order
Dim reverseNames() As Text
For i As Integer = names.UBound DownTo 0
reverseNames.Append(names(i))
Next
// reverseNames = "Jim", "Jack", "Bob"
Page 130
Data Types
into a base array and then use SortWith on the base array, providing the object array as a withArray.
Sample Code
Sample Code
Data Types
Page 132
Data Types
Item Summary
Name
Auto
Type
Data Type
Inherits
n/a
Implements
n/a
Targets
All
Platforms
All
Related
Introspection
Notes
Once a value is placed into an Auto variable, it is treated as if it is that type of the value. For example, if you put an
Integer into an Auto variable, you can not later use it as a Text. You'll have to first assign it to an Integer and then
convert it to a Text using intVal.ToText.
You can use Introspection to check the type of the value contained in an Auto variable.
You can assign a value of a different type to an Auto that already had a value.
Examples
Simple Auto examples:
// Add an Auto containing an integer
Dim num As Auto
num = 42
Dim sum As Integer
sum = num + 10
// Display an Auto containing an integer
Dim numInt As Integer = num
Dim output As Text
output = numInt.ToText // output contains "42"
// Convert an Auto containing a Double to Text
Dim num As Double = 5.5
Page 133
Data Types
Page 134
Data Types
Boolean
Boolean is a data type used to store True or False. The default value is False.
Boolean
Type
Data Type
Targets
All
Platforms
All
Related
Example
Declares boolean variables and set their values to True:
Dim IsTaxable As Boolean
IsTaxable = True
Dim DocumentModified As Boolean = True
Enable a TextField:
TextField1.Enabled = True
Page 135
Data Types
Color
The data type for storing color values with an optional alpha component.
Color
Type
Data Type
Constants
Black, Blue, Brown, Clear, Cyan, DarkGray, Gray, Green, LightGray, Magenta, Orange, Purple, Teal,
White, Yellow
Methods
Targets
All
Platforms
All
Related
iOSGraphics
Constants
Black
&c000000
Blue
&c0000FF
Brown
&c996633
Clear
&c000000FF
Cyan
&c00FFFF
DarkGray
&c555555
Gray
&c808080
Green
&c00FF00
LightGray
&cAAAAAA
Magenta
&cFF00FF
Orange
&cFF8000
Purple
&c800080
Red
&cFF0000
Teal
&c008080
White
&cFFFFFF
Page 136
Data Types
Yellow
&cFFFF00
Methods
HSV(h As Double, s As Double, v As Double) As Color
Create a Color from hue, saturation and value.
Page 137
Data Types
Currency
A a decimal number that holds 15 digits to the left of the decimal point and 4 digits to the right. The default value of
a Currency is 0.0.
Currency
Type
Data Type
Methods
ToText
Shared Methods
FromText
Targets
All
Platforms
All
Related
Double
Notes
Currency is a 64-bit fixed-point decimal. This means that Currency does not have some of the rounding issues that
are inherent in floating-point numbers stored in Double.
Use Currency instead of Double when storing monetary values. Since Double is a standard double-precision floatingpoint number, it is unable to store some specific decimal values. The Currency type avoids these issues, which can
be particularly important with rounding and when dealing with money.
Methods
ToText(Optional locale As Locale) As Text
Converts a currency value to a Text value using the specified locale.
Example
Shared Methods
Page 138
Data Types
If the Text value does not contain a valid currency for the locale.
Example
Page 139
Data Types
Double
A double-precision floating-point number. The default value of a Double is 0.0.
Double
Type
Data Type
Methods
Equals, ToText
Shared Methods
FromText, Parse
Targets
All
Platforms
All
Related
Currency, Single
Notes
Double is an IEEE double-precision, floating-point value. This means it is speedy but has some limitations in the type
of values it can contain. For more information, refer to the wikipedia page about floating point.
In most situations you should use Currency when dealing with monetary values.
Methods
Equals(numValue As Double, maxUIps As Integer) As Boolean
Compares two floating point values within a specified tolerance.
Parameters
numValue
maxUIps
The number of units in the last position that are used to denote the acceptable range in the test of
equality. The default is 1. If you pass zero, then the test is the same as with =.
Returns
True if the Double is equal to numValue within the tolerance specified by maxUIps.
Notes
Use this method rather than = when you need to determine whether two floating point numbers are close enough in
value to be considered equal. This can be used to account for the imprecision of floating point division on
computers, for example. It allows for a user-specified rounding error.
Page 140
Data Types
Sample Code
ToText(Extends value As Double, Optional locale As Locale, format As Text = "") As Text
Converts a Double value to a Text value using the optional locale and format.
Notes
Refer to Unicode Number Format Patterns for a list of formats.
Sample Code
Shared Methods
FromText(theText As Text, Optional locale As Locale) As Double
Converts a Text value that containing a number that can be represented as a double to a Double.
Sample Code
Page 141
Data Types
Notes
Numbers are converted only if they are found at the beginning of the text. Any numbers that follow a non-numeric
value are ignored. Empty text returns 0.
Sample Code
Dim d As Double
d = Double.Parse("123ABC")
// d = 123
Page 142
Data Types
Single
A Single-precision floating-point number. The default value of a Single is 0.0.
Single
Type
Data Type
Methods
ToText
Shared Methods
FromText, Parse
Targets
All
Platforms
All
Related
Currency, Double
Notes
Single is an IEEE single-precision, floating-point value. This means it is speedy but has some limitations in the type
of values it can contain. For more information, refer to the wikipedia page about floating point.
In most situations you should use Currency when dealing with monetary values.
Methods
ToText(Extends value As Single, Optional locale As Locale, format As Text = "") As Text
Converts a Double value to a Text value using the optional locale and format.
Notes
Refer to Unicode Number Format Patterns for a list of formats.
Examples
Page 143
Data Types
Shared Methods
FromText(theText As Text, Optional locale As Locale) As Single
Converts a Text value that containing a number that can be represented as a single to a Single.
Examples
Dim s As Single
s = Single.Parse("123ABC")
// s = 123
Page 144
Data Types
Integer
Used to store integer values. The default value is 0. Generally you will use the Integer data type (equivalent to Int32
on 32-bit builds or Int64 on 64-bit builds when available) or UInteger (equivalent to UInt32 on 32-bit builds or UInt64
on 64-bit builds when available). There are also other size-specific integer data types that are available, primarily for
dealing with external OS APIs.
Integer
Type
Data Type
Bytes
Range
-2,147,483,648 to 2,147,483,647
Methods
Shared Methods
Targets
All
Platforms
All
Related
Name
UInteger
Type
Data Type
Bytes
Range
0 to 4,294,967,295
Bytes Used
Number Range
Int8
-128 to 127
Int16
-32,768 to 32,767
Int32
-2,147,483,648 to 2,147,483,647
Int64
UInt8 or Byte
0 to 255
UInt16
0 to 65,535
UInt32
0 to 4,294,967,295
Page 145
Data Types
Bytes Used
8
Number Range
0 to 2^64-1 (18,446,744,073,709,551,615)
Notes
If you assign a value that is larger (or smaller) than what the specific Integer type can hold, then the value will
"overflow". This means the value will wrap around to the corresponding largest or smallest value and continue from
there.
Methods
ToBinary(Optional minimumDigits As Integer) As Text
Converts the integer value to a Text containing its binary representation.
Sample Code
Dim i As Integer = 8
Dim binary As Text = i.ToBinary(4) // binary = "1000"
Dim i As Integer = 10
Dim octal As Text = i.ToOctal(4) // octal = "0012"
Page 146
Data Types
Notes
Refer to the Unicode Technical Standard #35, appendix G (Number Format Patterns) for information on how to
specify a format.
Sample Code
Display an Integer value in a Label:
Dim i As Integer = 42
Dim t As Text = "The number is " + i.ToText</code>
// Add to an Integer directly and convert the new value
Dim n As Integer = 5
Dim t As Text = Integer(n+1).ToText
Shared Methods
FromBinary(theText As Text) As Integer
Converts a text form of a binary number to an Integer.
Sample Code
Convert "0110" to the integer value of 6:
Dim value As Integer
value = Integer.FromBinary("0110") // value = 6
Page 147
Data Types
Dim i As Integer
i = Integer.Parse("123ABC")
// i = 123
Page 148
Data Types
Structure
Type
Data Type
Inherits
n/a
Implements
n/a
Methods
ByteValue
Targets
All
Platforms
All
Related
MemoryBlock, Auto
Notes
Once you have defined a structure, you can use it in almost any context where you would use any other data type.
Use the dot syntax to access the fields of the structure.
Methods
ByteValue(littleEndian As Boolean, Assigns value() As Byte)
ByteValue(littleEndian As Boolean) As Byte()
Gets or sets the structure data using a byte array.
Page 149
Data Types
Text
The Text type is used to store text with a defined encoding. It is a modern replacement for String, which did not
require an encoding. By using Text instead of String, you can be assured that your text data always has a
known encoding and is never treated as just a collection of raw data. All classes, methods and properties in the Xojo
framework use the Text type. You can convert Text data to a String, if necessary.
Text
Type
Data Type
Constants
CompareCaseSensitive
Methods
Shared Methods
Targets
All
Platforms
All
Related
TextEncoding
Notes
The Text type is an immutable series of Unicode scalar values.
The documententation is very deliberate in its use of the terms character, code point, and scalar value. A character,
in this context, refers to an extended grapheme cluster (also known as a user-perceived character). The terms code
point and scalar value retain the meaning defined in the Unicode standard.
All of the APIs on the Text type operate in characters. For example, if the APIs worked in terms of Unicode code
points, it would be possible to corrupt data using Left/Mid/Right if the positions happened to be in the middle of a
composed character or grapheme cluster. Working in characters also avoids situations where the length of '' can
be either 1 or 2.
Many of the functions in this API optionally take locales because different locales can have special rules for casing
and comparing. The default behavior being to perform the operation in a locale-insensitive manner. Functions that
perform comparisons also take option flags that specify how to perform the comparison (e.g. case sensitively).
These flags are bit flags that are combined via the bitwise Or operator. If the combination of options is invalid, an
exception is thrown.
To get the bytes for the Text, you must use the TextEncoding class and specify an explicit encoding you wish to get
them as.
Page 150
Data Types
Sample Code
Assign text to a Label:
Dim t As Text
t = "Hello, World"
MyLabel.Text = t
Text is available in all project types, so you can also use it in place of String. A Text value can be converted to a
String, so code like this works:
Dim t As Text = "Hello, World!"
MsgBox(t) // MsgBox takes a String, but this works because Text can be converted to
String
You can also convert a String with a known encoding to a Text using the String.ToText method:
Dim s As String = "Hello"
Dim t As Text = s.ToText // t = "Hello"
Some String History
Constants
CompareCaseSensitive
Page 151
Data Types
Methods
BeginsWith(other As Text, options As Integer = 0, Optional locale As Locale = Nil) As Boolean
Determines whether the beginning of this Text instance matches the other text when compared using the specified
comparison options and locale.
Parameters
other
options
locale
Return Value
Returns True if other matches the beginning of the text, False if it does not.
Notes
By default this performs a case-insensitive comparison. The compareOptions parameter is a bitfield that can be
used to customize the comparison, with different options being combined via the Or operator. Invalid combinations
will cause an exception to be raised. The only flag supported currently is CompareCaseSensitive.
By default comparisons are done in an invariant locale (i.e. not dependent on the user's preferences). The locale
parameter can be used to specify an explicit locale to do comparisons in.
Exceptions
RuntimeException
InvalidArgumentException
Sample Code
Dim t As Text
t = "All we have to decide is what to do with the time that is given to us."
If t.BeginsWith("All") Then
Label1.Text = "Text starts with 'All'."
End If
Page 152
Data Types
Characters As Iterable
Returns an iterator that yields a Text value for each character, in order of first to last.
Codepoints As Iterable
Returns an iterator that yields integer values for each Unicode scalar value that comprises the text.
Sample Code
Compare(other As Text, Optional options As integer = 0, Optional locale As Locale = Nil) As Integer
Compares a text value with another text value. A non-empty text is always greater than an empty text. By default, a
case-insensitive comparison is done.
Parameters
other
options
locale
Return Value
Returns a negative integer if the value is less than other, 0 if the two values are equal, and a positive integer if other
is greater than the value.
Notes
By default this performs a case-insensitive comparison. The options parameter is a bitfield that can be used to
customize the comparison, with different options being combined via the Or operator. Invalid combinations will
cause an exception to be thrown. The only flag supported currently is CompareCaseSensitive.
By default comparisons are done in an invariant locale (i.e. not dependent on the user's preferences). The locale
parameter can be used to specify an explicit locale to do comparisons in.
Page 153
Data Types
Exceptions
RuntimeException
Sample Code
Empty As Boolean
Returns whether or not the text has contents. This will always be as fast or faster than checking length against zero.
Return Value
Returns True when the text is empty, False when it is not.
Sample Code
EndsWith(other As Text, Optional options As integer = 0, Optional locale As Locale = Nil) As Boolean
Determines if the text ends with other text.
Parameters
other
options
locale
Page 154
Data Types
Return Value
Returns True if the text ends with other, False if it does not.
Notes
By default this performs a case-insensitive comparison. The compareOptions parameter is a bitfield that can be
used to customize the comparison, with different options being combined via the Or operator. Invalid combinations
will cause an exception to be thrown. The only flag supported currently is CompareCaseSensitive.
By default comparisons are done in an invariant locale (i.e. not dependent on the user's preferences). The locale
parameter can be used to specify an explicit locale to do comparisons in.
Exceptions
RuntimeException
InvalidArgumentException
compareOptions
locale
Return Value
Returns the zero-based loation of other within the text. If other is not found, returns -1.
Notes
By default this performs a case-insensitive comparison. The compareOptions parameter is a bitfield that can be
used to customize the comparison, with different options being combined via the Or operator. Invalid combinations
will cause an exception to be thrown. The only flag supported currently is CompareCaseSensitive. By default
comparisons are done in an invariant locale (i.e. not dependent on the user's preferences). The locale parameter
Page 155
Data Types
InvalidArgumentException
other
options
locale
Return Value
Returns the zero-based location of other within the text. If other is not found, returns -1.
Notes
By default this performs a case-insensitive comparison. The compareOptions parameter is a bitfield that can be
used to customize the comparison, with different options being combined via the Or operator. Invalid combinations
will cause an exception to be thrown. The only flag supported currently is CompareCaseSensitive. By default
comparisons are done in an invariant locale (i.e. not dependent on the user's preferences). The locale parameter
can be used to specify an explicit locale to do comparisons in.
Exceptions
RuntimeException
InvalidArgumentException
OutOfBoundsException
Data Types
OutOfBoundsException
Exceptions
OutOfBoundsException
Sample Code
Length As Integer
The number of characters.
Sample Code
Sample Code
Set text to lower case:
Dim t As Text = "Hello, World!"
Page 157
Data Types
Exceptions
OutOfBoundsException
OutOfBoundsException
Sample Code
Get "World!" from text:
Dim t As Text = "Hello, World!"
t = t.Mid(7) // t = "World!"
length
Exceptions
OutOfBoundsException
Sample Code
Get "World" from text:
Page 158
Data Types
replace
options
locale
Notes
By default this performs a case-insensitive comparison. The compareOptions parameter is a bitfield that can be
used to customize the comparison, with different options being combined via the Or operator. Invalid combinations
will cause an exception to be thrown. The only flag supported currently is CompareCaseSensitive. By default
comparisons are done in an invariant locale (i.e. not dependent on the user's preferences). The locale parameter
can be used to specify an explicit locale to do comparisons in.
Exceptions
RuntimeException
InvalidArgumentException
Example
Replace "World" with "Mars":
Dim t As Text = "Hello, World!"
Dim newText As Text
newText = t.Replace("World", "Mars") // newText = "Hello, Mars!"
Data Types
value. If the input does not contain the requested value, nothing is replaced and the input is returned.
Parameters
find
replacement
options
locale
Notes
By default this performs a case-insensitive comparison. The compareOptions parameter is a bitfield that can be
used to customize the comparison, with different options being combined via the Or operator. Invalid combinations
will cause an exception to be thrown. The only flag supported currently is CompareCaseSensitive. By default
comparisons are done in an invariant locale (i.e. not dependent on the user's preferences). The locale parameter
can be used to specify an explicit locale to do comparisons in.
Exceptions
RuntimeException
InvalidArgumentException
Example
Replaces all instances of "l" with "1":
Dim t As Text = "Hello, World!"
Dim newText As Text
newText = t.ReplaceAll("l", "1") // newText = "He11o, Wor1d!"
Exceptions
OutOfBoundsException
Page 160
Data Types
Example
Get "World!" from text:
Dim t As Text = "Hello, World!"
t = t.Right(6) // t = "World!"
Split As Text()
Creates an array of the characters in the Text.
Example
Splits the text into an array with one element for each character:
Dim t As Text = "Hello, World!"
Dim chars() As Text
chars = t.Split
compareOptions
locale
(Optional) The locale to use for comparisons. By default an invariant locale (not dependent on
the system settings) is used.
Notes
By default this performs a case-insensitive comparison. The compareOptions parameter is a bitfield that can be
used to customize the comparison, with different options being combined via the Or operator. Invalid combinations
will cause an exception to be thrown. The only flag supported currently is CompareCaseSensitive.
By default comparisons are done in an invariant locale (i.e. not dependent on the user's preferences). The locale
parameter can be used to specify an explicit locale to do comparisons in.
Page 161
Data Types
Exceptions
RuntimeException
InvalidArgumentException
Example
Split the text into "Hello" and "World":
Dim t As Text = "Hello World"
Dim words() As Text
words = t.Split(" ")
(Optional) The locale to use for comparisons. By default an invariant locale (not dependent on the system
settings) is used.
Example
Convert text to "Hello, World!":
Dim t As Text = "hello, world!"
t = t.TitleCase // t = "Hello, World!"
Exceptions
NilObjectException
If encoding is Nil.
Page 162
Data Types
UnsupportedFormatException
If the text is cannot be represented in the given encoding. For example, Emoji is
not representable in the ASCII encoding.
Trim As Text
Trims whitespace, as defined in the Unicode standard, from the beginning and end of the text. If the value is empty
or consists entirely of whitespace, an empty Text is returned.
Example
Removes beginning and ending white space:
Dim t As Text = "
Hello, World!
t = t.Trim // t = "Hello, World!"
"
TrimLeft As Text
Trims whitespace, as defined in the Unicode standard, from the beginning. If the value is empty or consists entirely
of whitespace, an empty Text is returned.
Example
Removes beginning white space:
Dim t As Text = "
Hello, World!
t = t.Trim // t = "Hello, World!
"
"
TrimRight As Text
Trims whitespace, as defined in the Unicode standard, from end of the text. If the value is empty or consists entirely
of whitespace, an empty Text is returned.
Removes ending white space:
Dim t As Text = "
Hello, World!
"
t = t.Trim // t = "
Hello, World!"
Page 163
Data Types
Parameters
locale
Example
Set text to upper case:
Dim t As Text = "Hello, World!"
t = t.Uppercase // t = "HELLO, WORLD!"
Shared Methods
FromUnicodeCodepoint(codepoint As UInt32) As Text
Creates a new Text object from a single Unicode scalar value.
Parameters
codepoint
Exceptions
UnsupportedFormatException
Example
Get the EndOfLine character:
Dim EOL As Text = Text.FromUnicodeCodepoint(10)
encoding
Exceptions
Page 164
Data Types
NilObjectException
If str is Nil.
NilObjectException
If encoding is Nil.
UnsupportedFormatException
separator
The separator used to separate each element in the array when joined into the text.
Exceptions
NilObjectException
If items is Nil.
Example
Create a text from the array containing "Hello" and "World":
Dim words() As Text = Array("Hello", "World")
Dim newText As Text
newText = Text.Join(words, ",") // newText = "Hello,World"
Page 165
Data Types
CFStringRef
CString
Delegate
Ptr
WString
Page 166
Item Summary
Name
CFStringRef
Type
Data Type
Inherits
n/a
Implements
n/a
Targets
All
Platforms
All
Related
Declare
Notes
CFStringRef implicitly converst to String or Text when assigned to String or Text variables.
Memory Management
The Xojo framework handles memory management of CFStringRefs smartly.
Based on rules explained under Apple's Create Rule, a call to a declared function will either retain (CFRetain) the
retrieved value or not. Once the CFStringRef object goes out of scope (i.e. it's no longer referenced by Xojo code), it
will be released by calling CFRelease.
That means that you usually do not have to worry about proper Retain/Release calls for CFStringRef objects you
retrieve using declares.
Page 167
Item Summary
Name
CString
Type
Data Type
Inherits
n/a
Implements
n/a
Targets
All
Platforms
All
Related
Declare, MemoryBlock
Notes
You can assign a standard String variable to it and it will be terminated with a null automatically.
CString implicitly converts to String assigned to String variables.
To convert a Text value to a CString, call Text.ToCString.
Page 168
Item Summary
Name
Delegate
Type
Data Type
Inherits
n/a
Implements
n/a
Methods
Invoke
Targets
All
Platforms
All
Related
Notes
A Delegate data type is an object representing a specific method. It is a function pointer with a method signature.
Delegates decouple interface from implementation in a similar way to events or interfaces. This decoupling allows
you to treat a method implementation as a variable that is changeable based on run-time conditions. They
represent methods that are callable without knowledge of the target object. You can change the function the
delegate points to on the fly.
A Delegate can be declared in either a module or a class. You use the Insert Delegate menu command or the Add
button in the Code Editor to create a Delegate entry.
A Delegate must have a name and can have optional parameters and a return type, which must match the method
to which it delegates.
You cannot directly create a variable of type Delegate. You can only create variables of the type of Delegate that
you actually added to the module or class.
Constructors
Constructor(p As Ptr)
Creates a delegate based on the supplied pointer, which is assumed to be correct for the delegate type.
Sample Code
Assume there is a Delegate declared as SimpleProc:
Page 169
Methods
Invoke([optional parameters) As [optional type]
Calls the method pointed to by the delegate. You must specify the same parameters (and return value) as the
method to which the delegate refers.
Page 170
Item Summary
Name
Ptr
Type
Data Type
Inherits
n/a
Implements
n/a
Properties
Boolean, Byte, CFStringRef, Class, Color, CString, Currency, Double, Int16, Int32, Int64, Int8,
Integer, Object, Ptr, Short, Single, String, Text, UInt16, UInt32, UInt64, UInt8, UInteger, Variant,
WindowPtr, WString
Targets
All
Platforms
All
Related
Declare
Notes
You can compare one Ptr to another Ptr or to Nil.
You can conver the value referenced to by the pointer to a specific data type using the properites listed below.
Properties
Boolean(offset As Integer = 0) As Boolean
Byte(offset As Integer = 0) As Byte
CFStringRef(offset As Integer = 0) As CFStringRef
Class(offset As Integer = 0) As Class
Color(offset As Integer = 0) As Color
Page 171
Page 172
Page 173
Item Summary
Name
WString
Type
Data Type
Inherits
n/a
Implements
n/a
Targets
All
Platforms
All
Related
Declare, MemoryBlock
Notes
You can assign a standard String to it and it will be converted to UTF-16 and terminated automatically.
WString implicitly converts to String when assigned to a String variable.
Page 174
Language
Literals
These syntax elements are used to define literal values.
Syntax Elements
""
Represents a Text or String literal.
Notes
To denote empty text, use two double quotes with no spaces.
An empty text value is not equivalent to Nil. Nil represents a non-existing object.
To include a quote within the text, enter two consective double quotes.
The ampersand character (&) is often interpreted as a keyboard shortcut when used for user interface labels, such
as for buttons, menus, label controls. If you want to display an & in these situation, simply use two of them together,
such as "&&".
Sample Code
&b
Represents binary literals.
Notes
Binary literals are stored in Integer data types as integer values.
Sample Code
&cRRGGBBAA
Represents a Color literal.
Page 175
Language
Notes
Specify each portion of the color as hexadecimal.
RR
GG
BB
AA
Optional Alpha channel (transparency) in the color. The range is 00 (opaque) to FF (fully transparent).
Using this literal is equivalent to using the Color.RGB method, except the RGB method uses decimal values rather
than hexadecimal.
Sample Code
&h
Represents hexadecimal literals.
Notes
Hexadecimal literals are stored in Integer data types as integer values.
&o
Represents octal literals.
Notes
Octal literals are stored in Integer data types as integer values.
&u
Used to create a Unicode codepoint (hex value) as Text (or String) constants.
Notes
Unicode Codepoint Chart
Sample Code
Language
Operators
This section describes the operators in the Xojo Programming Language.
Addition (+)
AddressOf
And
CType
Division (/)
Equals (=)
Exponentiation (^)
If
Is
IsA
Mod
Multiplication (*)
Negation
New
Not
Or
Subtraction (-)
Xor
WeakAddressOf
Operator Precedence
When there are multiple operators in an expressions, they are evaluated in order of precedence. For example,
consider this mathematical expression:
5 + 2 * 3
which has both multiplication and addition operators. Operator precedence dictates that multiplication is done
before addition, so the above expression evaluates to 11.
You can always use parenthesese to force a particular evaluation order since parenthesese are evaluated first. For
example, if you want to do the "5+2" before the multiplication, you would write the expression like this:
(5 + 2) * 3
Description
Dot operator for accessing
class members.
AddressOf, WeakAddressOf
IsA
Exponentiation (^)
Negation (-)
Not
Multiplication (*), Division (/), Integer Division (\), Mod
Subtraction (-), Addition (+)
Page 177
Language
Operator
Description
Equals (=), Greater Than (>), Less Than (<), Greater Than Equals (>=), Less
Than Equals (<=), Not Equals (<>)
And
Or, Xor
Pair (:)
If there is more than one of the same operator in an expression, the precendence goes from left to right in the table.
All operators are left-associative except for Pair (:) and Exponentiation (^). Left association means that an
expression such as "True Or False Or True" evaulates as if it were written like "(True Or False) Or True". Conversely,
right association means that an expression such as "2^3^2" evaluates as "2^(3^2)".
Page 178
Operators
Operator Summary
Name
Multiplication
Type
Operator
Token
Targets
All
Platforms
All
Related
Syntax
result = expression1 + expression2
Parameters
result
expression1
expression2
Notes
You can use the Operator_Add method to define this operator for classes.
Sample Code
Dim sum As Integer
sum = 1 + 2 + 3 // sum = 6
Dim name As String
name = "Bob " + "Roberts" // name = "Bob Roberts"
Page 179
Operators
AddressOf (Operator)
Gets the address of a method (as a delegate). Can be used with AddHandler, Declares and other advanced
commands.
Operator Summary
Name
AddressOf
Type
Operator
Implements
n/a
Targets
All
Platforms
All
Related
AddHandler, Delegate
Syntax
delgate = AddressOf methodName
Parameters
methodName
delegate
Page 180
Operators
And (Operator)
Performs a logical And comparison of two boolean expressions or a bitwise comparison of two integers.
Operator Summary
Name
And
Type
Operator
Targets
All
Platforms
All
Related
Or
Syntax
result = expression1 And expression2
result = integer1 And integer2
Parameters
result
expression1
expression2
integer1
integer2
Notes
Boolean Comparison
The most common use of And is to compare to boolean expressions. Refer to the truth table below to see the results
from a comparison of boolean expressions
Expression1
Expression2
And
Or
Xor
True
True
True
True
False
True
False
False
True
True
False
True
False
True
True
False
False
False
False
False
Page 181
Operators
Bitwise Comparison
If you pass two integers, And returns an integer that is the result of comparing each bit of the two integers and
assigning 1 to the bit position in the integer returned if both bits in the same position in the integers passed are 1.
Otherwise, 0 is assigned to the bit position.
The following table gives the results for bitwise operators.
Integer1
Integer2
And
Or
Xor
The Operator_Add method can be used to define the And operator for classes.
Use Within If Statements
When used within an If..Then statement, once the first expression results to False, none of the subsequent
expressions are evaluated. In this example, the IsValid method is not called because the first expression is False:
Dim b As Boolean = False
If b And IsValid("value") Then // IsValid does not get called
...
End If
Sample Code
Dim
Dim
Dim
Dim
a
b
c
d
a
b
d
d
True
True
a And b // Returns True
a And c // Returns False
=
=
=
=
As
As
As
As
Boolean
Boolean
Boolean // defaults to False
Boolean // defaults to False
Page 182
Operators
CType (Operator)
Explicitly converts a value of one data type to another data type.
Operator Summary
Name
CType
Type
Operator
Targets
All
Platforms
All
Related
Syntax
result = CType(value, dataType)
Parameters
result
value
dataType
Notes
The CType operator is the explicit version of type conversion. Implicit conversion is available via the assignment (=)
operator.
CType does not necessarily preserve the value across the types. It converts the passed value source type to the
destination data type. In that regard, it is identical to implicit conversion. If you are using CType to convert a real
number data type (e.g., Single, Double, Currency) to an Integer data type, it truncates the value rather than rounds
it. Sign extension is preserved when converting from a signed data type to another signed data type. Conversion
between signed and unsigned types (either way) preserves the bits but not the value.
Sample Code
Dim s As Single
Dim i As Integer
i = 5
Page 183
Operators
s = i // implicit conversion
s = CType(i, Single) // explicit conversion
Dim d As Double
Dim i As Integer
d = 566.75
i = CType(d, Integer) // returns 566
i = d // returns 567
Page 184
Operators
Operator Summary
Name
Division
Type
Operator
Token
Targets
All
Platforms
All
Related
Syntax
result = expression1 / expression2
Parameters
result
expression1
expression2
Notes
Use this operator when you require division that considers the decimal portion of the expressions.
Regardless of the datatypes of expression1 and expression2, both operands are coerced to Doubles and the result is
a Double. If you divide by zero, the result is positive or negative infinity, except if the numerator is also zero. In that
case, the result is NaN. For that reason, you should always check to see whether the denominator is zero before
dividing.
Use the \ operator for integer division or the Mod operator to get the remainder of the division.
You can use the Operator_Multiple method to define this operator for classes.
Sample Code
Dim x As Double
x = 50.56 / 30.34 // x = 1.6664469
Page 185
Operators
Operator Summary
Name
Division
Type
Operator
Token
Targets
All
Platforms
All
Related
Syntax
result = expression1 \ expression2
Parameters
result
expression1
expression2
Notes
Use this operator when you require division that does not consider the decimal portion of the expressions. The result
may differ from systems that round the expressions prior to the division.
If expression1 and expression2 are not integers, they are coerced to Int32s. The result is an Integer. If you divide by
zero, the result is undefined even if the numerator is also zero. The only expected behavior is the application will not
crash. For that reason, you should always check to see whether the denominator is zero before dividing.
When converting a floating point number to an integer, there is always the chance of data loss. The same is true
when a floating-point value holds a sentinel such as infinity or NaN. Integers do not reserve space for sentinel
values, so that information is lost. Converting a floating-point number that represents a sentinel to an Integer yields
undefined results.
Use the / operator for floating point division and the Mod operator to obtain the remainder of the division.
Page 186
Operators
Sample Code
Dim x As Integer
x = 50.56 \ 30.34 // x = 1
x = 49.56 \ 25.34 // x = 1
Page 187
Operators
Equals (Operator)
Determines whether one expression is equal to another or to assign a value to an identifier. Text comparisons are
case-insensitive.
Operator Summary
Name
Equals
Type
Operator
Token
Targets
All
Platforms
All
Related
Syntax
result = expression1 = expression2
Parameters
result
expression1
expression2
result = value
Parameters
result
value
Notes
The data types of expression1 and expression2 must match. You can make comparisons between objects of any
data type and between objects. If you compare objects, their references are compared, not their contents. For
example, when you compare two FolderItems, this operator determines whether they have the same reference, not
whether they point to the same file.
Use the Text.Compare method to do case-sensitive string comparisons.
Page 188
Operators
Sample Code
Dim t1 As Text = "Hello"
Dim t2 As Text = "There"
If t1 = t2 Then
// t1 is equal to t2
Else
// t1 is not equal to t2
End If
Page 189
Operators
Operator Summary
Name
Not Equals
Type
Operator
Token
<>
Targets
All
Platforms
All
Related
Equals (=)
Syntax
result = expression1 <> expression2
Parameters
result
expression1
expression2
Notes
The data types of expression1 and expression2 must match. You can make comparisons between objects of any
data type and between objects. If you compare objects, their references are compared, not their contents. For
example, when you compare two FolderItems, this operator determines whether they have the same reference, not
whether they point to the same file.
You can use Not Equals (<>) with objects to test if they are Nil.
Use the Text.Compare method to do case-sensitive string comparisons.
Use the Operator_Compare method to do comparsions for classes.
Sample Code
Dim t1 As Text = "Hello"
Dim t2 As Text = "There"
Page 190
Operators
If t1 <> t2 Then
// t1 is not equal to t2
Else
// t1 is equal to t2
End If
Page 191
Operators
Operator Summary
Name
Exponentiation
Type
Operator
Token
Targets
All
Platforms
All
Related
Syntax
result = expression1 ^ expression2
Parameters
result
expression1
expression2
Notes
You can use the Operator_Power method to define this operator for classes.
Sample Code
Dim
i =
i =
i =
i As Double
2 ^ 2 // i = 4
(2 + 3) ^ (4 - 2)) // i = 25
3.75 ^ 3.5 // i = 102.12
Page 192
Operators
If (Operator)
A trinary operator that evaluates an expression and returns results when it is True or False.
Operator Summary
Name
If
Type
Operator
Targets
All
Platforms
All
Related
Syntax
result = If(expression, resultWhenTrue, resultWhenFalse)
Parameters
result
resultWhenTrue
resultWhenFalse
Notes
The return type is the common type between the resultWhenTrue and resultWhenFalse. For example, if an Int8 and
an Int32 are used as result values, the result type will actually be Int32. Having no common type results in a Type
Mismatch compile error.
This operator uses the same evaluation rules as a normal If..Then statement. Only the result that is needed gets
evaluated.
Sample Code
Dim myInteger As Integer = 41
Dim result As Text
result = If(myInteger > 40, "Big number", "Small number")
Page 193
Operators
Operator Summary
Name
Greater Than
Type
Operator
Tokens
>, >=
Targets
All
Platforms
All
Related
Equals (=)
Syntax
result = expression1 > expression2
Parameters
result
expression1
expression2
Parameters
result
expression1
expression2
Notes
Text is "greater than" another Text if it is last when the two strings are sorted alphabetically. Use Text.Compare to
do a case-sensitive comparisons.
Use the Operator_Compare method to define comparisons for classes.
Sample Code
Page 194
Operators
Page 195
Operators
Is (Operator)
Compares two object references to determine whether they both refer to the same object.
Operator Summary
Name
Is
Type
Operator
Targets
All
Platforms
All
Related
IsA
Syntax
result = object1 Is object2
Parameters
result
object1
object2
Notes
The Is operator returns True if object1 and object2 actually refer to the same object. It checks identity, not contents,
so it is not affected by the presence of a comparison operator.
Sample Code
Dim d1 As New Dictionary
Dim d2 As Dictionary
d2 = d1
If d1 Is d2 Then
// d1 and d2 are the same reference
Else
// d1 and d2 are not the same reference
End If
Page 196
Operators
IsA (Operator)
Compares a class instance (object) with a class type or interface.
Operator Summary
Name
IsA
Type
Operator
Targets
All
Platforms
All
Related
Syntax
result = object IsA class
Parameters
result
A Boolean value that is True when object is an instance of class, a subclass of class or implements the
class interface.
object
class
Notes
If object is of type class, then IsA returns True; if not, it returns False. If object is Nil, then IsA returns False. The IsA
operator returns True for the object's own class as well as the super class from which that class was derived, all the
way to the Object class. IsA will report that all classes ultimately derive from Object.
Remember that object must always be a class instance, not just a variable with the class of the type. For example,
this code always returns False because
Dim d As Dictionary
// Returns False because d is not an instance
If d IsA Dictionary Then
...
Else
...
End If</code>
Page 197
Operators
Sample Code
// Count all the Labels on a Window
Dim labelCount As Integer
For i As Integer = 0 To Self.ControlCount-1
If Self.Control(i) IsA Label Then labelCount = labelCount + 1
Next
Page 198
Operators
Operator Summary
Name
Less Than
Type
Operator
Tokens
<, <=
Targets
All
Platforms
All
Related
Syntax
result = expression1 < expression2
Parameters
result
expression1
expression2
Parameters
result
expression1
expression2
Notes
Text is "less than" another Text if it is first when the two strings are sorted alphabetically. Use Text.Compare to do a
case-sensitive comparisons.
Use the Operator_Compare method to define comparisons for classes.
Sample Code
Page 199
Operators
Page 200
Operators
Mod (Operator)
Calculates the remainder of the division of two numbers.
Operator Summary
Name
Mod
Type
Operator
Targets
All
Platforms
All
Related
Syntax
result = number1 Mod number2
Parameters
result
number1
Any number.
number2
Notes
The Mod operator divides number1 by number2 and returns the remainder as the result.
Type Rules
number1 or number2 are floaing point
number2 is 0 (zero)
undefined result
When converting a floating-point number to an Integer, there is always the possibility of data loss.
The same is true when a floating-point value holds a sentinal such as infinity (INF) or not a number
(NaN). Integers do not reserve space for sentinal values, so that information is lost. Converting a
floating-point number that represents a sentinal to an Integer yields undefinied results.
Page 201
Operators
Sample Code
Dim r As Integer
r = 5 Mod 2 // returns 1
r = 5 Mod 1.99999 // returns 0
r = -10 Mod 3 // Returns -1
r = -10 Mod -3 // Returns -1
r = 10 Mod 3 // Returns 1
r
r
r
r
r
=
=
=
=
=
10 Mod 3 // Returns 1
2 Mod 4 // Returns 2
9.3 Mod 2.75 // Returns 1
4.5 Mod 1 // Returns 0
25 Mod 5 // Returns 0
Page 202
Operators
Operator Summary
Name
Multiplication
Type
Operator
Token
Targets
All
Platforms
All
Related
Division (/)
Syntax
result = expression1 * expression2
Parameters
result
expression1
expression2
Notes
You can use the Operator_Multiple method to define this operator for classes.
Sample Code
Dim x As integer
x = 50 * 30 // x = 1500
Dim y As Integer = 42
x = y * 10 // x = 420
Page 203
Operators
New (Operator)
Creates instances of classes (instantiation).
Operator Summary
Name
New
Type
Operator
Targets
All
Platforms
All
Related
Syntax
objectInstance = New className
control = New controlSetName
The Dim and Static statements can also use New to declare a variable and assign it a value in one step.
Parameters
objectInstance
className
Notes
If the class has a Constructor defined, it is called when you instantiate it using New.
Page 204
Operators
View.AddControl.
Sample Code
// Create a Dictionary
Dim d As New Dictionary
d.Value("Name") = "Red Sox"
Page 205
Operators
Not (Operator)
Performs a logical negation of a boolean expression or a bitwise Not operation on an integer expression.
Operator Summary
Name
Not
Type
Operator
Targets
All
Platforms
All
Related
Syntax
result = Not expression
result = Not integerExpression
Parameters
result
expression
integerExpression
Notes
Boolean Comparison
The most common use of Not is to negate boolean expressions. Refer to the truth table below:
Expression
Not
True
False
False
True
Bitwise Comparison
If you pass an integer, Not returns an integer that is the result of inverting the bit values of the integer expression.
The following table gives the results for bitwise operators.
Page 206
Operators
IntegerExpression
Not
The Operator_Not method can be used to define the Not operator for classes.
Sample Code
Dim a As Boolean
Dim b As Boolean
Dim c As Boolean // defaults to False
a = True
b = Not a // b = False
b = Not c // b = True
Page 207
Operators
Or (Operator)
Performs a logical Or comparison of two boolean expressions or a bitwise comparison of two integers.
Operator Summary
Name
Or
Type
Operator
Targets
All
Platforms
All
Related
And
Syntax
result = expression1 Or expression2
result = integer1 Or integer2
Parameters
result
expression1
expression2
integer1
integer2
Notes
Boolean Comparison
The most common use of Or is to compare to boolean expressions. Refer to the truth table below to see the results
from a comparison of boolean expressions
Expression1
Expression2
And
Or
Xor
True
True
True
True
False
True
False
False
True
True
False
True
False
True
True
False
False
False
False
False
Page 208
Operators
Bitwise Comparison
If you pass two integers, And returns an integer that is the result of comparing each bit of the two integers and
assigning 1 to the bit position in the integer returned if both bits in the same position in the integers passed are 1.
Otherwise, 0 is assigned to the bit position.
The following table gives the results for bitwise operators.
Integer1
Integer2
And
Or
Xor
The Operator_Or method can be used to define the Or operator for classes.
Sample Code
Dim
Dim
Dim
Dim
a
b
c
d
a
b
d
d
True
False
a Or b // Returns True
b Or c // Returns False
=
=
=
=
As
As
As
As
Boolean
Boolean
Boolean // defaults to False
Boolean
Page 209
Operators
Operator Summary
Name
Subtraction
Type
Operator
Token
Targets
All
Platforms
All
Related
Addition (+)
Syntax
result = expression1 - expression2
result = -expression
Parameters
result
expression1
expression2
expression
Notes
You can use the Operator_Subtract method to define the subtraction operation for classes.
You can use the Operator_Negate method to define the negation operation for classes.
Sample Code
Dim diff As Integer
diff = 50 - 30 // diff = 20
Dim diff As Integer = 50
diff = -diff // diff = -50
Page 210
Operators
Page 211
Operators
Xor (Operator)
Performs a logical Xor comparison of two boolean expressions or a bitwise Xor comparison of two integers.
Operator Summary
Name
Xor
Type
Operator
Targets
All
Platforms
All
Related
Or
Syntax
result = expression1 Xor expression2
result = integer1 Xor integer2
Parameters
result
expression1
expression2
integer1
integer2
Notes
Boolean Comparison
Refer to the truth table below to see the results from a comparison of boolean expressions
Expression1
Expression2
And
Or
Xor
True
True
True
True
False
True
False
False
True
True
False
True
False
True
True
False
False
False
False
False
Page 212
Operators
Bitwise Comparison
If you pass two integers, And returns an integer that is the result of comparing each bit of the two integers and
assigning 1 to the bit position in the integer returned if both bits in the same position in the integers passed are 1.
Otherwise, 0 is assigned to the bit position.
The following table gives the results for bitwise operators.
Integer1
Integer2
And
Or
Xor
The Operator_XOr method can be used to define the Xor operator for classes.
Sample Code
Dim i As Integer
i = 5 Xor 3 // i = 6
Page 213
Operators
WeakAddressOf (Operator)
Gets the address of a method (as a delegate). Can be used with AddHandler, Declares and other advanced
commands. This uses a WeakRef interally.
Operator Summary
Name
WeakAddressOf
Type
Operator
Targets
All
Platforms
All
Related
Syntax
delgate = WeakAddressOf methodName
Parameters
methodName
delegate
Page 214
Operators
Operator Overloading
You can definte the various operators in the Xojo languages for your own classes and subclasses by overloading
these specific methods.
Summary
Name
Operator Overloading
Methods
Targets
All
Platforms
All
Related
Notes
Several of the example below use a Vector class, which is defined as follows:
Class Vector
Property x As Integer
Property y As Integer
End Class
Methods
Operator_Add(rightSide As Type1) As Type2
Operator_AddRight(leftSide As Type1) As Type2
Allows the class to support the Addition (+) operator.
Notes
The Self instance is the left operand. Use Operator_AddRight to have the Self instance be the right operand.
Sample Code
// Vector addition
Function Operator_Add(rightSide As Vector) As Vector
Dim newVector As New Vector
newVector.x = Self.x + rightSide.x
newVector.y = Self.y + rightSide.y
Page 215
Operators
Return newVector
End Function
Page 216
Operators
Operator_Convert(rightSide As Type1)
Operator_Convert As Type2
Allows the class to be converted from one type to another or allows another type to be converted to the class.
Notes
When you use the convert-to form of the operator (the one with a parameter), the compiler needs to create a new
object implicitly so that you can copy data into it. When you use a convert-to operator, the compiler needs to create
a new instance of the item it located the Operator_Convert method on, and then it calls that method to complete the
conversion. When it creates the new instance of the item, it does not call any constructors for it. The
Operator_Convert method takes the place of the constructor.
When you use a convert-from operator (the one without a parameter), the compiler doesn't have to do any extra
work. Whenever an implicit (or explicit) conversion needs to take place, the compiler looks for the convert-from
operator, and if it finds one, it calls it. The function itself already does all of the conversion work.
Constructors are not called when doing a convert-to operation. That's simply something to be
aware of. If you're doing required work in your constructor, you'll need to perform that work
yourself in the conversion. This generally won't need to happen, since most constructors simply
initialize things to sensible values, and conversion operations would do exactly the same thing. But
if you are doing some sort of Declare work, it may still be necessary. For instance, let's say that
you were doing some sort of COM work on Windows. Your Operator_Convert method had better
call CoInitialize just to be on the safe side.
Sample Code
Operators
End If
// This allows you to write code like this, which converts a Person to a Text value for
use by a Label:
Label1.Text = p2
Operator_Divide
Operator_DivideRight
Allows the class to support the division (/) operator.
Sample Code
Operator_IntegerDivide
Operator_IntegerDivideRight
Allows the class to support the integer division (\) operator.
Sample Code
Operator_Lookup(name As String)
Allows the class to handle dot notation references that are not class members.
Notes
If you implement Operator_Lookup on a class, you will no longer get compilation errors if you, for example,
inadvertently misspell a property name. Instead, the Operator_Lookup method is called at runtime and is passed the
Page 218
Operators
Operator_Modulo
Operator_ModuloRight
Allows the class to handle the Mod operator.
Sample Code
Operator_Multiply
Operator_MultiplyRight
Allows the class to handle the multiplication (*) operator.
Sample Code
Page 219
Operators
End If
Operator_Negate
Allows the class to handle the negation (-) operator.
Sample Code
Operator_Not
Allows the class to handle the Not operator.
Sample Code
Operator_Or
Operator_OrRight
Allows the class to handle the Or operator.
Sample Code
Operator_Power
Operator_PowerRight
Allows the class to handle the exponentiation (^) operator.
Page 220
Operators
Sample Code
// Raises the sum of the vector to the sum of the power vector
Function Operator_Power(rightSide As Vector) As Integer
Dim a, b As Integer
a = Self.x + Self.y
b = rightSide.x + rightSide.y
Return a ^ b
End Function
Operator_Redim
Allows the class to support the Redim statement, allowing you to use Redim on objects that are not arrays.
Sample Code
Class OneBasedArray
Sub Constructor(bounds As Integer = 0)
Redim mArray(bounds - 1)
End Sub
Function Count() As Integer
Return mArray.UBound + 1
End Function
Sub Operator_Redim(newSize As Integer)
Redim mArray(newSize - 1)
End Sub
Function Operator_Subscript(index As Integer) As Auto
Return mArray(index - 1)
End Function
Sub Operator_Subscript(index As Integer, Assigns a As Auto)
mArray(index - 1) = a
End Sub
Private mArray() As Auto
End Class
Operator_Subscript
Allows the array subscript operator to be used by a class when it is not an array. Refer to Operator_Redim for
sample code.
Page 221
Operators
Operator_Subtract
Operator_SubtractRight
Allows the class to handle the subtraction (-) operator.
Sample Code
Operator_XOr
Operator_XOrRight
Allows the class to handle the Xor operator.
Sample Code
Page 222
Language
Pragma Directives
Pragma directives are used to alter standard behavior of the compiler.
Directive
BackgroundTasks
Syntax
Description
#PragmaBackgroundTasks True |
False
#PragmaBackgroundTasks On |
Off
BoundsChecking
BreakOnExceptions
#Pragma BreakOnExceptions
True | False
#Pragma BreakOnExceptions On
| Off
DisableBackgroundTasks
#Pragma
DisableBackgroundTasks
DisableBoundsChecking
#Pragma DisableBoundsChecking
Error
Page 223
Language
Directive
NilObjectChecking
Syntax
#Pragma NilObjectChecking
True | False
#Pragma NilObjectChecking On
| Off
Description
Controls whether objects are checked for Nil
before accessing their members.
This can be toggled within a method.
Setting NilObjectChecking False/Off will result in a
slight speed improvement, but it is not
recommended because unhandled exceptions can
cause your app to crash.
#Pragma NilObjectChecking Off
StackOverflowChecking
#Pragma StackOverflowChecking
True | False
#Pragma StackOverflowChecking
On | Off
Unused
Warning
X86CallingConvention
#Pragma X86CallingConvention
StdCall | CDecl
Sample Code
Normally you want Project->Break On Exceptions to be enabled. The BreakOnExceptions Pragma can be a handy
way to prevent the debugger from appearing in code where you are expecting (and handle) an exception:
#Pragma BreakOnExceptions Off
Try
TextOutputStream.Create(myFile)
Catch e As IOException
// Could not create file, probably permissions
ErrorMessage = "Unable to create file."
End Try
#Pragma BreakOnExceptions On
Page 224
Language
Reserved Words
These words are reserved by the Xojo Programming Language and may not be used as identifiers for your own
variables, objects, event definitions, methods, etc.
In addition, do not use the underscore ("_") as the first character of an identifier.
#Bad, #Else, #ElseIf, #If, #Pragma, #Tag
AddHandler, AddressOf, Aggregates, And, Array, As, Assigns, Attributes
Break, ByRef, ByVal
Call, Case, Catch, Class, Const, Continue, CType
Declare, Delegate, Dim, Do, DownTo
Each, Else, ElseIf, End, Enum, Event, Exception, Exit, Extends
False, Finally, For, Function
Global, GoTo
Handles
If, Implements, In, Inherits, Inline68K, Interface, Is, IsA
Lib, Loop, Me, Mod, Module
Namespace, New, Next, Nil, Not
Object, Of, Optional, Or
ParamArray, Private, Property, Protected, Public
Raise, RaiseEvent, Rect, ReDim, Rem, RemoveHandler, Return
Select, Self, Shared, Soft, Static, Step, Structure, Sub, Super
Then, To, True, Try
Until, Using
WeakAddressOf, Wend, While, With
Xor
Page 225
Reference Guide
Framework
The section describes the Xojo Framework, which consists of classes in both the global namespace and in the Xojo
namespace.
Page 226
Framework
Exceptions
In Xojo, exceptions are used for error handling. If your code causes or raises an exception and you do not handle it,
iOSApplication.UnhandledException will be called with information about the exception and your app will then crash.
Use Try...Catch blocks around code that could raise exceptions.
Page 227
Exceptions
FunctionNotFoundException (Class)
Raised when a soft declared function is invoked but the function could not be loaded.
Class Summary
Name
FunctionNotFoundException
Type
Class
Inherits
RuntimeException
Implements
n/a
Properties
Methods
CallStack, Stack
Targets
All
Platforms
All
Related
Declare
Notes
This exception is raised when a Soft Declare statement fails to find or load the specified function or library.
For example, this code displays a message if the function cannot be loaded:
Try
Soft Declare Function getpid Lib "libc" () As Integer
Catch e As FunctionNotFoundException
ErrorLabel.Text = "The getpid function was not found in the libc library."
End Try
Page 228
Exceptions
NilObjectException (Class)
Raised when invoking a method on a Nil base expression or passing a Nil object to a function that expects a non-Nil
object.
Class Summary
Name
NilObjectException
Type
Class
Inherits
RuntimeException
Properties
Methods
CallStack, Stack
Targets
All
Platforms
All
Related
Notes
A NilObjectException occurs when you try to access an object that does not have an instance. The most common
occurrence of this error when an object is not instantiated using the New operator before accessing its members.
For example, this code causes a NilObjectException:
Dim d As Date
If d.Year = 2014 Then // NilObjectException on this line because d was not instantiated
// Do something
End If
Instead, always remember to use the New operator:
Dim d As New Date
If d.Year = 2014 Then
// Do something
End If
Page 229
Exceptions
ObjCException (Class)
Raised when an Objective-C declare throws an exception.
Class Summary
Name
ObjCException
Type
Class
Inherits
RuntimeException
Implements
n/a
Properties
Methods
CallStack, Stack
Targets
All
Platforms
All
Related
Properties
Handle As Ptr
The handle for the exception.
Page 230
Exceptions
OutOfBoundsException (Class)
Raised when accessing an element that is out of bounds of the container.
Class Summary
Name
OutOfBoundsException
Type
Class
Inherits
RuntimeException
Implements
n/a
Properties
Methods
CallStack, Stack
Targets
All
Platforms
All
Related
Notes
Examples for when this occur include:
attempting to access an array element larger (or smaller) than the size of the array
Attempting to access a row that it outside the available rows for a container
Page 231
Exceptions
OutOfMemoryException (Class)
Raised when trying to allocate more memory than is available.
Class Summary
Name
OutOfMemoryException
Type
Class
Inherits
RuntimeException
Implements
n/a
Properties
Methods
CallStack, Stack
Targets
All
Platforms
All
Related
MemoryBlock, MutableMemoryBlock
Notes
Typically used with MemoryBlock or MutableMemoryBlock when trying to allocate large blocks of memory that
exceeds what is available.
Low-level memory situations are inherently problematic if you are frequently requesting small blocks of memory.
Because of this, there is no guarantee that an OutOfMemoryException can even be raised. If the system memory is
critically low, the process itself may crash as it attempts to reserve memory in order to display an exception
message. In this situation, you might consider reserving a single large block of memory up front and using that
within your application rather than repeatedly requesting smaller blocks.
Page 232
Exceptions
RuntimeException (Class)
The base class of all exceptions.
Class Summary
Name
RuntimeException
Type
Class
Inherits
n/a
Implements
n/a
Properties
Methods
CallStack, Stack
Targets
All
Platforms
All
Related
StackFrame
Notes
Exceptions are raised when an error condition occurs. Unhandled exceptions cause your app to terminate. You can
handle exceptions using a Try...Catch code block. Generally, you always want to check for specific exceptions that
could be caused by your code.
For example, a Dictionary raises an exception if you try to remove a key that does not exist. You can catch that
exception like this:
Try
d1.RemoveByKey("Test")
Catch e As KeyNotFoundException
// You may want to report the error to the user
ErrorLabel.Text = "The key 'Test' does not exist."
End Try
Now in the case of Dictionary, it has a method that can check if a key exists. It is more efficient to use this method
than to catch the exception:
If d1.HasKey("Test") Then
d1.RemoveByKey("Test")
Else
ErrorLabel.Text = "The key 'Test' does not exist."
End If
Page 233
Exceptions
Properties
ErrorNumber As Integer
The error number for the exception, if appropriate.
Message As String
A description of why the exception occurred.
Not available on iOS. Use Reason instead.
Methods
CallStack As StackFrame (read-only)
The stack when the exception was first raised.
Stack As As String()
The stack when the exception was first raised.
Not available on iOS. Use CallStack instead.
Page 234
Exceptions
StackOverflowException (Class)
Raised when the program is close to running out of stack space and crashing.
Class Summary
Name
StackOverflowException
Type
Class
Inherits
RuntimeException
Implements
n/a
Properties
Methods
CallStack, Stack
Targets
All
Platforms
All
Related
Notes
This exception can occur when the calling chain gets too long. This can easily happen when your code makes a
recursive call without providing a way to terminate the recursion (or the condition to terminate the recursion takes
too many calls to occur).
This can also occur in situations where two methods or events call each other repeatedly because of UI actions
(such as a Canvas Paint event handler calling a method that causes the Canvas to refresh).
Page 235
Exceptions
TypeMismatchException (Class)
Raised when assigning to a variable from an incompatible type.
Class Summary
Name
TypeMismatchException
Type
Class
Inherits
RuntimeException
Implements
n/a
Properties
Methods
CallStack, Stack
Targets
All
Platforms
All
Related
Notes
This exception occurs when you try to assign a value of an incorrect type to an object. The error occurs only if the
value cannot be determined at run-time, for example when using Auto or Variant. Normally, errors with incompatible
type are caught at compile-time.
Page 236
Framework
IOS
These are the controls, classes and interfaces used by iOS apps.
Framework Summary
Controls
Classes
Interfaces
Layout
Targets
Mobile
Platforms
iOS
Related
Xojo namespace
Retina Images
On iOS, it is possible that an app may require 1x, 2x or 3x versions of images. There are two ways to incorporate
these different size images into your projects. Regardless of the technique, you do have to use a standard naming
convention for the images.
Naming Conventions
1. First, create your three images using PNG format.
2. Name them without any special characters, but append "@2x", "@3x" suffixes for the large images. For
example, you could have: MyImage.png, MyImage@2x.png and MyImage@3x.png.
With the images created, you now have two ways to incorporate them into your project. The first way is to simply
drag all the images into the project. Xojo will remove the "@" character, so you'll see: MyImage, MyImage2x,
MyImage3x. These will be iOSImage classes.
The second way is to drag just the 1x image into the project, so you'll see: MyImage. Use a Copy Files Build Step to
copy the remaining images to the Resources folder in the app bundle.
In your code, you always refer to the images using the 1x name, so you would always use MyImage, for example. At
run-time, the appropriate image for the device (1x, 2x or 3x) will be automatically used.
Page 237
Framework
Auto-Layout
For any single control there are a number of attributes which can be used to refer to its position and size.
In left to right writing systems Left is the same as leading and Right is the same as trailing. In right to left writing
systems, like Arabic, right is Leading and left is trailing as the normal flow of layout is from right to left or from the
leading edge to the trailing edge.
There are other positional and sizing attributes that are very useful as well.
Suppose you have an iOS View (seen below in grey) and a button placed on that view where the left guide line
appeared. That gap between the View and the button is the LeadingMargin. There is also a trailing margin, top
margin and bottom margin.
Suppose you have buttons positioned close to each other and you placed the right most after the left most. When
you did this you snapped it to the guideline that appeared offset from the left most button. Something like below.
That gap between the two buttons is a Standard gap and is appropriately sized for the version of iOS that you are
using.
Page 238
Framework
Page 239
iOS Framework
IOSApplication
The base class for iOS apps.
Class Summary
Name
iOSApplication
Type
Class
Inherits
n/a
Implements
n/a
Events
LowMemoryWarning, Open,
UnhandledException
Properties
DefaultiPhoneScreen, DefaultiPadScreen
Targets
Mobile
Platforms
iOS
Related
iOSScreen
Events
LowMemoryWarning
Called when iOS reports a low-memory situation. Applications should attempt to free up objects and other resources
when this event is raised.
Open
Called when the iOS app is first launched.
Page 240
iOS Framework
Properties
DefaultiPhoneScreen (design property)
Set to the default screen to use when the app is launched on an iPhone-sized device. If you do not specify a
DefaultiPhoneScreen, then the app will not run on iPhone-sized devices.
Notes
One or both of DefaultiPhoneScreen and DefaultiPadScreen must be specified.
By specifying separate screens for DefaultiPhoneScreen and DefaultiPadScreen, you can have completely different
layouts for each type of device.
Page 241
iOS Framework
iOSBitmap
A bitmap image that can be modified using the Graphics property.
Class Summary
Name
iOSBitmap
Type
Class
Inherits
n/a
Implements
n/a
Properties
Targets
Mobile
Platforms
iOS
Related
iOSGraphics
Constructors
Constructor(width As Integer, height As Integer, scale As Double, opaque As Boolean = False)
Creates a bitmap image using the specified width, height, scale and opaqueness.
Parameters
width
height
scale
opaque
Notes
Setting opaque to True disables the alpha channel. If you know that you wil be filling every point in the bitmap, set
opaque to True to improve performance.
The scale indicates how the image appears on the device. For example, bitmaps drawn with a scale of 1.0 will
appear at half the size when drawn on a device with a 2x screen.
Sample Code
Page 242
iOS Framework
Properties
Graphics As iOSGraphics (read-only)
The iOSGraphics object for the bitmap that is used for drawing.
Sample Code
Page 243
iOS Framework
iOSBlock (Class)
Used to help call declares taking Obj-C blocks. An iOSBlock is created from a Xojo delegate and in turn creates an
Objective-C block that will call into the delegate. This Objective-C block is retrieved from the Handle property and
passed into declares.
Control Summary
Name
iOSBlock
Type
Class
Inherits
n/a
Implements
n/a
Properties
Handle
Targets
Mobile
Platforms
iOS
Related
Declare
Notes
iOSBlock is only suitable for blocks that execute on non-background queues/threads.
Constructors
Constructor(theDelegate As Object)
Used to supply the delegate to create for the block.
Properties
Handle As Ptr (read-only)
Gets the Objective-C block.
Sample Code
This example iterates over all of the subviews of a view using a block:
This code goes in a button's Action event:
Declare Function view Lib "UIKit" Selector "view" ( obj as Ptr ) As Integer
Page 244
iOS Framework
Page 245
iOS Framework
iOSButton
This is the standard Button control for iOS.
Control Summary
Name
iOSButton
Type
Control
Inherits
iOSControl
Implements
n/a
Events
Properties
Methods
Handle, Invalidate
Targets
Mobile
Platforms
iOS
Related
UIKit
UIButton
Events
Action
The Action event handler is called when the button is pressed, tapped, clicked, etc.
Sample Code
Change Label Text when a Button is pressed:
Label1.Text = "You pressed the button."
Properties
Caption As Text
Gets or sets the caption for the Button.
Page 246
iOS Framework
Sample Code
Me.Caption = "Save"
Enabled As Boolean
Indicates whether the control is enabled or disabled.
Sample Code
Button1.Enabled = False
TextColor As Color
The color to display the text.
Sample Code
Change the text color to red:
Button1.TextColor = Color.Red
TextFont As iOSFont
The font for displaying the text.
Sample Code
Button1.TextFont = iOSFont.ItalicSystemFont
Label1.TextFont = iOSFont.SystemFont(32)
Page 247
iOS Framework
iOSCanvas
Used to draw graphics.
Control Summary
Name
iOSCanvas
Type
Control
Inherits
iOSControl
Implements
n/a
Events
Properties
Methods
Handle, Invalidate
Targets
Mobile
Platforms
iOS
Related
iOSEventInfo, iOSGraphics
Example Projects
Examples/iOS/Controls/SwipeExample
Examples/iOS/Controls/TouchCanvas
Events
Paint(g As iOSGraphics)
Called when the Canvas needs to update its graphical display.
Parameters
g
Sample Code
To draw a blue rectangle in the Canvas:
g.FillColor = Color.Blue
g.FillRect(0, 0, g.Width, g.Height)
iOS Framework
Parameters
pos
eventInfo
Sample Code
This code saves all touch points to an array, which is used to display circles in the Paint event:
// mTouches is a property
// mTouches() As Point
If eventInfo.PointerCount > 0 Then
// Save multi-touch points
For i As Integer = 0 To eventInfo.PointerCount-1
mTouches.Append(eventInfo.PointerPosition(i))
Next
Else
mTouches.Append(pos)
End If
Me.Invalidate
This code goes in the Paint event handler:
For Each p As Point In mTouches
g.FillColor = Color.Blue
g.FillOval(p.X, p.Y, 10, 10)
Next
eventInfo
Sample Code
Saves the drag positions to draw as circles:
// mTouches is a property
// mTouches() As Point
Page 249
iOS Framework
mTouches.Append(pos)
Me.Invalidate
eventInfo
Sample Code
This code saves all touch points in an array where circles are displayed:
// mTouches is a property
// mTouches() As Point
If eventInfo.PointerCount > 0 Then
// Save multi-touch points
For i As Integer = 0 To eventInfo.PointerCount-1
mTouches.Append(eventInfo.PointerPosition(i))
Next
Else
mTouches.Append(pos)
End If
Me.Invalidate
Page 250
iOS Framework
iOSControl
Control is the base class for most Xojo UI controls. You cannot instantiate Control directly.
Class Summary
Name
iOSControl
Type
Class
Inherits
n/a
Implements
n/a
Events
Close, Open
Properties
Methods
Targets
Mobile
Platforms
iOS
Related
Events
Close
Called when the control is closed by calling its Close method.
Open
Called when the control is first displayed. This is where you typically put initialization code.
Sample Code
Properties
AccessibilityHint As Text
The accessibility hint is a longer description that is read aloud when VoiceOver is enabled.
Page 251
iOS Framework
Sample Code
Me.AccessibilityHint = "Click to calculate the value and display the next view."
AccessibilityLabel As Text
The accessibility label of of a control is a short name that is read aloud when VoiceOver is enabled.
Sample Code
Visible As Boolean
Indicates whether the control is visible.
Sample Code
Make a button invisible:
Button1.Visible = False</code>
Page 252
iOS Framework
Methods
AddControl(child As iOSControl)
Adds a control to the control.
ControlCount As Integer
The number of controls in the control.
Handle As Ptr
The handle is used to get a reference to the control for interfacing directly with the iOS API.
Invalidate
Marks the control so that it will be redrawn during the next event loop.
Sample Code
Call Invalidate to force a Canvas to redraw itself:
Canvas1.Invalidate
RemoveControl(child As iOSControl)
Removes the control from the control.
SetTintColor(value As Color)
Changes a control's tint color. This varies by control. For example, with an iOSTextField this changes the cursor
color.
Page 253
iOS Framework
iOSEventInfo
Contains information about a the UI event.
Class Summary
Name
iOSEventInfo
Type
Class
Inherits
n/a
Implements
n/a
Properties
Methods
Handle, PointerPosition
Targets
Mobile
Platforms
iOS
Related
iOSCanvas
Properties
Handled As Boolean
TBD
Page 254
iOS Framework
Methods
Handle As Ptr
Used for interfacing directly with the native OS API.
Returns
The specified point.
Page 255
iOS Framework
iOSFont
Provides access to fonts on iOS.
Class Summary
Name
iOSFont
Type
Class
Inherits
n/a
Implements
n/a
Properties
Shared Methods
Targets
Mobile
Platforms
iOS
Related
Example Projects
Examples/iOS/Controls/FontExample
Notes
You can find a good list of fonts available on iOS devices at iOSFonts.com.
Constructors
Constructor(postscriptName As Text, pointSize As Double)
Creates an iOSFont from the postscriptName.
Notes
Apple has a list of Fonts Installed with iOS7.
iOS adds a few additional fonts:
KhmerSangamMN
DamascusLight
LaoSangamMN
AppleSDGothicNeo-UltraLight
KohinoorDevanagari-Light
KohinoorDevanagari-Medium
KohinoorDevanagari-Book
Page 256
iOS Framework
Sample Code
Sets a button text to use Courier:
Dim courier As New iOSFont("Courier", 18)
Button1.TextFont = courier
Properties
Ascent As Double (read-only)
The ascent of the font. The ascent of a font is the distance from the tops of the tallest glyphs to the baseline.
Page 257
iOS Framework
Shared Methods
BoldSystemFont(size As Double = 0) As iOSFont
Gets the bold system font.
Parameters
size
The point size of the font, which defaults to size 0 (the standard system font size).
Returns
An iOSFont that is typically assigned to a TextFont property.
Sample Code
Label1.TextFont = iOSFont.BoldSystemFont
The point size of the font, which defaults to size 0 (the standard system font size).
Returns
An iOSFont that is typically assigned to a TextFont property.
Sample Code
Sets a Label to use a large system italic font:
Label1.TextFont = iOSFont.ItalicSystemFont(48)
SmallSystemFontSize As Double
Gets the small system font size. Use this to provide the size parameter to BoldSystemFont, ItalicSystemFont and
SystemFont to get those fonts in the small size.
Returns
The small system font size as a Double.
Page 258
iOS Framework
Sample Code
Label1.TextFont = iOSFont.SystemFont(iOSFont.SmallSystemFontSize)
The point size of the font, which defaults to size 0 (the standard system font size).
Returns
An iOSFont that is typically assigned to a TextFont property.
Sample Code
Label1.TextFont = iOSFont.SystemFont(48)
SystemFontSize As Double
Gets the system font size.
Returns
The system font size as a Double.
Sample Code
Label1.TextFont = iOSFont.ItalicSystemFont(iOSFont.SystemFontSize)
Page 259
iOS Framework
iOSGraphics (Class)
Used to draw text, lines, rectangle and images.
Class Summary
Name
iOSGraphics
Type
Class
Inherits
n/a
Implements
n/a
Properties
Alpha, AntiAlias, FillColor, Handle, Height, LineColor, LineWidth, TextFont, TextUnderline, Width
Methods
Targets
Mobile
Platforms
iOS
Related
Notes
You cannot instantiate iOSGraphics. You can get a Graphics instance from either an iOSCanvas or an iOSBItmap.
Changing the graphics state only affects subsequent drawing commands.
Properties
Alpha As Double
The Alpha value, which ranges from 0.0 (transparent) to 1.0 (opaque).
Sample Code
g.Alpha = 0.5
AntiAlias As Boolean
Specifies whether anti-aliasing is used. The default is True.
Sample Code
Page 260
iOS Framework
g.AntiAlias = False
FillColor As Color
The color used when drawing filled shapes and text.
Sample Code
g.FillColor = Color.Blue
g.LineColor = Color.Blue
g.DrawLine(0, 0, g.Width, g.Height)
LineColor As Color
The color to use when drawing lines and shapes.
Sample Code
g.LineColor = Color.Blue
g.DrawLine(0, 0, g.Width, g.Height)
LineWidth As Double
The width (in points) to use when drawing lines and shapes.
Sample Code
g.LineWidth = 10
g.DrawLine(0, 20, 50,20)
Page 261
iOS Framework
TextFont As iOSFont
The font to use when drawing text.
Sample Code
TextUnderline As Boolean
Indicates if drawn text should be underlined.
Sample Code
g.LineColor = Color.Blue
g.DrawLine(0, 0, g.Width, g.Height)
Methods
ClipToPath(path As iOSPath)
Clips the drawing to the specified path.
Parameters
path
Sample Code
// Clip to an iOSPath
// Path is a triangle
Dim p As New iOSPath
p.MoveToPoint(0, 0) // Start location
Page 262
iOS Framework
p.LineToPoint(20, 44)
p.LineToPoint(40, 0)
p.LineToPoint(0, 0)
g.ClipToPath(p)
g.FillOval(0, 0, 50, 50)
width
height
Sample Code
iOS Framework
g.LineColor = Color.Blue
g.DrawLine(0, 0, g.Width, g.Height)
DrawPath(path As iOSPath)
Draws the specified path.
Sample Code
// Draw a triangle
Dim p As New iOSPath
p.MoveToPoint(0, 0) // Start location
p.LineToPoint(20, 44)
p.LineToPoint(40, 0)
p.LineToPoint(0, 0)
g.LineColor = Color.Blue
g.DrawPath(p)
Page 264
iOS Framework
g.LineColor = Color.Blue
g.DrawRect(10, 10, 20, 20)
g.LineColor = Color.Blue
g.DrawRoundRect(10, 10, 50, 50, 5, 5)
g.FillColor = Color.Blue
Dim t As Text
t = "How much wood would a woodchuck chuck if a woodchuck could chuck would?"
g.DrawTextBlock(t, 0, 10, g.Width, g.Height, iOSTextAlignment.Left, False)
g.FillColor = Color.Blue
Dim t As Text
t = "Hello, World!"
g.DrawTextLine(t, 0, 10, -1, iOSTextAlignment.Center, False)
Page 265
iOS Framework
Sample Code
g.FillColor = Color.Blue
g.FillOval(10, 10, 20, 20)
FillPath(path As iOSPath)
Draws a path, filling it with the FillColor.
Sample Code
// Draw a triangle
Dim p As New iOSPath
p.MoveToPoint(0, 0) // Start location
p.LineToPoint(20, 44)
p.LineToPoint(40, 0)
p.LineToPoint(0, 0)
g.FillColor = Color.Blue
g.FillPath(p)
g.FillColor = Color.Blue
g.FillRect(10, 10, 20, 20)
g.FillColor = Color.Blue
g.FillRoundRect(10, 10, 50, 50, 5, 5)
RestoreState
Restores graphics context previously saved with SaveState.
Page 266
iOS Framework
Sample Code
g.FillColor = Color.Blue
g.FillRect(10, 10, 20, 20)
g.SaveState
g.FillColor = Color.Red
g.FillRect(50, 50, 20, 20)
// Restore to state where FillColor is Blue
g.RestoreState
g.FillRect(10, 50, 20, 20)
Rotate(angle As Double)
Rotates the drawing context by the specified angle (in radians) around the origin point (usually 0,0). This only
affects subsequent drawing. Any drawing done before the Rotate method call is not rotated.
Notes
Use Translate to move the origin.
Sample Code
Page 267
iOS Framework
SaveState
Saves graphics state of the graphics context so that it can be restored later.
Notes
These values are saved with SaveState and are restored when you call RestoreState.
Translation
Clip region
LineWidth
AntiAlias
FillColor
LineColor
Alpha value
TextFont
TextUnderline
Rotation
Sample Code
g.FillColor = Color.Blue
g.FillRect(10, 10, 20, 20)
g.SaveState
g.FillColor = Color.Red
g.FillRect(50, 50, 20, 20)
// Restore to state where FillColor is Blue
g.RestoreState
g.FillRect(10, 50, 20, 20)
g.Scale(2.0, 4.0)
g.FillColor = Color.Blue
g.FillRect(10, 10, 10, 10) // The squares scales to a rectangle
TextBlockSize (value As Text, maxWidth As Double = -1, maxHeight As Double = -1, alignment As
Page 268
iOS Framework
Page 269
iOS Framework
iOSHTMLViewer (Control)
Displays HTML in a scrollable area.
Control Summary
Name
iOSHTMLViewer
Type
Control
Inherits
iOSControl
Implements
n/a
Events
Properties
Methods
LoadURL
Targets
Mobile
Platforms
iOS
Related
Example Projects
Examples/iOS/Controls/HTMLViewerExample
Methods
LoadURL(url As Text)
Displays the specified URL. Be sure to include the appropriate prefix, such as "http://".
Parameters
url
Sample Code
Display wikipedia:
HTMLViewer1.LoadURL("http://www.wikipedia.org")
Page 270
iOS Framework
iOSImage (Class)
A pre-existing image that was either added to the project or is loaded from another source.
Class Summary
Name
iOSImage
Type
Class
Inherits
n/a
Implements
n/a
Properties
Methods
ToData, WriteToFile
Shared Methods
Targets
Mobile
Platforms
iOS
Related
iOSBitmap
Notes
An iOSImage is immutable, which means that it cannot be changed. Because of this it can be cached by iOS for
speed. If you need to change an image, you should instead create it as an iOSBitmap.
Properties
Handle As Ptr (read-only)
The UIImage handle to use when calling OS APIs through Declares.
iOS Framework
Methods
ToData(type As Text) As MemoryBlock
Converts the image to data that can be used for storing in databases, for example. Use type to specify the uniform
type identifier for the data. For example, use "public.png" for PNG data.
Notes
Common types include "public.jpeg", "public.tiff" and "public.png".
Apple provides a list of uniform type identifiers.
Notes
Common types include "public.jpeg", "public.tiff" and "public.png".
Apple provides a list of uniform type identifiers.
Shared Methods
FromData(data As MemoryBlock) As iOSImage
Creates an image from data in a MemoryBlock.
Sample Code
Page 272
iOS Framework
Page 273
iOSImage
As of iOS 8.1, here are the supported formats that can be used with iOSImage.ToData and WriteToFile.
Input Formats
Portable Network Graphics image
public.png
JPEG image
public.jpeg
com.compuserve.gif
com.canon.tif-raw-image
com.adobe.raw-image
Input formats:
Portable Network Graphics image: public.png
JPEG image: public.jpeg
Graphics Interchange Format (GIF): com.compuserve.gif
Canon TIF raw image: com.canon.tif-raw-image
Adobe raw image: com.adobe.raw-image
Canon CR2 raw image: com.canon.cr2-raw-image
Leaf raw image: com.leafamerica.raw-image
Hasselblad FFF raw image: com.hasselblad.fff-raw-image
Hasselblad 3FR raw image: com.hasselblad.3fr-raw-image
Nikon raw image: com.nikon.raw-image
Nikon NRW raw image: com.nikon.nrw-raw-image
Pentax raw image: com.pentax.raw-image
Samsung raw image: com.samsung.raw-image
Sony raw image: com.sony.raw-image
Sony SR2 raw image: com.sony.sr2-raw-image
Sony ARW raw image: com.sony.arw-raw-image
Epson raw image: com.epson.raw-image
Kodak raw image: com.kodak.raw-image
TIFF image: public.tiff
Canon CRW raw image: com.canon.crw-raw-image
Fuji raw image: com.fuji.raw-image
Panasonic raw image: com.panasonic.raw-image
Panasonic raw 2 image: com.panasonic.rw2-raw-image
Leica raw image: com.leica.raw-image
Leica raw image: com.leica.rwl-raw-image
Minolta raw image: com.konicaminolta.raw-image
Olympus SR raw image: com.olympus.sr-raw-image
Page 274
iOSImage
Output formats:
Portable Network Graphics image: public.png
JPEG image: public.jpeg
Graphics Interchange Format (GIF): com.compuserve.gif
TIFF image: public.tiff
Windows icon image: com.microsoft.ico
Windows bitmap image: com.microsoft.bmp
Portable Document Format (PDF): com.adobe.pdf
TGA image: com.truevision.tga-image
JPEG 2000 image: public.jpeg-2000
(Netpbm): public.pbm
Page 275
iOS Framework
iOSImageViewer (Control)
Displays an image.
Control Summary
Name
IOSImageView
Type
Control
Inherits
iOSControl
Implements
n/a
Enumerations
ContentMode
Events
Close, Open
Properties
Methods
Handle, Invalidate
Targets
Mobile
Platforms
iOS
Related
iOSImage
Enumerations
ContentMode
The way the image gets displayed.
ScaleToFill
The image's aspect ratio is ignored and the image is stretched to fit within the bounds of the
frame.
ScaleAspectFit
ScaleAspectFill
Scales the image until it fills the ImageView entirely, maintaining aspect.
Center
Top
The image is positioned with its top at the top of the frame.
Bottom
The image is positiioned with its bottom at the bottom of the frame.
Left
The image is positioned with its left at the left of the frame.
Right
The image is positioned with its right at the right of the frame.
Page 276
iOS Framework
Topleft
The image is positioned with its top left at the top left of the frame.
TopRight
The image is positioned with its top right at the top right of the frame.
BottomLeft
The image is positioned with its bottom left at the bottom left of the frame.
BottomRight
The image is positioned with its bottom right at the bottom right of the frame.
Properties
ContentMode
Specifies the way the picture gets displayed using a ContentMode enumeration.
Image As iOSImage
The image to display.
Page 277
iOS Framework
iOSLabel (Control)
This is the standard Label control for iOS.
Control Summary
Name
iOSLabel
Type
Control
Super
iOSControl
Interfaces
n/a
Events
Properties
Methods
Handle, Invalidate
Targets
Mobile
Platforms
iOS
Related
iOSFont
UIKit
UILabel
Properties
Enabled As Boolean
Indicates if the label is enabled or disabled.
Sample Code
Disable a label:
Label1.Enabled = False
Text As Text
The text to display in the Label.
Sample Code
Set the label text:
Page 278
iOS Framework
TextAlignment As iOSTextAlignment
Specifies the alignment for the text using the iOSTextAlignment enumeration. The default value is
iOSTextAlignment.Left.
Sample Code
Label1.TextAlignment = iOSTextAlignment.Center
TextColor As Color
The color of the text.
Sample Code
Label1.TextColor = Color.Blue
TextFont As iOSFont
The font used to display the text.
Sample Code
Label1.TextFont = iOSFont.BoldSystemFont(40)
Page 279
iOS Framework
iOSLayoutConstraint (Class)
Used to add new auto-layout constraints or modify existing ones.
Class Summary
Name
iOSLayoutConstraint
Type
Class
Inherits
n/a
Implements
n/a
Enumerations
AttributeTypes, RelationTypes
Properties
Shared Properties
StandardGap
Targets
Mobile
Platforms
iOS
Related
iOSView.Constraint
Constructors
Constructor(firstItem As Object, firstAttribute As AttributeTypes, relation As RelationTypes,
secondItem As Object, secondAttribute As AttributeTypes, multiplier As Double, addend As Double)
Creates a new auto-layout rule for the firstItem control with an addend offset value.
Sample Code
Page 280
iOS Framework
Sample Code
Enumerations
AttributeTypes
The auto-layout attributes.
None
No constraint.
Left
Right
Top
Bottom
Leading
Trailing
Width
Height
CenterX
Horizontal center
CenterY
Vertical center
Baseline
LeftMargin
*iOS 8 only
RightMargin
*iOS 8 only
TopMargin
*iOS 8 only
BottomMargin
*iOS 8 only
LeadingMargin
*iOS 8 only
TrailingMargin
*iOS 8 only
Page 281
iOS Framework
RelationTypes
The auto-layout relation.
LessThanOrEqual
The value must be less than or equal to the value of the related control.
Equal
GreaterThanOrEqual
The value must be greater than or equal to the value of the related control.
Properties
Active As Boolean
Indicates if this auto-layout rule is active.
Sample Code
Offset As Double
The offset that can be applied to the rule.
Sample Code
Page 282
iOS Framework
Notes
Higher priority constraints are met before lower priority constraints.
Priority
Value
Priority Required
1000 or greater
Optional Priority
High Priority
750
Low Priority
250
Auto
50?
You cannot change a priority from a required value (1000 or greater) to an optional value (less than 1000).
Shared Properties
StandardGap
Used to supply a standard gap value when creating a new auto-layout rule. This item can only be used for the gap
parameter in the constructor. It has no defined type.
Page 283
iOS Framework
iOSLine (Control)
This is the standard Line control for iOS.
Control Summary
Name
iOSLine
Type
Control
Super
IOSControl
Interfaces
n/a
Events
Close, Open
Properties
Methods
Handle
Targets
Mobile
Platforms
iOS
Related
Properties
Direction As Integer
The direction of the line.
0
Horizontal
Vertical
LineColor As Color
The color of the line.
LineWidth As Double
The width of the line.
Page 284
iOS Framework
iOSMessageBox
Used to asynchronously display alerts.
Class Summary
Name
iOSMessageBox
Type
Class
Super
n/a
Interfaces
n/a
Events
ButtonAction
Properties
Message, Title
Methods
Buttons, Show
Targets
Mobile
Platforms
iOS
Related
Notes
Since iOSMessageBox is asyncrhonous, any code after the Show method is executed after the message box is
displayed. Use the ButtonAction event handler to get the results of a button selection and to run code based on the
selection.
Events
ButtonAction(buttonIndex As Integer)
Called when the button at buttonIndex (0-based) is selected.
Sample Code
Properties
Message As Text
A longer message that appears below the title in the message box.
Page 285
iOS Framework
Title As Text
The title of the message box, which appears at the top.
Methods
Buttons As Text()
Buttons(Assigns value() As Text)
Gets or sets the buttons for the message box.
Sample Code
Displays a message box with multiple buttons. HelloMessage is an iOSMessageBox that was dragged onto the View
from the Library:
HelloMessage.Title = "Hello"
HelloMessage.Message = "Hello, World!"
Dim buttons() As Text
buttons.Append("Yes")
buttons.Append("No")
HelloMessage.Buttons = buttons
HelloMessage.Show
Show
Displays the message box. This is not modal, so your code continues to run. When the user selects a button, the
ButtonAction event handler is called.
Sample Code
Displays a message box. HelloMessage is an iOSMessageBox that was dragged onto the View from the Library:
HelloMessage.Title = "Hello"
HelloMessage.Message = "Hello, World!"
HelloMessage.Show // Not modal, so code does not pause here</code>
Page 286
iOS Framework
iOSOval (Control)
This is the standard Oval control for iOS.
Control Summary
Name
iOSOval
Type
Control
Super
iOSControl
Interfaces
n/a
Events
Close, Open
Properties
Targets
Mobile
Platforms
iOS
Related
iOSLine, iOSRectangle
Properties
BorderColor As Color
The color of the border.
BorderWidth As Double
The width of the border.
FillColor As Color
The fill color.
Page 287
iOS Framework
iOSPath (Class)
A graphics path is a mathematical description of a series of shapes or lines.
Class Summary
Name
iOSPath
Type
Class
Inherits
n/a
Implements
n/a
Properties
Methods
Targets
Mobile
Platforms
iOS
Related
iOSGraphics
UIKit
UIBezierPath
Properties
CurrentPoint As Point (read-only)
The current point.
Methods
AddArc(x As Double, y As Double, radius As Double, startAngle As Double, endAngle As Double,
clockwise As Boolean)
Adds an arc to the path.
Page 288
iOS Framework
Notes
The ending point of the Arc becomes the start point for the next element added to the path. In particular, if you add
two arcs in a row, there will be a line that connects the ending point of the first arc to the starting point of the
second arc. If you do not want this behavior, set the new starting point manually using MoveToPoint.
Parameters
x
radius
startAngle
The angle (in radians) that determines the starting point of the arc, measured from the x-axis.
endAngle
The angle (in radians) that determines the ending point of the arc, measured from the x-axis.
clockwise
A Boolean value that specifies whether or not to draw the arc in the clockwise direction.
Sample Code
cp1y
cp2X
cp2Y
Sample Code
Page 289
iOS Framework
cpY
Sample Code
Page 290
iOS Framework
Parameters
x
width
height
Sample Code
width
height
cornerWidth
cornerHeight
Sample Code
Page 291
iOS Framework
Sample Code
// Draw a triangle
Dim p As New iOSPath
p.MoveToPoint(0, 0) // Start location
p.LineToPoint(20, 44)
p.LineToPoint(40, 0)
p.LineToPoint(0, 0)
g.LineColor = Color.Blue
g.DrawPath(p)
Sample Code
Operators
The comparison operator is supported.
Page 292
iOS Framework
iOSProgressBar (Control)
The ProgressBar is used to display progress using a horizontal line.
Control Summary
Name
iOSProgressBar
Type
Control
Super
iOSControl
Interfaces
n/a
Events
Close, Open
Properties
Methods
Handle, SetMinCurrentMax
Targets
Mobile
Platforms
iOS
Related
iOSProgressWheel
Example Projects
Examples/iOS/Controls/ProgressExample
Properties
CurrentValue As Double
The current position of the progress bar.
MaxValue As Double
The maximum value of the progress bar. When CurrentValue reaches MaxValue, the progress bar appears "full".
MinValue As Double
The minimum value of the progress bar. When CurrentValue is MinValue, the progress bar appears "empty".
Methods
SetMinCurrentMax(minValue As Double, currentValue As Double, maxValue As Double)
Sets all the properties at one time.
Page 293
iOS Framework
Parameters
minValue
currentValue
maxValue
Notes
Using this method is more efficient than setting the properties individually. It also avoids the animation that some
platforms may show when you update the properties separately.
Page 294
iOS Framework
iOSProgressWheel (Control)
The ProgressWheel is an animated spinning wheel used to indicate that a task is in process.
Control Summary
Name
iOSProgressWheel
Type
Control
Super
iOSControl
Interfaces
n/a
Enumerations
Shade
Events
Close, Open
Properties
AccessibilityHint, AccessibilityLabel, Height, Left, Name, Parent, Shade, Top, Visible, Width
Targets
Mobile
Platforms
iOS
Related
iOSProgessBar
Example Projects
Examples/iOS/Controls/ProgressExample
Enumerations
Shade
Shade options for the ProgressWheel.
Light
Dark
Properties
Shade As Shade
The shade of the progress wheel (light or dark). The default is Dark.
Sample Code
Set the shade to dark:
ProgressWheel1.Shade = iOSProgressWheel.Shade.Dark
Page 295
iOS Framework
iOSRectangle (Control)
The standard rectangle control for iOS.
Control Summary
Name
iOSRectangle
Type
Control
Super
iOSControl
Interfaces
n/a
Events
Close, Open
Properties
Targets
Mobile
Platforms
iOS
Related
iOSLine, iOSOval
Properties
BorderColor As Color
The color of the border.
BorderWidth As Double
The width of the border.
CornerHeight As Double
The height of the corner. Used to create rounded corners.
CornerWidth As Double
The width of the corner. Used to create rounded corners.
FillColor As Color
The fill color.
Page 296
iOS Framework
iOSScreen
An iOS screen that controls specific layouts depending on the type of device being used.
Class Summary
Name
iOSScreen
Type
Class
Inherits
n/a
Implements
n/a
Properties
Content
Methods
Handle
Targets
Mobile
Platforms
iOS
Related
Notes
You cannot directly add controls to an iOSScreen.
An iOSScreen allows you to specify how your app looks depending on the type of device being used. For example,
on an iPhone you can have your app display a single View that contains a Table with a list of items. To do this, you
select the View for the Content property in the Inspector for the DefaultiPhoneScreen. The iPhoneScreen is set in the
App Inspector as the default screen to use for an iPhone.
On an iPad, you may instead want to have a split screen with a list of items on the left and detail information on the
right. You can do this by setting the Content property for DefaultiPadScreen to be Split and then setting the views
for the Main and Detail sections.
Properties
Content As iOSScreenContent
The content to display on the screen. This can be a single View, a SplitView (consisting of a main and detail view) or
a TabBar (consisting of multiple Views).
Methods
Handle As Ptr
The iOS pointer to the screen handle.
Page 297
iOS Framework
iOSScreenContent (Interface)
Identifies iOS controls that can be used as a screen.
Interface Summary
Name
iOSScreenContent
Type
Interface
Implements
iOSViewController
Events
Properties
Methods
Targets
Mobile
Platforms
iOS
Related
Page 298
iOS Framework
iOSSegmentedControl (Control)
A horizontal button made up of multiple, independent segments.
Control Summary
Name
iOSSegmentedControl
Type
Control
Super
iOSControl
Interfaces
n/a
Events
Properties
AccessibilityHint, AccessibilityLabel, Height, Left, Name, Parent, Top, Value, Visible, Width
Methods
Targets
Mobile
Platforms
iOS
Related
iOSSegmentedControlItem
Example Projects
Examples/iOS/Controls/SegmentedControl
Events
ValueChanged
Called when the selected segment changes.
Properties
Value As Integer
The currently selected segment.
Methods
Add(item As iOSSegmentedControlItem)
Adds a segment to the end.
Sample Code
Add segments:
Page 299
iOS Framework
Me.Add(New iOSSegmentedControlItem("Earth"))
Me.Add(New iOSSegmentedControlItem("Sun"))
Me.Add(New iOSSegmentedControlItem("Moon"))
Count As Integer
The number of segments.
RemoveAll
Removes all segments.
RemoveByIndex(index As Integer)
Removes a specific segment by its index.
RemoveByValue(item As iOSSegmentedControlItem)
Removes a specific segment.
Page 300
iOS Framework
iOSSegmentedControlItem (Control)
An item to display within the SegmentedControl.
Item Summary
Name
iOSSegmentedControlItem
Type
Control
Super
n/a
Interfaces
n/a
Properties
Targets
Mobile
Platforms
iOS
Related
iOSSegmentedControl
Constructors
Constructor(icon As Image)
Creates an item using the specified image.
Properties
Icon As iOSImage
The icon to display.
Notes
Although you can have both an Icon and a Title, iOS only shows one of them, preferring the icon if available.
If you use an icon that is too large (about 28x28 seems to be the maximum), you will only see an empty square.
Only the mask for the icon is used, displayed using the tint color for iOS (currently blue), so be sure to use a PNG
with an alpha channel.
Page 301
iOS Framework
Selected As Boolean
Indicates if the item is selected.
Title As Text
The title text of the item.
Notes
Although you can have both an Icon and a Title, iOS only shows one of them, preferring the icon if available.
Width As Double
The width of the item.
Page 302
iOS Framework
iOSSeparator (Control)
Used to separate sections of a layout.
Control Summary
Name
iOSSeparator
Type
Control
Super
iOControl
Interfaces
n/a
Events
Close, Open
Properties
Targets
Mobile
Platforms
iOS
Related
iOSLine
Page 303
iOS Framework
iOSSound (Class)
Plays sounds.
Control Summary
Name
iOSSound
Type
Class
Super
n/a
Interfaces
n/a
Properties
Methods
Targets
Mobile
Platforms
iOS
Related
Example Projects
Examples/iOS/Sound/GameBuzzer
Examples/iOS/Sound/NatureSounds
Constructors
Constructor(file As FolderItem)
Creates a new sound from a sound file.
Properties
IsPlaying As Boolean (read-only)
Indicates if the sound is currently playing.
Pan As Integer
Specifies the relative volume (balance) between the left and right sound channels.
Notes
The value ranges from -100 to +100, with 0 indicating equal volume in both channels. -100 plays sound in only the
left channel, 100 plays sound only in the right channel.
Page 304
iOS Framework
Methods
Clone As iOSSound
Creates a clone of the current sound that can be used independently of the original.
Play
Plays the sound once.
PlayLooping
Plays the sound, repeating it indefinitely.
Stop
Stops the sound from playing.
Page 305
iOS Framework
iOSSlider (Control)
A control with a draggable slider than can be used to change a value.
Control Summary
Name
iOSSlider
Type
Control
Super
iOSControl
Interfaces
n/a
Events
Properties
Methods
Handle, SetMinCurrentMax
Targets
Mobile
Platforms
iOS
Related
UIKit
UISlider
Events
ValueChanged
Called when CurrentValue is changed.
Properties
CurrentValue As Double
The current value of the slider.
Enabled As Boolean
Enables or disables the slider.
MaxValue As Double
The maximum value of the slider.
Page 306
iOS Framework
MinValue As Double
The minimum value of the slider.
Methods
SetMinCurrentMax(minValue As Double, currentValue As Double, maxValue As Double)
Sets all the properties at one time.
Page 307
iOS Framework
iOSSplitContent (Interface)
Indicates the iOS controls that can be used in a SplitView.
Interface Summary
Name
iOSSplitContent
Type
Interface
Implements
Events
Properties
Methods
Targets
Mobile
Platforms
iOS
Related
Page 308
iOS Framework
iOSSplitView (Control)
A SplitView allows you to present master/detail views on a single iPad screen.
Control Summary
Name
iOSSplitView
Type
Control
Inherits
n/a
Implements
Enumerations
Events
Properties
Detail, Master
Methods
ViewControllerHandle
Shared Methods
Available
Targets
All
Platforms
All
Related
iOSView
Example Projects
Examples/iOS/Controls/SplitView
Properties
Detail As iOSSplitContent
The detail (or right-hand side) view or tab bar to display.
Master As iOSSplitContent
The master (or left-hand side) view or tab bar to display.
Methods
ViewControllerHandle As Ptr
Used when calling OS APIs.
Page 309
iOS Framework
Shared Methods
Available As Boolean
Indicates that a SplitView is available. This typically means that an iPad is being used.
Page 310
iOS Framework
iOSSwitch (Control)
A Switch control is used to indicate an on/off, yes/no or true/false selection.
Control Summary
Name
iOSSwitch
Type
Control
Super
iOSControl
Interfaces
n/a
Events
Properties
AccessibilityHint, AccessibilityLabel, Enabled, Height, Left, Name, Parent, Top, Value, Visible,
Width
Methods
Handle
Targets
Mobile
Platforms
iOS
Related
UIKit
UISwitch
Example Projects
Examples/iOS/Controls/SwitchExample
Events
ValueChanged
Called when the value property is changed either by code or by the user.
Properties
Enabled As Boolean
Enables or disables the Switch.
Value As Boolean
The value of switch. ON = True, OFF = False.
Page 311
iOS Framework
iOSTabBar
An iOS TabBar.
Class Summary
Name
iOSTabBar
Type
Control
Super
n/a
Interfaces
Methods
Targets
Mobile
Platforms
iOS
Related
iOSTabContent, iOSView
Example Projects
Examples/iOS/Controls/TabBarExample/TabBarExample
Examples/iOS/Framework/AdvancedThreadingExample
Examples/iOS/Apps/EddiesElectronics/EEiOS
Notes
You set up a tab bar using the Inspector to change the Content property for a Screen. Refer to Getting Started with
iOS for information on how to do this.
From the Apple User Interface Guidelines, a tab bar:
Is translucent
Always appears at the bottom edge of the screen
Displays no more than five tabs at one time in a horizontally compact environment (if there are more tabs, the
tab bar displays four of them and adds the More tab, which reveals the additional tabs in a list)
Maintains the same height in all orientations
Can display a badge on a tab to communicate app-specific information (a badge is a red oval containing white
text and either a number or exclamation point)
Regardless of the icon's visual style, create a tab bar icon in the following sizes: About 50 x 50 pixels (96 x 64 pixels
Methods
AddTab(content As iOSTabContent)
Adds an iOSView to the tab bar.
Page 312
iOS Framework
Sample Code
Page 313
iOS Framework
iOSTabContent (Interface)
Identifies iOS controls that can be used on a TabBar.
Interface Summary
Name
iOSTabContent
Type
Interface
Implements
Events
Properties
Methods
Targets
Mobile
Platforms
iOS
Related
Notes
You set up a tab bar on the Screens for the iOS devices. Refer to Getting Started with iOS for information on how to
do this.
Page 314
iOS Framework
iOSTable (Control)
An iOS Table.
Control Summary
Name
iOSTable
Type
Control
Super
iOSControl
Interfaces
n/a
Enumerations
Formats
Events
AccessoryAction, Action
Properties
Methods
Targets
Mobile
Platforms
iOS
Related
iOSTableCellData, iOSTableDataSource
UIKit
UITableView
Example Projects
Examples/iOS/Controls/Table/GroupTableExample
Examples/iOS/Controls/Table/SectionTableExample
Examples/iOS/Controls/Table/SimpleTableExample
Examples/iOS/Controls/Table/TableCheckmark
Examples/iOS/Controls/Table/TableDataSource
Examples/iOS/Controls/Table/TableDetail
Examples/iOS/Controls/Table/TableDisclosure
Examples/iOS/Apps/EddiesElectronics/EEiOS
Examples/iOS/Apps/XojoNotes/XojoNotes
Notes
An iOSTable can only show a single column of data.
A table can have data added to it in one of two ways: manually or from a data source. Some methods only work with
data that was added manually, some methods only work with data added using a data source.
A table must have at least one section (0-based). If there is only one section, then the section title does not appear
in the table.
Page 315
iOS Framework
Sample Code
// Simple usage
Table1.AddSection("")
For i As Integer = 0 To 4
Table1.AddRow(0, "Row " + i.ToText)
Next
Enumerations
Formats
Indicates the formatting of the table.
Plain
A plain table consists of just the rows and section headings. This is the default.
Grouped
A grouped table has the section headings displayed outside of the table in visually distinct sections.
Events
AccessoryAction(section As Integer, row As Integer)
Called when the accessory (if specified) for a row is tapped.
row
Properties
DataSource As iOSTableDataSource
The data to display in the table.
Notes
For data sets that are large, a data source allows you to efficiently provide rows without the memory cost of having
an iOSTableCell in memory at all times for every single one of them.
DataSource is a weak reference so you need to make sure your data source instance does not go out of scope. The
easiest way to ensure this is to make it a property of your iOSView.
Page 316
iOS Framework
Methods
AddRow(section As Integer, data As iOSTableCellData)
Adds the data to the section.
Notes
There has to be at least one section before you can add rows. If you do not want the section to appear, you can add
it with a blank title.
Exceptions
UnsupportedOperationException
Sample Code
Table1.AddSection("")
Dim cell As iOSTableCellData
For i As Integer = 0 To 4
cell = New iOSTableCellData("Row " + i.ToText)
Table1.AddRow(0, cell)
Next
Page 317
iOS Framework
Table1.AddSection("")
For i As Integer = 0 To 4
Table1.AddRow(0, "Row " + i.ToText)
Next
Sample Code
Table1.AddSection("Tasks")
Page 318
iOS Framework
InsertSection(index As Integer)
Inserts a section at the index.
ReloadData
Reloads all the table data from the DataSource.
Notes
It is faster to only reload the specific data that need to be refreshed, so consider using ReloadDataInSection or
ReloadRow.
ReloadDataInSection(section As Integer)
Reloads the table data for the section from the DataSource.
Sample Code
RemoveAll
Removes all rows from the table.
Exceptions
UnsupportedOperationException
Page 319
iOS Framework
Sample Code
Table1.RemoveAll</code>
RemoveSection(section As Integer)
Removes the section from the table (and all its rows).
Sample Code
iOS Framework
Table1.ReloadRow(0, 0)
Page 321
iOS Framework
iOSTableCellData
A cell within an iOSTable.
Class Summary
Name
iOSTableCellData
Type
Class
Inherits
n/a
Implements
n/a
Enumerations
AccessoryTypes
Properties
Targets
Mobile
Platforms
iOS
Related
iOSTable, iOSTableDataSource
Enumerations
AccessoryTypes
Additional UI controls for a cell.
None
Disclosure
You use the disclosure indicator when selecting a cell results in the display of another
table view reflecting the next level in the data model hierarchy.
Detail
You use the detail disclosure button when selecting a cell results in a detail view of that
item (which may or may not be a table view).
Checkmark
You use a checkmark when a touch on a row results in the selection of that item. This kind
of table view is known as a selection list, and it is analogous to a pop-up list. Selection
lists can limit selections to one row, or they can allow multiple rows with checkmarks.
Constructors
Constructor(text As Text, detail As Text = "", image As iOSImage = nil, accessory As AccessoryTypes
= AccessoryTypes.None)
Creates a new cell data using the text, detail, image, accessory values.
Page 322
iOS Framework
Properties
AccessoryType As AccessoryTypes
The accessory type that is displayed in the cell.
DetailText As Text
The the smaller text that appears below the main Text in the cell.
Image As iOSImage
The image for the cell.
Tag As Auto
A tag value for the cell.
Text As Text
The text of the cell. This is the main (large) text that appears for the row.
Page 323
iOS Framework
iOSTableDataSource (Interface)
A data source to use to populate a Table.
Interface Summary
Name
iOSTableDataSource
Type
Interface
Inherits
n/a
Implements
n/a
Methods
Targets
Mobile
Platforms
iOS
Related
iOSTable, iOSTableCellData
Notes
To use the interface, create a class that implements the interface to manage the data. The data could be in a
database, dictionary, array or anything else you want. Your class implements the methods below to return the
appropriate values based on the data it is managing.
Methods
RowCount(section As Integer) As Integer
The number of rows for the section.
SectionCount As Integer
The number of sections.
Page 324
iOS Framework
iOSTextArea (Control)
A multiline text area for displaying text.
Control Summary
Name
iOSTextArea
Type
Control
Super
iOSControl
Interfaces
n/a
Events
Properties
AccessibilityHint, AccessibilityLabel, Editable, Height, Hint, Left, Name, PanelIndex, Parent, Text,
TextAlignment, TextColor, TextFont, Top, Visible, Width
Methods
Handle
Targets
Mobile
Platforms
iOS
Related
iOSTextField
Events
SelChange
Called when the text selection changes.
TextChange
Called when the text changes.
Properties
Editable As Boolean
Indicates if the text is editable or read-only.
Text As Text
The text of the text area.
Page 325
iOS Framework
Sample Code
Set the text of the text area:
TextArea1.Text = "Hello, World!"
Get the text in the text area:
Dim desc As Text
desc = TextArea1.Text</code>
TextAlignment As iOSTextAlignment
The alignment of the text.
Sample Code
TextArea1.TextAlignment = iOSTextAlignment.Center
TextColor As Color
The color of the text.
Sample Code
TextArea1.TextColor = Color.Red
TextFont As iOSFont
The font used to display the text.
Sample Code
TextArea1.TextFont = iOSFont.BoldSystemFont
Page 326
iOS Framework
iOSTextField (Control)
A single-line text field for text.
Control Summary
Name
iOSTextField
Type
Control
Super
iOSControl
Interfaces
n/a
Events
Properties
Methods
Handle
Targets
Mobile
Platforms
iOS
Related
iOSTextArea
Events
TextChange
Called when the text changes.
Properties
Enabled As Boolean
Indicates if the field is enabled or disabled.
Sample Code
Disable the text field
TextField1.Enabled = False</code>
KeyboardType As iOSKeyboardTypes
Specifies the type of keyboard to use with the text field. The various types are specified using the
iOSKeyboardTypes enumeration.
Page 327
iOS Framework
Sample Code
Use the number pad for the text field:
Me.KeyboardType = iOSKeyboardTypes.NumberPad
Password As Boolean
Indicates if this is is a password, which means the text is obscured as it is entered.
PlaceHolder As Text
The placeholder text that appears when the field is empty.
Text As Text
The text in the field.
Sample Code
Sets the text in the field:
TextField1.Text = "Hello, World!"
Gets the text from the field:
Dim desc As Text
desc = TextField1.Text</code>
TextAlignment As iOSTextAlignment
The alignment for the text.
Sample Code
TextField1.TextAlignment = iOSTextAlignment.Center
TextColor As Color
The color of the text.
Sample Code
TextField1.TextColor = Color.Red
Page 328
iOS Framework
TextFont As iOSFont
The font used to display the text.
Sample Code
TextField1.TextFont = iOSFont.BoldSystemFont
Page 329
iOS Framework
iOSToolbar (Class)
A toolbar can be displayed in a view as its toolbar or navigation bar.
Class Summary
Name
iOSToolbar
Type
Class
Methods
Targets
Mobile
Platforms
iOS
Related
iOSToolButton, iOSView
Example Projects
Examples/iOS/Controls/ToolbarExample
Notes
Accessed using the LeftNavigationToolbar, RightNavigationToolbar and Toolbar properties of the iOS view.
Methods
Add(value As iOSToolButton)
Adds the button to the end of the toolbar.
Sample Code
RightNavigationToolbar.Add(iOSToolButton.NewSystemItem(iOSToolButton.Type.SystemAdd))
Count As Integer
The number of buttons on the toolbar.
Sample Code
Get the count of buttons on an iOSView:
If Toolbar <> Nil Then
Dim buttonCount As Integer = Toolbar.Count
End IF
Page 330
iOS Framework
RemoveAll
Removes all the BarButtons from the bar.
RemoveAllByValue(value As iOSToolButton)
Removes all of a specific button from the toolbar.
RemoveByIndex(index As Integer)
Removes the button at the specified index from the toolbar.
RemoveByValue(value As iOSToolButton)
Removes a specific button from the toolbar.
Page 331
iOS Framework
iOSToolButton (Control)
A button to add to a toolbar.
Class Summary
Name
iOSToolButton
Type
Control
Inherits
n/a
Implements
n/a
Enumerations
Type
Properties
Method
Handle
Shared Methods
Targets
Mobile
Platforms
iOS
Related
iOSToolbar
Enumerations
Type
System icons to use when creating buttons using NewSystemItem.
SystemAction
SystemAdd
SystemBookmarks
SystemCamera
SystemCancel
SystemCompose
SystemDone
SystemEdit
Page 332
iOS Framework
SystemFastForward
SystemFixedSpace
SystemFlexibleSpace
SystemOrganize
SystemPageCurl
SystemPause
SystemPlay
SystemRedo
SystemRefresh
SystemReply
SystemRewind
SystemSave
SystemSearch
SystemStop
SystemTrash
SystemUndo
Constructors
Constructor(type As iOSToolButton.Type, title As String = "", image As Image = Nil)
Creates a button with the specified type, title and image.
Properties
Caption As Text
Sets the caption for the button. If you have both a Caption and Image specified, then only the Image appears.
Enabled As Boolean
Enables or disables the button.
Page 333
iOS Framework
Image As Image
Specifies an image to display for the button. If you have both a Caption and Image specified, then only the Image
appears.
Notes
Only the mask for the image is used, displayed using the tint color for iOS (currently blue).
Tag As Auto
A tag value.
Type As iOSToolButton.Type
The button type.
Width As Double
The button width.
Methods
Handle As Ptr
Returns the iOS handle for use with Declares.
Shared Methods
FixedSpace As iOSToolButton
Creates a fixed space button.
Returns
A new iOSToolButton.
Sample Code
FlexibleSpace As iOSToolButton
Creates a flexible space button.
Page 334
iOS Framework
Returns
A new iOSToolButton.
Sample Code
image
Returns
A new iOSToolButton.
Notes
On iOS 7 and 8, this button looks the same as a button created with NewPlain.
image
Returns
A new iOSToolButton.
Notes
This button has a bold appearance.
Page 335
iOS Framework
Sample Code
Dim b As iOSToolButton
b = iOSToolButton.NewDone("Done")
Self.Toolbar.Add(b) // Add to toolbar on view
image
Sample Code
Dim b As iOSToolButton
b = iOSToolButton.NewPlain("Invoices")
Self.Toolbar.Add(b) // Add to toolbar on view
iOS Framework
iOSUserControl (Control)
Used to embed UIViews created via declares into the Xojo control hierarchy.
Control Summary
Name
iOSUserControl
Type
Class
Inherits
iOSControl
Implements
n/a
Events
CreateView
Targets
Mobile
Platforms
iOS
Related
Declare
Notes
Each iOSControl has an underlying UIView. The iOSUserControl class lets you hand the framework explicitly what
you want it to use for the UIView.
In the CreateView event, you should create and configure whatever UIView you want. If the UIView's initializer
requires a frame rectangle, pass in anything arbitrary (it will be placed correctly via auto layout). The UIView should
be returned autoreleased and not just the result of alloc+init.
You cannot place an iOSUserControl directly on a layout. You must subclass, implement
CreateView and then drag the subclass onto the layout.
Events
CreateView As Integer
Use this event to create the UIView to use for the control. Return the pointer to the UIView.
Page 337
iOS Framework
iOSView
The View is where you design your iOS layouts.
Class Summary
Name
iOSView
Type
Control
Inherits
n/a
Implements
Events
Properties
Methods
Targets
Mobile
Platforms
iOS
Related
Example Projects
Examples/iOS/Controls/MultipleViews
Examples/iOS/Controls/SplitViewExample
Events
Activate
Called when the view is activated.
Notes
This occurs when:
Close
Called when the View is closed by calling the Close method.
Notes
This is called by the Destructor.
Page 338
iOS Framework
Deactivate
Called when the view is deactivated. This occurs when:
Open
Called when the view first appears.
Notes
This event is called by the Constructor.
Resized
Called when the view is resized, which can occur when the device orientation changes.
ToolbarPressed(button As iOSToolButton)
Called when a button on the left or right navigation bar or the toolbar is pressed.
Sample Code
Properties
BackButtonTitle As Text
The back button that gets back to this view uses the text specified here.
Notes
This title does not appear on the back button for this view, but instead appears on the back button for any views
shown by this view (using PushTo). It is the title for the back button that goes back to this view.
Page 339
iOS Framework
LeftNavigationToolbar As iOSToolbar
The toolbar to display at the left of the navigation bar.
Sample Code
LeftNavigationToolbar.Add(iOSToolButton.NewSystemItem(iOSToolButton.Type.SystemAdd))
NavigationBarVisible As Boolean
Indicates whether the navigation bar is visible. The navigation bar must be visible in order to see the Title,
LeftNavigationToolbar or RightNavigationToolbar.
ParentSplitView As iOSSplitView
Indicates the split view that is the owner of this view. It is Nil is there is no split view.
Notes
Use this property to determine if a SplitView is displayed. You can then use it to get access to the Master and Detail
views that are displayed.
Sample Code
ParentTabBar As iOSTabBar
Indicates the tab bar that is the owner of this view. It is Nil if there is no tab bar.
Sample Code
Page 340
iOS Framework
RightNavigationToolbar As iOSToolbar
The toolbar to display at the right of the navigation bar.
Sample Code
RightNavigationToolbar.Add(iOSToolButton.NewSystemItem(iOSToolButton.Type.SystemAdd))
TabIcon As iOSImage
The icon for the tab that this view is displayed on.
TabTitle As Text
The title for the tab that this view is displayed on.
Title As Text
The title for the navigation bar. This only appears if NavigationBarVisible is True.
Sample Code
Toolbar As iOSToolbar
The toolbar that is displayed in the view, typically at the bottom.
Sample Code
Toolbar.Add(iOSToolButton.NewSystemItem(iOSToolButton.Type.SystemAdd))
Methods
AddConstraint(constraint As iOSLayoutConstraint)
Adds the constraint to the view.
Page 341
iOS Framework
AddControl(child As iOSControl)
Adds a control to the view.
Sample Code
Close
For views that were displayed using PushTo, this closes the view causing the previous view to display.
Notes
You cannot close the main View (the one that is specified as the Content for the Screen).
ContentSize As Size
The size (in points) of the content area. This excludes the Navigation Bar, if it is visible.
Sample Code
Page 342
iOS Framework
Sample Code
ControlCount As Integer
The number of controls on the view.
Sample Code
Handle As Ptr
The handle to use when creating Declares to UIView.
PushTo(newView As iOSView)
Displays a new view by "pushing" it onto the current view.
Sample Code
RemoveConstraint(constraint As iOSLayoutConstraint)
Removes the constraint from the view.
RemoveControl(child As iOSControl)
Removes the control from the view.
Size As Size
The size of the View (excluding the StatusBar if visible).
Sample Code
Page 343
iOS Framework
ViewControllerHandle As Ptr
The handle to use when creating Declares to UIView.
Page 344
iOS Framework
iOSViewController (Interface)
Identifies controls that can be on a screen.
Interface Summary
Name
iOSViewController
Type
Interface
Inherits
n/a
Implements
n/a
Methods
Targets
Mobile
Platforms
iOS
Related
Methods
ViewControllerHandle As Ptr
The handle to use for OS API calls.
ViewResized
TBD
ViewWillAppear
TBD
ViewWillDisappear
TBD
Page 345
iOS Framework
SQLiteDatabase (Class)
Provides access to SQLite databases.
Class Summary
Name
SQLiteDatabase
Type
Class
Inherits
n/a
Implements
n/a
Properties
DatabaseFile
EncryptionKey
LibraryVersion
ThreadYieldInterval
Timeout
Methods
AttachDatabase
Connect
CreateDatabaseFile
Decrypt
DetachDatabase
Encrypt
LastRowID
SQLExecute
SQLSelect
Targets
Mobile
Platforms
iOS
Related
Example Projects
SQLiteInMemory, SQLiteVersion
Notes
SQLiteDatabase uses SQLite 3.8.5. For more information about SQLite:
SQL Syntax
Pragma Commands
Unsupported SQL
If your database object goes out of scope, the database is closed. This means you are typically going to want your
database object be somewhat global to your app. A common technique is to have a SQLiteDatabase property on the
App object that you refer throughout your app as App.DB.
Transactions
SQLiteDatabase does an auto-commit after each SQL command if you do not manually start a transaction. You can
start a transaction using this command:
myDB.SQLExecute("BEGIN TRANSACTION")
Page 346
iOS Framework
When the transaction is complete, you commit your changes with this command:
myDB.SQLExecute("COMMIT")</code>
You can cancel a transaction by calling rollback with this command:
myDB.SQLExecute("ROLLBACK")</code>
Properties
DatabaseFile As FolderItem
Specifies the FolderItem for the SQLite database file. If DatabaseFile is Nil, calling the Connect method creates an inmemory database.
EncryptionKey As Text
Specifies the encryption key used to open an encrypted database or to encrypt a database.
Notes
To encrypt a new database, specify this value before calling CreateDatabaseFile.
To connect to an encrypted database, specify this value before calling Connect.
To encrypt an existing database, use the Encrypt method after you have created or connected to the database.
ThreadYieldInterval As Integer
Yields time back to your application every N virtual machine instructions. The unit is virtual machine instructions.
Timeout As Double
The maximum number of seconds that an operation may wait before a lock is cleared (if any).
Page 347
iOS Framework
Notes
A SQLiteDatabase can be locked while it is being modified. On iOS, you will not need to worry about the timeout
unless you have multiple threads accessing a database using separate connections.
Methods
AttachDatabase(file As FolderItem, databaseName As Text, encryptionKey As Text = "") As Boolean
Attaches the SQLite database referred to by file to the database. It gives the newly attached database the name
databaseName. If the database is encrypted, be sure to specify the encryptionKey.
Notes
You can attach one or more databases to a currently connected SQLiteDatabase so that you can work with all the
databases at one time. This can be useful to copy data between databases, for example.
If tables in the attached database have the same name as tables in the primary database, you can refer to them
using databaseName as the prefix.
Connect As Boolean
Connects to the database so that you can begin using it. Before proceeding with database operations, test to be
sure that Connect returns True.
Notes
To create an in-memory SQLite database, call Connect without specifying a DatabaseFile.
Sample Code
Connect to an existing database:
Dim db As New SQLiteDatabase
Dim dbFile As FolderItem
dbFile = SpecialFolder.Documents.Child("MyDB.sqlite")
If dbFile.Exists Then
db.DatabaseFile = dbFile
If db.Connect Then
//proceed with database operations here...
Else
Dim err As Text = "Could not open the database."
End If
End If
Page 348
iOS Framework
CreateDatabaseFile As Boolean
Creates a database file. Returns True if the database was successfully created.
Notes
You are automatically connected if CreateDatabase returns True, so you do not need to also call Connect.
Sample Code
Create a new SQLiteDatabase:
Dim dbFile As FolderItem
dbFile = SpecialFolder.Documents.Child("MyDB.sqlite")
Dim db As New SQLiteDatabase
db.DatabaseFile = dbFile
If db.CreateDatabaseFile Then
// proceed with database operations here...
Else
Dim err As Text = "Database could not be created."
End If
Decrypt
Removes the encryption from an encrypted database. You must be connected to the database in order to decrypt it.
Notes
Decrypting a database removes the encryption. You do not need to decrypt the database for normal use. Only use
this command if you want to actually remove the encryption so that you can later connect to the database without
providing the encryption key.
DetachDatabase(databaseName As Text)
Detaches the passed database that was previously attached with AttachDatabase.
Encrypt(encryptionKey As Text)
Encrypts the database using password as the encryption key. If you are already connected to an encrypted
database and call Encrypt with an empty string, the database is decrypted.
LastRowID As Int64
Returns an Int64 containing the value of the last RowID added to any table in the database.
Page 349
iOS Framework
Page 350
SQLiteDatabase
Examples/iOS/Database
SQLiteInMemory
This example demonstrates these features:
Create an in-memory SQLite database
Add a table to the database using SQLiteDatabase.SQLExecute
Add data to the table using SQLiteDatabase.SQLExecute
Display the data in an iOSTable using SQLiteDatabase.SQLSelect
Refer to the CreateTableWithData and LoadData methods.
SQLiteVersion
Uses SQLiteDatabase.LibraryVersion to display the version of SQLite being used.
Page 351
iOS Framework
SQLiteDatabaseField (Class)
Used to access the values of fields in a row of a SQLite database table.
Item Summary
Name
SQLiteDatabaseField
Type
Class
Inherits
n/a
Implements
n/a
Properties
Targets
Mobile
Platforms
iOS
Related
Properties
BooleanValue As Boolean (read-only)
Gets the boolean value for a column.
Sample Code
Page 352
iOS Framework
Page 353
iOS Framework
Page 354
iOS Framework
SQLiteException (Class)
Raised when there are errors when using a SQLiteDatabase.
Class Summary
Name
SQLiteException
Type
Class
Inherits
LogicException
Implements
n/a
Properties
CallStack, Reason
Targets
All
Platforms
All
Related
Notes
You should always check for an SQLiteException after calling commands such as SQLExecute or SQLSelect.
Sample Code
Dim sql As Text
sql = "SELECT * FROM Team"
Dim data As SQLiteRecordSet
Try
data = DB.SQLSelect(sql)
Catch e As SQLiteException
ErrorLabel.Text = e.Reason
Return
End Try
// Now you can use the results
Page 355
iOS Framework
SQLiteRecordSet (Class)
A SQLiteRecordSet is a group of SQLiteDatabase rows and is the result of a SELECT statement.
Class Summary
Name
SQLiteRecordSet
Type
Class
Inherits
n/a
Implements
n/a
Properties
Methods
Targets
Mobile
Platforms
iOS
Related
Sample Code
Get the first column of data from the results of a table SELECT:
Dim sql As Text
sql = "SELECT * FROM Team"
Dim data As SQLiteRecordSet
Try
data = DB.SQLSelect(sql)
Catch e As SQLiteException
ErrorLabel.Text = e.Reason
Return
End Try
If data <> Nil Then
While Not data.EOF
TextArea1.Text = TextArea1.Text + Text.FromUnicodeCodepoint(10) +
data.IdxField(0).TextValue
data.MoveNext
Wend
data.Close
Page 356
iOS Framework
End If
Properties
BOF As Boolean (read-only)
Indicates if the RecordSet is pointing before the first row.
Methods
Close
Closes the RecordSet.
MoveFirst
Moves the RecordSet pointer to the first row of the RecordSet.
MoveLast
Moves the RecordSet pointer to the last row in the RecordSet.
Page 357
iOS Framework
MoveNext
Moves the RecordSet pointer to the next row in the RecordSet. If the pointer was at the last row, then this moves
the pointer to EOF.
MovePrevious
Moves the RecordSet pointer to the previous row in the RecordSet. If the pointer was at the first row, then this
moves the poiner to BOF.
RecordCount As Integer
The number of rows in the RecordSet.
Page 358
Framework
Xojo
The Xojo namespace contains all parts of the Xojo framework.
Namespace Summary
Name
Xojo
Type
Namespace
Namespaces
Enumerations
iOSKeyboardTypes, iOSTextAlignment
Methods
IsText
Targets
All
Platforms
All
Related
Notes
iOS projects include the entire Xojo namespace by default (Using Xojo.*), making it simple to refer
to all the classes.
Enumerations
iOSKeyboardTypes
Used to specify the type of keyboard to use with text fields and text areas.
Default
ASCIICapable
NumbersAndPunctuation
URL
Use a keyboard optimized for URL entry. This type features ., /, and .com
prominently.
NumberPad
Use a numeric keypad designed for PIN entry. This type features the numbers 0
through 9 prominently. This keyboard type does not support auto-capitalization.
PhonePad
Use a keypad designed for entering telephone numbers. This type features the
numbers 0 through 9 and the * and # characters prominently. This keyboard type
does not support auto-capitalization.
Page 359
Framework
NamePhonePad
Use a keypad designed for entering a persons name or phone number. This keyboard
type does not support auto-capitalization.
EmailAddress
Use a keyboard optimized for specifying email addresses. This type features the @,
. and space characters prominently.
DecimalPad
Use a keyboard optimized for twitter text entry, with easy access to the @ and #
characters.
WebSearch
Use a keyboard optimized for web search terms and URL entry. This type features the
space and . characters prominently.
iOSTextAlignment
Used to specify alignment for iOS controls.
Left
Center
Right
Justified
Fully justify the text so that the last line in a paragraph is natural aligned.
Natural
Methods
IsText(val As Auto) As Boolean
Determines if the supplied Auto value contains a Text.
Page 360
Xojo
Xojo.Core
The Xojo.Core namespace contains core classes you can use in all your projects.
Namespace Summary
Name
Xojo.Core
Type
Namespace
Classes
Targets
All
Platforms
All
Related
Notes
Normally you have to include the full namespace to access the classes in Xojo.Core. The Using command allows you
to just refer to the classes by name. For example, at the top of a method you can put this code:
Using Xojo.Core
Within the method you are then able to access the classes in Xojo.Core just by their simple names. So instead of
Xojo.Core.Dictionary, you can write:
Dim d As Dictionary
iOS projects include the entire Xojo namespace by default (Using Xojo), making it simple to refer to
all the classes.
Page 361
Core
Date (Class)
Used to store date/time values. Once a date is created, it cannot be modified, but you can create new dates by
applying a DateInterval to an existing date.
Class Summary
Name
Xojo.Core.Date
Type
Class
Inherits
n/a
Implements
n/a
Enumerations
FormatStyles
Properties
Methods
ToText
Shared Methods
FromText, Now
Operators
Add, Subtract
Targets
All
Platforms
OS X, iOS
Related
DateInterval, TimeZone
Example Projects
Examples/iOS/Framework/DateExample
Notes
You cannot use Dim d As New Date to get the current date. Instead, use Dim d As Date =
Date.Now or more simply, just Date.Now.
Constructors
Constructor(secondsFrom1970 As Double, timezone As TimeZone)
Creates a date using number of seconds from the first instant of 1 January 1970, GMT. Use a negative value to refer
to specify a date before this date.
Sample Code
Convert a date in the current time zone to GMT:
Page 362
Core
Dim myDate As Date = Date.Now // Get date for current time zone
Dim gmt As New TimeZone(0) // Get GMT time zone
Dim gmtDate As New Date(myDate.SecondsFrom1970, gmt)
Constructor(year As Integer, month As Integer, day As Integer, hour As Integer = 0, minute As Integer
= 0, seconds As Integer = 0, nanoseconds As Integer = 0, timezone As TimeZone)
Creates a new date using the specified values. Use this method to create a specific date.
Sample Code
Enumerations
FormatStyles
Short
Medium
Long
Full
None
Properties
Day As Integer (read-only)
The day of the month as a number.
Sample Code
Page 363
Core
Core
Page 365
Core
Methods
ToText(loc As Locale = Nil, dateStyle As FormatStyles = FormatStyles.Medium, timeStyle As
FormatStyles = FormatStyles.Medium) As Text
Converts the Date (along with the time component) to a text format using the optional locale and formats.
Notes
The default non-locale savvy version (loc is Nil) of ToText returns a date in the format YYYY-MM-DD HH:MM:SS.
Example date output would be: 2014-10-31 09:38:24
Sample Code
Display the current date and time:
Dim d As Date = Date.Now
Label1.Text = d.ToText
To get just the date portion:
Dim d As Date = Date.Now
Dim t As Text = d.ToText(Locale.Current, Date.FormatStyles.Short,
Date.FormatStyles.None)
Page 366
Core
Shared Methods
FromText(input As Text, loc As Locale = Nil) As Date
Converts a textual date to an actual date using the optional locale.
Notes
When no locale is specified, you can choose to include a time portion in 24-hour format.
Sample Code
Now As Date
The current date and time.
Example
Operators
+ (Add)
You can add a Date and a DateInterval to get a new Date.
Sample Code
Get the date two months from today:
Dim twoMonths As New DateInterval
twoMonths.Month = 2 // 2 month interval
// Get date two months from today
Dim future As Date = Date.Now + twoMonths
Page 367
Core
- (Subtract)
You can subtract a Date and a DateInterval to get a new Date.
You can subtract a Date from a Date and get a DateInterval
Example
Get the date two months before today:
Dim twoMonths As New DateInterval
twoMonths.Month = 2 // 2 month interval
// Get date two months before today
Dim past As Date = Date.Now - twoMonths
Calculate the interval until January 1, 2030:
Dim d2 As New Date(2030, 1, 1, TimeZone.Current)
Dim interval As DateInterval
interval = d2 - Date.Now
Page 368
Core
DateInterval (Class)
A DateInterval is used to modify a date object. You specify how much you want to offset the date by and then add
(or subtract) the interval to the date to get a new date object.
Item Summary
Name
Xojo.Core.DateInterval
Type
Class
Inherits
n/a
Implements
n/a
Properties
Targets
All
Platforms
All
Related
Date
Constructors
Constructor(years As Integer = 0, months As Integer = 0, days As Integer = 0, hours As Integer = 0,
minutes As Integer = 0, seconds As Integer = 0, nanoseconds As Integer = 0)
Specifies an interval using the various properties.
Example
Creates a date that is two months from today and two months before today:
Dim d As Date = Date.Now
Dim di As New DateInterval
di.Month = 2 // 2 months
// Get date two months from today
Dim d2 As Date = d + di
// Get date two months before today
Dim d3 As Date = d - di
Properties
Page 369
Core
Days As Integer
The number of days in the interval.
Hours As Integer
The number of hours in the interval.
Minutes As Integer
The number of minutes in the interval.
Months As Integer
The number of months in the interval.
NanoSeconds As Integer
The number of nanoseconds in the interval.
Seconds As Integer
The number of seconds in the interval.
Years As Integer
The number of years in the interval.
Page 370
Core
Dictionary (Class)
The Dictionary class is an unordered, mutable, key-value store that is loosely typed. It implements the Iterable
interface, allowing efficient and easy iteration over all key-value pairs.
Class Summary
Name
Xojo.Core.Dictionary
Type
Class
Inherits
n/a
Implements
Iterable
Events
CompareKeys
Properties
Count
Methods
Targets
All
Platforms
All
Related
DictionaryEntry
Events
CompareKeys(lhs As Auto, rhs As Auto) As Integer
Implement this event handler if you would like the Dictionary to support case-sensitive keys.
Parameters
lhs
rhs
Returns
Return a positive integer if lhs is greater than rhs.
Return 0 if lhs is the same as rhs.
Return a negative integer is lhs is less than rhs.
Example
This code does a case-sensitive comparison of the text value of the specified keys:
Page 371
Core
Properties
Count As Integer
The number of entries in the Dictionary (read-only).
Methods
Clone As Dictionary
Performs a shallow clone of the Dictionary, resulting in a new Dictionary that can be manipulated independently of
the first. A shallow clone means that if a Dictionary Value or Key refers to a class instance, its contents are not also
cloned.
Return Value
Returns the clone of the Dictionary.
Example
Clone a dictionary and then change the original:
Dim d1 As New Dictionary
d1.Value("Test") = "Hello, World!"
Dim d2 As Dictionary
d2 = d1.Clone
d1.Value("Test") = "Changed!"
// d2.Value("Test") is still "Hello, World!"
Page 372
Core
Return Value
True if the key exists in the Dictionary, False if it does not.
Example
Check if "Test" is used as a key value:
If Not d1.HasKey("Test") Then
d1.Value("Test") = "Initial value"
End If
GetIterator As Iterator
Creates a new iterator for the Dictionary which will yield DictionaryEntry objects for its values. Part of the Iterable
interface.
Notes
You will not typically access this method directly. Instead use the ability to iterate over the Dictionary using a
For..Each loop.
Example
Iterate over the Dictionary entries using For Each:
Using Xojo.Core
Dim d As New Dictionary
d.Value("One") = "Testing"
d.Value("Two") = "Iterator"
For Each entry As DictionaryEntry In d
TextArea1.Text = TextArea1.Text + " " + entry.Key + " " + entry.Value
Next
defaultValue
An Auto value that is returned when the key is not found in the Dictionary.
Page 373
Core
Return Value
Returns the value for key (if key is found). Returns the defaultValue if key is not found.
Example
if the User ID is not found in the Dictionary, return "UnknownUser":
Dim userID As Integer = 123
Dim user As Text
user = d1.Lookup(userID, "UnknownUser")
RemoveAll
Removes all entries from the Dictionary. This invalidates all interators that were created from the Dictionary.
Example
Remove all entries from a Dictionary:
d1.RemoveAll
Remove(key As Auto)
Removes a single entry with the specified key from the Dictionary, invalidating all iterators that were created from
the Dictionary. If there is no entry in the Dictionary for the key, a KeyNotFoundException is raised.
Parameters
key
Exceptions
KeyNotFoundException
Example
Remove the entry for the value "Test" in the Dictionary:
d1.Remove("Test")
Core
Parameters
key
newValue
Example
As this is an extension method, you use it with the assignement operator.
Dim d As New Xojo.Core.Dictionary
d.Value(123) = "Bob Roberts"
Exceptions
KeyNotFoundException
Example
Page 375
Core
DictionaryEntry (Class)
The DictionaryEntry class represents a single key-value pair in a Dictionary. It is immutable and is not tied to the
Dictionary it was created from, so subsequent updates to the Dictionary will not change the DictionaryEntry
property values.
Class Summary
Name
Xojo.Core.DictionaryEntry
Type
Class
Inherits
n/a
Implements
n/a
Properties
Key, Value
Targets
All
Platforms
All
Related
Dictionary
Properties
Key As Auto
The entry's key (read-only).
Example
Value As Auto
The entry's value (read-only).
Example
Page 376
Core
Next
Page 377
Core
Iterable (Interface)
The Iterable interface allows objects to denote themselves as being able to be used with "For Each" loops and
provides a way to create Iterators, which do the actual work.
Interface Summary
Name
Xojo.Core.Iterable
Type
Interface
Aggregates
n/a
Methods
GetIterator
Targets
All
Platforms
All
Related
Dictionary
Methods
GetIterator As Iterator
Returns an Iterator that can be used with "For Each" loops.
Example
Classes that implement Iterable, such as Dictionary, can be used with For..Each loops:
Dim entries() As Xojo.Core.DictionaryEntry
For Each entry As Xojo.Core.DictionaryEntry In d
TextArea1.Text = TextArea1.Text + " " + entry.Key + " " + entry.Value
Next
Page 378
Core
Iterator (Interface)
Iterators perform the actual task of yielding values from the Iterable object.
Interface Summary
Name
Xojo.Core.Iterator
Type
Interface
Aggregates
n/a
Methods
MoveNext, Value
Targets
All
Platforms
All
Related
DictionaryEntry, Iterable
Notes
Initially the Iterator is positioned before the first item and invoking MoveNext is required before accessing the
Iterator's current value. Failure to do so is undefined behavior and typically results in the implementor raising an
exception.
The MoveNext method advances the Iterator one item. If the Iterator has ran out of values to yield, MoveNext
returns False and continues returning False until the Interator is destructed. Access to the interator's current value
at that point is undefined behavior and implementors typically raise an exception.
Iterators may be invalidated if the iterable object is was created from is mutated. Invoking MoveNext or Value on an
invalidated iterator results in undefined behavior and implementors should raise an exception.
While the iterator is valid, the Value method must remain the same across multiple calls to Value until MoveNext
has been invoked.
Methods
MoveNext As Boolean
Moves the iterator to the next item.
Return Value
Returns False when there are no more items, otherwise returns True.
Page 379
Core
Value As Auto
The value of the current item in the iterator. The Value is invalid when MoveNext returns False. It is also invalid
before the first call to MoveNext.
Return Value
Returns the value of the current item in the iterator.
Page 380
Core
Locale (Class)
Used to represent a locale, which describes linguistic, cultural and other locale-specific information. For example, a
locale might specify "English as spoken in the United States, using the metric system".
Class Summary
Name
Xojo.Core.Locale
Type
Class
Inherits
n/a
Implements
n/a
Properties
Shared Properties
Current, Raw
Targets
All
Platforms
All
Related
Text
Constructors
Constructor(localeIdentifier As Text)
Creates a locale with the given localeIdentifier.
Notes
Use the two-letter ISO 639-1 standard combined with the the ISO 3166-1 standard, for example "en-US" for English
in the United States.
Exceptions
RuntimeException
Invalid localeIdentifier.
Example
Create an English US locale:
Dim locale As New Xojo.Core.Locale("en-US")
Page 381
Core
Properties
Identifier As Text (read-only)
This is the locale's identifier. The identifier may not exactly match the identifier passed in via the constructor due to
conversions (e.g. 'en_US' could become 'en-US').
Example
Get the locale's identifier:
Dim locale As New Xojo.Core.Locale("en-US")
Dim id As Text
id = locale.Identifier
Core
Example
Get the locale's decimal separator:
Dim locale As New Xojo.Core.Locale("en-US")
Dim decimal As Text
decimal = locale.DecimalSeparator
Shared Properties
Current As Locale (read-only)
The user's current locale. For web apps, this is the session's current locale, which is based off of the information sent
by the browser and will return Nil if there is no session or the information is unavailable.
Example
Get the current locale:
Dim currentLocale As Xojo.Core.Locale
currentLocale = Xojo.Core.Locale.Current
Page 383
Core
MemoryBlock (Class)
A read-only class for managing blocks of memory. Since the contents of a MemoryBlock cannot be altered, if you
need to alter a MemoryBlock, use MutableMemoryBlock.
Class Summary
Name
Xojo.Core.MemoryBlock
Type
Class
Inherits
n/a
Implements
n/a
Properties
Methods
Targets
All
Platforms
All
Related
Constructors
Constructor(size As UInteger)
Creates a MemoryBlock with the desired size in bytes.
Parameters
size
The size (in bytes) of the MemoryBlock to create. Size is either a 32-bit or 64-bit unsigned integer
depending on the OS.
Exceptions
OutOfMemoryException
If there is insufficient memory to allocate size bytes and there is sufficient memory to
recover from this error.
Sample Code
Page 384
Core
A Ptr that points to a chuck of memory that was allocated using some other method such as a Declare to an
OS API call.
size
The size (in bytes) of the allocated memory as either a 32-bit or 64-bit unsigned integer depending on the
OS. This size is used for bounds checking on the various getter and setter functions.
Notes
The pointer p serves as the MemoryBlock's backing. Mutating the MemoryBlock will also mutate the contents of the
chunk of memory. The MemoryBlock does not take ownership of the memory, so the application is responsible for
freeing it after the MemoryBlock has been destructed. If it is freed before then, all MemoryBlock behavior is
undefined and will likely crash.
Exceptions
NilObjectException
If p is Nil.
RuntimeException
If size is 0.
RuntimeException
Constructor(p As Ptr)
Creates a MemoryBlock from an existing chuck of memory.
Parameters
p
A Ptr that points to a chunk of memory that was allocated using some other method such as a Declare to an
OS API call.
Constructor(bytes() As Byte)
Creates a MemoryBlock from an existing Byte array.
Parameters
bytes()
Notes
The contents of the Byte array are copied into the MemoryBlock. Mutating the MemoryBlock has no effect on the
Page 385
Core
original array.
Exceptions
NilObjectException
If bytes() is Nil.
OutOfMemoryException
If there is insufficient memory to copy the byte array and there is sufficient memory to
recover from this error.
Sample Code
Constructor(other As MemoryBlock)
Creates a new MemoryBlock with the data from an existing MemoryBlock.
Sample Code
Properties
LittleEndian As Boolean
When True, indicates that the MemoryBlock data is in LittleEndian format. The default is True.
Page 386
Core
Methods
Clone As MemoryBlock
Makes a copy of the MemoryBlock. If its size is unknown, it copies the content.
Exceptions
RuntimeException
OutOfBoundsException
length
Page 387
Core
Exceptions
OutOfBoundsException
OutOfBoundsException
Exceptions
OutOfBoundsException
RuntimeException
Page 388
Core
Operators
Page 389
Core
= (Comparison)
MemoryBlocks can be compared with each other using the "=" operator.
Notes
MemoryBlocks are considered equal for these conditions:
The MemoryBlocks are the same object
Both MemoryBlocks' data point to the same location
Both MemoryBlocks' size and content are the same
There is no concept of one MemoryBlock being greater than or less than another MemoryBlock.
Page 390
Core
MutableMemoryBlock (Class)
A mutable class for managing and modifying blocks of memory.
Class Summary
Name
Xojo.Core.MutableMemoryBlock
Type
Class
Inherits
MemoryBlock
Implements
n/a
Properties
Methods
Targets
All
Platforms
All
Related
Constructors
Constructor(size As UInteger)
Creates a MemoryBlock with the desired size in bytes.
Parameters
size
The size (in bytes) of the MemoryBlock to create. Size is either a 32-bit or 64-bit unsigned integer
depending on the OS.
Exceptions
OutOfMemoryException
If there is insufficient memory to allocate size bytes and there is sufficient memory to
recover from this error.
Page 391
Core
Parameters
p
A Ptr that points to a chuck of memory that was allocated using some other method such as a Declare to an
OS API call.
size
The size (in bytes) of the allocated memory as either a 32-bit or 64-bit unsigned integer depending on the
OS. This size is used for bounds checking on the various getter and setter functions.
Notes
The pointer p serves as the MemoryBlock's backing. Mutating the MemoryBlock will also mutate the contents of the
chunk of memory. The MemoryBlock does not take ownership of the memory, so the application is responsible for
freeing it after the MemoryBlock has been destructed. If it is freed before then, all MemoryBlock behavior is
undefined and will likely crash.
Exceptions
NilObjectException
If p is Nil.
RuntimeException
If size is 0.
RuntimeException
Constructor(p As Ptr)
Creates a MemoryBlock from an existing chuck of memory.
Parameters
p
A Ptr that points to a chunk of memory that was allocated using some other method such as a Declare to an
OS API call.
Constructor(bytes() As Byte)
Creates a MemoryBlock from an existing Byte array.
Parameters
bytes()
Notes
The contents of the Byte array are copied into the MemoryBlock. Mutating the MemoryBlock has no effect on the
original array.
Exceptions
NilObjectException
If bytes() is Nil.
Page 392
Core
OutOfMemoryException
If there is insufficient memory to copy the byte array and there is sufficient memory to
recover from this error.
Constructor(other As MemoryBlock)
Creates a MutableMemoryBlock from a MemoryBlock.
Parameters
other
Methods
Append(other As MemoryBlock)
Append(other() As Byte)
Appends other data (which consists of either a MemoryBlock or a Byte array) to the end of the MemoryBlock and
adjusts its size. This invalidates the Data property.
Parameters
other
You can supply the data to append as either another MemoryBlock or a Byte array.
Exceptions
NilObjectException
If other is Nil.
RuntimeException
If the source MemoryBlock has an unknown size or if the other MemoryBlock has an
unknown size.
You can supply the data to append as either another MemoryBlock or a Byte array.
Exceptions
NilObjectException
If other is Nil.
RuntimeException
If the source MemoryBlock has an unknown size or if the other MemoryBlock has an
unknown size.
Page 393
Core
OutOfBoundsException
The starting offset (in bytes) in the MemoryBlock from which to remove bytes.
length
Exceptions
RuntimeException
OutOfBoundsException
If the offset (or offset + length) is greater than the size of the MemoryBlock.
value
When replacing data, specifies the MemoryBlock or the Byte array to use.
Exceptions
NilObjectException
RuntimeException
OutOfBoundsException
Page 394
Core
length
Exceptions
OutOfBoundsException
NilObjectException
OutOfBoundsException
value
When replacing data, specifies the MemoryBlock or the Byte array to use.
Exceptions
OutOfBoundsException
RuntimeException
NilObjectException
Page 395
Core
Page 396
Core
Point (Class)
Represents a point in 2D space. Useful for things like the center of a rectangle or the location of the mouse or touch
event. Points are immutable and cannot be changed.
Class Summary
Name
Xojo.Core.Point
Type
Class
Inherits
n/a
Implements
n/a
Properties
X, Y
Methods
DistanceTo, Translate
Shared Methods
Zero
Targets
All
Platforms
All
Related
Rect, Size
Constructors
Constructor(X As Double, Y As Double)
Initializes the Point with an (x, y) of the parameters passed in.
Properties
X As Double (read-only)
The point's X coordinate.
Y As Double (read-only)
The point's X coordinate.
Methods
DistanceTo(Other As Point) As Double
Page 397
Core
Return Value
Returns a double that measures the distance between the two points.
Example
Calculate the distance (length of the line) between two points:
Dim p1 As New Xojo.Core.Point(10, 20)
Dim p2 As New Xojo.Core.Point(200, 5)
Dim dist As Double = p1.DistanceTo(p2)
deltaY
Return Value
Returns a new Point with the updated coordinates.
Example
Create a new point that is 100 greater than the old point's X coordinate:
Dim origPoint As New Point(50, 50)
Dim newPoint As Point = origPoint.Translate(100, 0)
Shared Methods
Zero As Xojo.Core.Point
Returns a Point with an (x, y) of (0, 0). This is a convenience for creating a new Point with those coordinates and
allows the implementation to have a singleton value (as Point objects are immutable).
Page 398
Core
Example
Calculate the distance from (0, 0):
Dim origPoint As New Point(123, 456)
Dim distance As Double = Xojo.Core.Point.Zero.DistanceTo(origPoint)
Operators
Add (+)
You can use the plus operator (+) to add the X and Y coordinates of the points together and get a new Point:
Example
Adds two points together to get a new point:
Dim p1 As New Point(50, 50)
Dim p2 As New Point(25, 40)
Dim p3 As Point = p1 + p2 // p3 is (75, 90)
Negate (-)
Use the negate operator (-) to create a new point with the X and Y coordinates negated.
Example
Negate an existing point to get a new point:
Dim p1 As New Point(50, 50)
Dim p2 As Point
Page 399
Core
Subtract (-)
Use the subtraction operator (-) to subtract the coordinates of two points to get a new Point.
Example
Subtract two points to get a new point:
Dim p1 As New Point(50, 50)
Dim p2 As New Point(10, 10)
Dim p3 As Point
p3 = p1 - p2 // p3 is (40, 40)
Page 400
Core
Rect (Class)
A way to represent an axis-aligned rectangular area. Rect can be used for window size/position, control size/position
and drawing of controls.
Class Summary
Name
Xojo.Core.Rect
Type
Class
Inherits
n/a
Implements
n/a
Properties
Methods
Targets
All
Platforms
All
Related
Point, Size
Constructors
Constructor(left As Double, top As Double, width As double, Height As Double)
Creates a new Rect with the specified values.
Parameters
left
top
width
height
Example
Create a new Rect:
Dim myRect As New Rect(10, 10, 100, 50)
Page 401
Core
size
Example
Creates a new Rect:
Dim p As New Point(10, 10)
Dim s As New Size(100, 50)
Dim myRect As New Rect(p, s)
Properties
Bottom As Double (read-only)
The bottom position of the Rect.
Page 402
Core
Methods
Contains(P As Point) As Boolean
Determines if the point is contained within the rect.
Page 403
Core
Operators
Comparison
Compares first by Size, then by Origin
Page 404
Core
Size (Class)
Used to represent 2D sizes, commonly used for window/view size, control size, etc.
Class Summary
Name
Xojo.Core.Size
Type
Class
Inherits
n/a
Implements
n/a
Properties
Height, Width
Shared Methods
Zero
Targets
All
Platforms
All
Related
Point, Rect
Constructors
Constructor(width As Double, height As Double)
Creates a new Size using she specified values.
Properties
Height As Double (read-only)
The height.
Shared Methods
Between(p1 As Point, p2 As Point) As Size
Calculates the Size between two points.
Page 405
Core
Zero As Size
A Size with width and height of 0.
Operators
Operator_Add(other As Size) As Size
Operator_Compare(Target As Size) As Integer
Compare first by width, then by height.
Operator_Divide(divisor As Double) As Size
Operator_Multiply(factor As Double) As Size
Operator_Negate() As Size
Operator_Subtract(other As Size) As Size
Page 406
Core
StackFrame (Class)
Represents a single frame on the stack.
Class Summary
Name
Xojo.Core.StackFrame
Type
Class
Inherits
n/a
Implements
n/a
Properties
Address, Name
Targets
All
Platforms
All
Related
RuntimeException
Properties
Address As Ptr (read-only)
The frame's instruction pointer.
Page 407
Core
TextEncoding (Class)
An encoding represents a way of converting text to and from raw bytes. Encodings are created from IANA character
set names or the shared properties for the very common encodings. Use this class to convert Text to specific
encodings.
Class Summary
Name
Xojo.Core.TextEncoding
Type
Class
Inherits
n/a
Implements
n/a
Properties
IANAName
Methods
ConvertTextToData, ConvertDataToText
Shared Properties
Shared Methods
FromIANAName
Targets
All
Platforms
All
Related
Locale, Text
Properties
IANAName As Text (read-only)
The encoding's name as specified in IANA's Character Sets document.
Methods
ConvertTextToData(value As Text, allowLossy As Boolean = False) As MemoryBlock
Converts a text value to bytes.
Parameters
value
allowLossy
When True, any characters that cannot be represented are replaced with a question mark.
Page 408
Core
Return Value
Returns a MemoryBlock containing the converted data.
Notes
If the value cannot be represented accurately in this encoding, an exception is raised. The allowLossy parameter
can be used to override this behavior. If it is True, any characters that cannot be represented are replaced with a
question mark. For example, Emoji is not representable in the ASCII encoding.
If the encoding is UTF-16 or UTF-32, the resulting data will begin with a byte order mark. If the byte order mark is
not desired, the encoding should specify an explicit big endian or little endian (e.g. using UTF32LittleEndian).
Exceptions
RuntimeException
Example
Convert text to UTF-8 data:
Dim t As Text = "Jbberwcky"
Dim utf8Data As Xojo.Core.MemoryBlock
utf8Data = Xojo.Core.TextEncoding.UTF8.ConvertTextToData(t)
allowLossy
When True, any characters that cannot be represented are replaced with the Unicode replacement
character (U+FFFD).
Return Value
Returns a Text value of the converted data.
Notes
Converts a chunk of data to Text. If the data is not valid for this encoding (e.g. overlong UTF-8 sequences), an
exception is raised. The allowLossy parameter can be used to override this behavior. If it is True, any invalid input is
replaced with the Unicode replacement character (U+FFFD).
Page 409
Core
Exceptions
NilObjectException
If data is Nil.
RuntimeException
RuntimeException
Example
Convert UTF-8 data to text:
Dim t As Text = "Jbberwcky"
Dim utf8Data As Xojo.Core.MemoryBlock
utf8Data = Xojo.Core.TextEncoding.UTF8.ConvertTextToData(t)
Dim decodedText As Text
decodedText = Xojo.Core.TextEncoding.UTF8.ConvertDataToText(utf8Data)
Shared Properties
ASCII As TextEncoding (read-only)
Returns the ASCII text encoding.
Page 410
Core
Shared Methods
FromIANAName(name As Text) As TextEncoding
Returns an encoding given its IANA name as specified in IANA's Character Sets document.
Parameters
name
Return Value
Returns the appropriate TextEncoding.
Exceptions
RuntimeException
If name is empty.
RuntimeException
Example
Gets the US ASCII encoding from its name:
Dim encoding As Xojo.Core.TextEncoding
encoding = Xojo.Core.TextEncoding.FromIANAName("US-ASCII")
Page 411
Core
Timer (Class)
This class calls its Action event handler at specified intervals.
Class Summary
Name
Xojo.Core.Timer
Type
Class
Inherits
n/a
Implements
n/a
Enumerations
Modes
Events
Action
Properties
Shared Methods
CallLater, CancelCall
Targets
All
Platforms
All
Related
Enumerations
Modes
Specifies when the timer gets called.
Off
Single
Calls the Action event handler once after the Period is reached, then turns the Timer to Off.
Multiple
Call the Action event handler each time the Period is reached.
Events
Action
Called when the Timer interval is reached, based on the Mode and Period properties.
Sample Code
This code updates a ProgressBar:
Page 412
Core
ProgressBar1.Value = ProgressBar1.Value + 1
// Stop Timer when ProgressBar reaches maximum
If ProgressBar1.Value > ProgressBar1.MaxValue Then
Me.Mode = Xojo.Core.Timer.Modes.Off
End If
Properties
Mode As TimerMode
Specifies if the timer calls the Action event handler once, multiple times or not at all.
Example
Set the Mode to Multiple:
Timer1.Mode = Xojo.Core.Timer.Modes.Multiple
Period As Integer
Specifies the number of millseconds between calls to the Action event handler.
Notes
A period of 0 means to start the timer immediately on the next event loop and is useful for creating a Timer that
runs as soon as possible.
Sample Code
Set the period to 1 second:
Timer1.Period = 1000
Tolerance As Integer
A hint to the system as to how precise (in milliseconds) you need the timer to be, although you may get less
tolerance that this depending on what the operating system supports. A value of 0 (the default) means to use the
standard for the platform. A value of 100 asks for 100 millisecond tolerance.
Shared Methods
CallLater(afterMsec As Integer, method As Xojo.Core.Timer.CallNoParams)
Used to call a method (without parameters) once (after the specified delay in milliseconds).
Page 413
Core
Parameters
afterMSec
method
Sample Code
Suppose you want to display some help text for a few seconds and then hide it. You can do this by creating a
method to clear a Label (ClearLabel):
Sub ClearLabel
MyLabel.Text = ""
End Sub
In the initial method, you set the Label help text and then use CallLater to set it to clear it after 2 seconds:
MyLabel.Text = "Help text goes here"
Xojo.Core.Timer.CallLater(2000, AddressOf ClearLabel)
method
argument
Sample Code
Suppose you want to display some help text for a few seconds and then replace it with different text. You can do
this by creating a method that takes the text to display as a parameter (SetLabel):
Sub SetLabel(helpText As Auto)
MyLabel.Text = helpText
End Sub
In the initial method, you set up the Label help text and use CallLater to change it after 2 seconds:
MyLabel.Text = "First help text goes here"
Xojo.Core.Timer.CallLater(2000, AddressOf SetLabel, "Second help text goes here")
Page 414
Core
CancelCall(method As Xojo.Core.Timer.CallNoParams)
Used to cancel a previously scheduled CallLater that has not yet been run.
Parameters
method
Sample Code
Cancel the ClearLabel callback:
Xojo.Core.Timer.CancelCall(AddressOf ClearLabel)
CancelCall(method As Xojo.Core.Timer.CallWithArg)
Used to cancel a previously scheduled CallLater that has not yet been run.
Parameters
method
Sample Code
Cancel the SetLabel callback:
Xojo.Core.Timer.CancelCall(AddressOf SetLabel)
Page 415
Core
TimeZone (Class)
Used to identify a time zone in relationship to a Date.
Class Summary
Name
Xojo.Core.TimeZone
Type
Class
Inherits
n/a
Implements
n/a
Properties
Abbreviation, SecondsFromGMT
Shared Method
Current
Targets
All
Platforms
All
Related
Date
Constructors
Constructor(gmtOffsetInSeconds As Integer)
Creates a time zone using the specified GMT offset.
Constructor(name As Text)
Creates a time zone using the specified name. If the name is invalid, then an InvalidArgumentException is raised.
Properties
Abbreviation As Text (read-only)
The abbreviation for the time zone.
Shared Methods
Current As TimeZone
The current time zone.
Page 416
Core
WeakRef (Class)
The WeakRef class is used to store references to an object without maintaining a strong reference that would force
the target object to remain in memory instead of getting removed by reference conuting.
Class Summary
Name
Xojo.Core.WeakRef
Type
Class
Inherits
n/a
Implements
n/a
Properties
Value
Shared Methods
Create
Targets
All
Platforms
All
Related
Properties
Value As Object (read-only)
The object that is wrapped by the WeakRef object. If the object has been destructed, this returns Nil.
Shared Methods
Create(value As Object) As WeakRef
Creates a WeakRef that wraps the given object.
Parameters
value
Exceptions
NilObjectException
If value is Nil.
Example
Create a WeakRef of an object instance:
Page 417
Core
Page 418
Exceptions
BadDataException (Class)
Raised when the data passed into a function is invalid.
Class Summary
Name
Xojo.Core.BadDataException
Type
Class
Inherits
RuntimeException
Implements
n/a
Properties
Methods
CallStack, Stack
Targets
All
Platforms
All
Related
Notes
This typically only applies to the actual data, such as the bytes passed into TextEncoding.ConvertDataToText.
Page 419
Exceptions
ErrorException (Class)
Represents an exception that is not necessarily caused by programmer error but rather something from the OS. A
good example is trying to write to a read-only file. Checking the writability in advance introduces a 'time of check to
time of use' race condition, so the correct thing actually is to just open it.
Class Summary
Name
Xojo.Core.ErrorException
Type
Class
Inherits
RuntimeException
Implements
n/a
Properties
Methods
CallStack, Stack
Targets
All
Platforms
All
Related
Notes
Constants
POSIXErrorDomain
POSIX
The error domain for error codes coming from POSIX functions in the form of
errno values (OS X and Linux).
WindowsErrorDomain
Windows
The error domain for error codes coming from Windows functions in the form
of HRESULT values.
XojoErrorDomain
Xojo
The error domain for the framework's cross platform error codes.
Properties
ErrorDomain As Text (read-only)
The error domain for the framework's cross platform error codes, specified using the constants POSIXErrorDomain,
WindowsErrorDomain and XojoErrorDomain.
Page 420
Exceptions
Page 421
Exceptions
InvalidArgumentException (Class)
Raised when an invalid argument is passed to a function.
Class Summary
Name
Xojo.Core.InvalidArgumentException
Type
Class
Inherits
RuntimeException
Implements
n/a
Properties
Methods
CallStack, Stack
Targets
All
Platforms
All
Related
Page 422
Exceptions
IteratorException (Class)
Raised when an invalid operation is performed on an iterator. For example, invoking Value before calling MoveNext.
Class Summary
Name
Xojo.Core.IteratorException
Type
Class
Inherits
RuntimeException
Implements
n/a
Properties
Methods
CallStack, Stack
Targets
All
Platforms
All
Related
Page 423
Exceptions
LogicException (Class)
A runtime exception.
Class Summary
Name
Xojo.Core.LogicException
Type
Class
Inherits
RuntimeException
Implements
n/a
Properties
Methods
CallStack, Stack
Targets
All
Platforms
All
Related
Page 424
Exceptions
UnsupportedOperationException (Class)
An unsupported operation occurred.
Class Summary
Name
Xojo.Core.UnsupportedOperationException
Type
Class
Inherits
LogicException
Implements
n/a
Properties
Methods
CallStack, Stack
Targets
All
Platforms
All
Related
Page 425
Xojo
Xojo.Crypto
This namespace contains hashing methods for use with cryptography.
Namespace Summary
Name
Xojo.Crypto
Type
Namespace
Enumerations
HashAlgorithms
Methods
Classes
CryptoException
Targets
Mobile
Platforms
iOS
Related
Example Projects
Examples/iOS/Framework/CryptoExample
Notes
Uses Crypto++ Library 5.6.2.
Enumerations
HashAlgorithms
Used by the HMAC method to specify the type of algorithm to use.
MD5
SHA1
SHA256
SHA512
Methods
GenerateRandomBytes(byteCount As UInteger) As MemoryBlock
Generates a random block of data of the specified byteCount.
Page 426
Xojo
RuntimeException
Page 427
Xojo
Page 428
Xojo
Page 429
Crypto
CryptoException (Class)
This exception is raised by the various Crypto methods when an error occurs.
Class Summary
Name
Xojo.Crypto.CryptoException
Type
Class
Inherits
RuntimeException
Implements
n/a
Enumerations
Events
Properties
Methods
Targets
Mobile
Platforms
iOS
Related
Page 430
Xojo
Xojo.Data
This namespace contains methods and classes used for handling data.
Namespace Summary
Name
Xojo.Data
Type
Namespace
Methods
GenerateJSON, ParseJSON
Classes
InvalidJSONException
Targets
Mobile
Platforms
iOS
Related
Methods
GenerateJSON(value As Auto) As Text
Generates JSON text from the supplied value, which is a Dictionary or array of Dictionaries.
Example
Convert a Dictionary of values to JSON data:
Dim d As New Dictionary
d.Value("Team") = "Red Sox"
d.Value("City") = "Boston"
Dim json As Text
json = Xojo.Data.GenerateJSON(d)
If you want to store an array of information, create an array of Dictionaries and use that to generate the JSON:
Dim dictArray() As Dictionary
Dim d As New Dictionary
d = New Dictionary
d.Value("Team") = "Red Sox"
d.Value("City") = "Boston"
dictArray.Append(d)
d = New Dictionary
Page 431
Xojo
d.Value("Team") = "Yankees"
d.Value("City") = "New York"
dictArray.Append(d)
Dim json As Text
json = Xojo.Data.GenerateJSON(dictArray)
Page 432
Data
InvalidJSONException (Class)
Raised when the JSON is invalid.
Class Summary
Name
Xojo.Core.InvalidJSONException
Type
Class
Inherits
RuntimeException
Implements
n/a
Properties
CallStack, Reason
Targets
All
Platforms
All
Related
GenerateJSON, ParseJSON
Page 433
Xojo
Xojo.Introspection
This namespace contains methods and classes used for introspection.
Namespace Summary
Name
Xojo.Introspection
Type
Namespace
Classes
Methods
GetType
Targets
Mobile
Platforms
iOS
Related
Example Projects
Examples/iOS/Framework/IntrospectionExample
Methods
GetType(obj As Auto) As TypeInfo
Gets a TypeInfo object that describes the supplied object. Before you can do anything with introspection, you need
to use this method to get a TypeInfo object.
Notes
You can supply any data type, including simple types (Integer, Text, etc.), object instances, arrays and structures.
Each TypeInfo instance that is returned is unique and immutable, so two objects of the same class will always return
the same TypeInfo instance.
Example
Gets the TypeInfo for a window and displays its name:
Dim info As TypeInfo = GetType(Self)
Label1.Text = "Window name: " + info.Name
Page 434
Introspection
AttributeInfo (Class)
Provides information on the attributes of a class instance, method or property using introspection.
Class Summary
Name
Xojo.Core.AttributeInfo
Type
Class
Inherits
n/a
Implements
n/a
Enumerations
Events
Properties
Name, Value
Methods
Targets
Mobile
Platforms
iOS
Related
Notes
Attributes are added to project items, methods, properties, constants, etc. by using the "Advanced" tab of the
Inspector.
Properties
Name As Text
The name of the attribute.
Example
This code displays the names of all the attributes on Class1 in a ListBox:
Using Xojo.Introspection
Dim obj As New Class1
Dim info As TypeInfo = GetInfo(obj)
Page 435
Introspection
Value As Auto
The optional value of the attribute.
Page 436
Introspection
ConstructorInfo (Class)
Provides information on the constructors of a class instance using introspection.
Class Summary
Name
Xojo.Introspection.ConstructorInfo
Type
Class
Inherits
MemberInfo
Implements
n/a
Enumerations
Events
Properties
Methods
GetAttributes, Invoke
Targets
Mobile
Platforms
iOS
Related
Methods
Invoke(Optional params() As Auto) As Auto
Creates an new instance and invokes the target constructor on the class instance, passing in the specified
parameters.
Parameters
params()
Returns
An Auto containing the data type of the object.
Notes
Exceptions
OutOfBoundsException if the number of parameters do not match?
IllegalCastException if the types of parameters do not match?
Page 437
Introspection
Example
Page 438
Introspection
MemberInfo (Class)
The superclass for many of the Introspection classes.
Class Summary
Name
Xojo.Core.MemberInfo
Type
Class
Inherits
n/a
Implements
n/a
Properties
Methods
GetAttributes, Parameters
Targets
Mobile
Platforms
iOS
Related
Properties
IsGlobal As Boolean
Checks if the item has global scope.
IsPrivate As Boolean
Checks if the item has private scope.
IsProtected As Boolean
Checks if the item has protected scope.
IsPublic As Boolean
Checks if the item has public scope.
Name As Text
The name of the item.
Page 439
Introspection
Methods
GetAttributes As AttributeInfo()
Gets the attributes for the associated item.
Returns
Return an array of the attributes.
Example
The following code gets the attributes for the window containing the code:
Dim myAttributes() As Instrospection.AttributeInfo
myAttributes = GetType(Self).GetAttributes
Parameters As ParameterInfo()
Gets the parameters for the member.
Page 440
Introspection
MethodInfo (Class)
Provides information on the methods of a class instance using introspection.
Class Summary
Name
Xojo.Introspection.MethodInfo
Type
Class
Inherits
MemberInfo
Implements
n/a
Enumerations
Events
Properties
Methods
Targets
Mobile
Platforms
iOS
Related
ParameterInfo
Properties
IsShared As Boolean
Checks if this is a shared method.
ReturnType As TypeInfo
The return type of the method.
Methods
Invoke(target As Object, Optional params() As Auto) As Auto
Calls the method, given its base object and an instance of the class that created it.
Page 441
Introspection
Parameters
params()
Returns
For a function call, returns an Auto containing the return value of the function.
Notes
You can use Nil as the base object if calling a shared method.
Exceptions
OutOfBoundsException if the number of parameters do not match?
IllegalCastException if the types of parameters do not match?
Example
Page 442
Introspection
ParameterInfo (Class)
Provides information on method parameters using introspection.
Class Summary
Name
Xojo.Core.ParameterInfo
Type
Class
Inherits
n/a
Implements
n/a
Properties
IsByRef, ParameterType
Targets
Mobile
Platforms
iOS
Related
MethodInfo
Notes
You get an array of ParameterInfo objects by calling MemberInfo.Parameters.
Properties
IsByRef As Boolean
Checks if the parameter is passed ByRef instead of ByVal.
ParameterType As TypeInfo
Type information for the parameter.
Page 443
Introspection
PropertyInfo (Class)
Provides information on the methods of a class instance using introspection.
Class Summary
Name
Xojo.Core.PropertyInfo
Type
Class
Inherits
MemberInfo
Implements
n/a
Properties
Methods
Value
Targets
Mobile
Platforms
iOS
Related
Properties
CanRead As Boolean
The property value can be read, indicating a simple value property or a computed property with a Get accessor.
CanWrite As Boolean
The property value can be written, indicating a simple value property or a computed property with a Set accessor.
IsComputed As Boolean
Checks if the property is a computed property or a value property.
IsShared As Boolean
Checks if this is a shared property.
Methods
Value(obj As Object) As Auto
Page 444
Introspection
Description of parameter.
Page 445
Introspection
TypeInfo (Class)
Contains type information for objects, arrays, simple data types and structures.
Class Summary
Name
Xojo.Core.TypeInfo
Type
Class
Inherits
MemberInfo
Implements
n/a
Properties
Methods
Targets
Mobile
Platforms
iOS
Related
Properties
BaseType As TypeInfo
Gets parent (or Super) of the current object. Allows you to navigate the type hiearchy from child to parent.
FullName As Text
The fully qualified name used as a unique identifier. This can differ from the simple name whenever the type lives in
a namespace.
HasElementType As Boolean
Compound data types have their own attributes as well as an element type.
IsArray As Boolean
Indicates the item is an array.
IsClass As Boolean
Indicates the item is a class.
Page 446
Introspection
IsEnum As Boolean
Indicates the item is an enumeration.
IsInterface As Boolean
Indicates the item is a class interface.
IsPointer As Boolean
Indicates the item is a Ptr or another external pointer type.
IsPrimitive As Boolean
Indicates the item is a primitive type, which are: Boolean, String, Color, Integer, Double, Single, Currency and other
numeric types.
IsValueType As Boolean
Indicates the item is a value type, which means it is not a reference. With value types, assignments copy the value
itself rather than the reference to the value. Primitive, pointer, structure and enum types are all value types.
Methods
ArrayElementType As TypeInfo
Get the type information for the array.
Returns
The TypeInfo for the element type.
Exceptions
RuntimeException
ArrayRank As Integer
The number of dimensions of an array. For arrays only (IsArray = True).
Returns
An integer indicating the number of dimensions of the array.
Page 447
Introspection
Notes
Exceptions
RuntimeException
Example
GetAttributes As AttributeInfo()
Gets the attributes for the item, which must be a class instance.
Returns
An array of AttributeInfo objects.
Constructors As ConstructorInfo()
Gets the constructors for the item, which must be a class instance.
Returns
An array of ConstructorInfo objects.
Methods As MethodInfo()
Gets the methods for the item, which must be a class instance.
Returns
An array of MethodInfo objects.
Properties As PropertyInfo()
Gets the properties for the item, which must be a class instance.
Returns
An array of PropertyInfo objects.
Xojo
IO
Contains classes used for file input and output.
Namespace Summary
Name
Xojo.IO
Type
Namespace
Enumerations
HandleTypes
Classes
Targets
Mobile
Platforms
iOS
Related
Enumerations
HandleTypes
The type of OS handle for the stream.
FileNumber
FilePointer
Win32
Page 449
IO
BinaryStream (Class)
The BinaryStream class is an input/output mechanism for reading and writing arbitrary binary data. It can be used
with MemoryBlocks and FolderItems.
Class Summary
Name
Xojo.IO.BinaryStream
Type
Class
Inherits
n/a
Implements
n/a
Constructors
Constructor(MemoryBlock)
Enumerations
LockModes
Properties
Methods
Shared Methods
Targets
Mobile
Platforms
iOS
Related
FolderItem, MemoryBlock
Notes
The Read/Write methods raise an exception when reading or writing past the end of the stream.
Sample Code
// Load an image that is copied to an iOS app using a Copy Files Build Step
Dim f As FolderItem = SpecialFolder.GetResource("MyImage.JPG")
Dim b As BinaryStream
b = BinaryStream.Open(f, BinaryStream.LockModes.Read)
Dim mb As New MemoryBlock(b.Read(b.Length))
Page 450
IO
b.Close
Dim image As iOSImage
image = Image.FromData(mb)
ImageView1.Image = image
Constructors
Constructor(mb As MemoryBlock)
Creates a BinaryStream from a MemoryBlock.
Enumerations
LockModes
The type of locking modes for the binary stream.
Read
Read access.
Write
Write access.
ReadWrite
Exclusive
Properties
IsClosed As Boolean (read-only)
Determines if the binary stream has been closed.
Length As UInt64
Gets or sets the length of the file in bytes. If you set the Length property to a value smaller than its current value, it
truncates the file. If the BinaryStream is backed by a MemoryBlock, it returns MemoryBlock.Size. Raises an
exception if setting the Length of a BinaryStream backed by a MemoryBlock with unknown size.
LittleEndian As Boolean
Gets or sets the byte order when reading or writing to a BinaryStream. A value of True sets the byte order to little
endian.
Position As UInt64
Gets or sets the current position within the BinaryStream. The first position is numbered zero. To move the position
Page 451
IO
Methods
Close
Closes an existing BinaryStream. Raises an exception if the stream is already closed.
EOF As Boolean
Returns True if the BinaryStream position = the file length. If the stream is closed this function always returns True.
Flush
Immediately sends the contents of internal write buffers to disk or to the output stream.
ReadBoolean As Boolean
Reads a Boolean from the stream. Raises an exception if the file is not readable.
ReadCurrency As Currency
Reads a Currency from the stream. Raises an exception if the file is not readable.
ReadDouble As Double
Reads a Boolean from the stream. Raises an exception if the file is not readable.
ReadInt16 As Int16
Reads an Int16 from the stream. Raises an exception if the file is not readable.
ReadInt32 As Int32
Reads an Int32 from the stream. Raises an exception if the file is not readable.
Page 452
IO
ReadInt64 As Int64
Reads an Int64 from the stream. Raises an exception if the file is not readable.
ReadInt8 As Int8
Reads an Int8 from the stream. Raises an exception if the file is not readable.
ReadSingle As Single
Reads a Single from the stream. Raises an exception if the file is not readable.
ReadUInt16 As UInt16
Reads a UInt16 from the stream. Raises an exception if the file is not readable.
ReadUInt32 As UInt32
Reads a UInt32 from the stream. Raises an exception if the file is not readable.
ReadUInt64 As UInt64
Reads a UInt64 from the stream. Raises an exception if the file is not readable.
ReadUInt8 As UInt8
Reads a UInt8 from the stream. Raises an exception if the file is not readable.
Write(block As MemoryBlock)
Writes the bytes in the memoryblock. Raises an exception if the stream is not writable or the MemoryBlock has an
unknown size.
WriteBoolean(value As Boolean)
Writes a Boolean to the stream. Raises an exception if the stream is not writable.
Page 453
IO
WriteCurrency(value As Currency)
Writes a Currency to the stream. Raises an exception if the stream is not writable.
WriteDouble(value As Double)
Writes a Double to the stream. Raises an exception if the stream is not writable.
WriteInt16(value As Int16)
Writes an Int16 to the stream. Raises an exception if the stream is not writable.
WriteInt32(value As Int32)
Writes an Int32 to the stream. Raises an exception if the stream is not writable.
WriteInt64(value As Int64)
Writes an Int64 to the stream. Raises an exception if the stream is not writable.
WriteInt8(value As Int8)
Writes an Int8 to the stream. Raises an exception if the stream is not writable.
WriteSingle(value As Single)
Writes a Single to the stream. Raises an exception if the stream is not writable.
WriteUInt16(value As UInt16)
Writes a UInt16 to the stream. Raises an exception if the stream is not writable.
WriteUInt32(value As UInt32)
Writes a UInt32 to the stream. Raises an exception if the stream is not writable.
WriteUInt64(value As UInt64)
Writes a UInt64 to the stream. Raises an exception if the stream is not writable.
Page 454
IO
WriteUInt8(value As UInt8)
Writes a UInt8 to the stream. Raises an exception if the stream is not writable.
Shared Methods
Create(file As FolderItem) As BinaryStream
Creates a new BinaryStream, bound to the passed File. Raises a RuntimeException if File is Nil, does not exist, is not
accessible or another error occurs.
Page 455
IO
FolderItem (Class)
The FolderItem class is used to represent files, applications, folders and other items in the file system.
Class Summary
Name
Xojo.IO.FolderItem
Type
Class
Inherits
n/a
Implements
n/a
Properties
Methods
Targets
Mobile
Platforms
iOS
Related
BinaryStream
Notes
To get a reference to a FolderItem, use SpecialFolder. For example:
Dim file As FolderItem = SpecialFolder.Documents("MyFile.txt")
Properties
Count As UInteger (read-only)
The number of items in the FolderItem if it is a folder. If the item is not a folder then it returns 0.
CreationDate As Date
The creation date of the FolderItem.
Notes
In order to change the creation date, you need to create a new Date and then assign it to this property. Changing
the CreationDate property directly will not cause the date to actually get changed.
Page 456
IO
Exceptions
RuntimeException
If the creation date can not be changed when attepting to set a new date.
Examples
Get the creation date:
Dim createDate As Xojo.Core.Date
createDate = MyFile.CreationDate
To change the creation date:
Dim newDate As New Xojo.Core.Date(2014, 8, 1)
MyFile.CreationDate = newDate
IO
End If
Page 458
IO
ModificationDate As Date
The modification date of the FolderItem.
Notes
In order to change the modification date, you need to create a new Date and then assign it to this property.
Changing the ModificationDate property directly will not cause the date to actually get changed.
Name As Text
The name of the FolderItem. Changing this name renames the file or folder.
Exceptions
RuntimeException
Methods
Page 459
IO
resolveAlias
Indicates if the FolderItem should resolve to its actual item, if the FolderItem is an alias or shortcut.
If the path points to an alias or shortcut, the FolderItem is resolved to the actual item being pointed to only
if resolveAlias is True.
Exceptions
RuntimeException
If the child cannot be constructed, which would only be the case if the FolderItem is not a
folder, or the last last component of the path does not already exist.
Example
Page 460
IO
IOException (Class)
Raised when there is a file input/output error.
Class Summary
Name
Xojo.Core.IOException
Type
Class
Inherits
ErrorException
Implements
n/a
Properties
Methods
CallStack, Stack
Targets
Mobile
Platforms
iOS
Related
BinaryStream, FolderItem
Page 461
IO
SpecialFolder (Module)
The SpecialFolder modules provides access to OS-specific folders.
Module Summary
Name
Xojo.IO.SpecialFolder
Type
Module
Methods
Targets
Mobile
Platforms
iOS
Related
FolderItem
Methods
ApplicationSupport As FolderItem
On iOS, this is the location of application support files (Library/Application Support).
Exceptions
RuntimeException
Sample Code
Caches As FolderItem
The OS folder for storing cache data.
Exceptions
RuntimeException
Sample Code
Page 462
IO
Documents As FolderItem
The Document folder is where will likely want to place most user-created files or data.
Exceptions
RuntimeException
Sample Code
Sample Code
Temporary As FolderItem
The user's temporary folder.
Exceptions
RuntimeException
Sample Code
Page 463
IO
TextInputStream
The BinaryStream class is an input/output mechanism for reading and writing arbitrary binary data. It can be used
with MemoryBlocks and FolderItems.
Class Summary
Name
Xojo.IO.TextInputStream
Type
Class
Inherits
n/a
Implements
n/a
Properties
BytePosition, Encoding
Methods
Shared Methods
Open
Targets
Mobile
Platforms
iOS
Related
FolderItem, TextOutputStream
Constructors
Constructor(handle As Ptr, type As HandleTypes, encoding As TextEncoding)
Creates a new TextInputStream based on the handle that was passed.
Exceptions
IOException
If the handle is invalid or the type does not match the handle.
Properties
BytePosition As UInt64
Gets or sets the byte position of the file pointer, not the character position. The first position is numbered zero.
Exceptions
IOException
Page 464
IO
Encoding as TextEncoding
Gets or sets the default encoding for the Read, ReadAll and ReadLine methods.
Exceptions
IOException
If Encoding is Nil.
Methods
Close
Closes the stream.
Exceptions
IOException
EOF As Boolean
Returns True when a Read method reaches the end of the stream.
Exceptions
IOException
ReadAll As Text
Reads all remaining bytes from the stream and returns them as a Text object.
Page 465
IO
Exceptions
IOException
ReadLine As Text
Reads bytes from the stream until and EOL character is encountered and returns them as a Text object.
Exceptions
IOException
Shared Methods
Open(file As FolderItem, encoding As TextEncoding) As TextInputStream
Creates a TextInputStream and connects it to the specified file.
Exceptions
IOException
When file = Nil, file does not exist or file is not readable.
Page 466
IO
TextOutputStream
Used for outputting text data to files.
Class Summary
Name
Xojo.IO.TextOutputStream
Type
Class
Inherits
n/a
Implements
n/a
Properties
Delimiter, Encoding
Methods
Shared Methods
Append, Create
Targets
Mobile
Platforms
iOS
Related
FolderItem, TextInputStream
Properties
Delimiter As Text
The character used to mark the end of a line of text written to the file. If this value is not set, the OS default for
EndOfLine is used.
Encoding As TextEncoding
The encoding used for writing the text. Raises an exception if set to Nil.
Methods
Close
Closes the TextOutputStream.
Flush
Immediately sends the contents of internal write buffers to disk or to the output stream.
Page 467
IO
Write(data As Text)
Writes the passed data to the output stream.
WriteLine(data As Text)
Writes the passed data to the output stream followed by the character(s) defined in Delimiter.
Shared Methods
Append(f As FolderItem, encoding As TextEncoding) As TextOutputStream
Opens the passed file so that text can be appended to existing text.
Exceptions
IOException
Examples
Create a text file and write data to it:
Dim f As New FolderItem("SaveData.txt")
Dim output As TextOutputStream
Page 468
IO
Try
output = TextOutputStream.Create(f, TextEncoding.UTF8)
output.WriteLine("Hello, World!")
output.Close
Catch e As IOException
Label1.Text = "Unable to create or write to file."
End Try
Page 469
Xojo
Xojo.Math
The Math namespace contains math-related constants and functions.
Namespace Summary
Name
Xojo.Math
Type
Module
Methods
Abs, ACos, ASin, ATan, ATan2, Ceil, Cos, Exp, Floor, Log, Max, Min, RandomInt, Round, Sign, Sin, Sqrt,
Tan
Targets
Mobile
Platforms
iOS
Related
Methods
Abs(value As Double) As Double
Returns the absolute value of a number.
Parameters
value
Return Value
Returns the absolute value of the specified value.
Sample Code
Get the absolute values:
Using Xojo.Math
Dim d As Double
d = Abs(23.9) // returns 23.9
d = Abs(-23.9) // returns 23.9
Page 470
Xojo
Parameters
value
Return Value
Returns the arccosine in radians.
Return Value
Returns the arcsine in radians.
Example
Return Value
Returns the arctangent in radians.
Page 471
Xojo
Return Value
Returns the arctangent in radians.
Return Value
Returns the nearest whole number rounded up from value.
Sample Code
Get the ceiling of a number:
Using Xojo.Math
Dim d As Double
d = Ceil(1.234) // returns 2
Ceil only works to whole numbers so if you want to get round using a specific number of decimal places, you first
have to multiple the number by 10^(number of decimal places), calculate the ceil and then divide it by the same
value to get the number. For example, this example rounds 1.2345 to 1.3:
Using Xojo.Math
Dim d As Double
Const kDecimalPlaces = 1
d = Ceil(1.2345 * (10 ^ kDecimalPlaces)) / (10 ^ kDecimalPlaces) // d = 1.3
Return Value
Returns the cosine in radians.
Page 472
Xojo
Sample Code
Gets the cosine of a 45 degree angle:
Using Xojo.Math
Dim angle As Double = 45 * (Pi/180) // Convert 45 degrees to radians
Dim value As Double
value = Cos(angle) // value = 0.707
Return Value
Returns the specified exponent of "e".
Return Value
Returns the nearest whole number rounded down from value.
Sample Code
The floor of a decimal number:
Using Xojo.Math
Dim d As Double
d = Floor(1.234) // d = 1
Page 473
Xojo
Return Value
Returns the natural logarithm.
Sample Code
Log 10:
Using Xojo.Math
Dim d As Double
d = Log(10) // d = 2.3025851
Return Value
Returns the maximum of all the values.
Sample Code
Calculates the maximum of multiple values:
Using Xojo.Math
Dim d As Double
d = Max(3.01, 4.05) // d = 4.05
d = Max(3.012, 3.011, 1.56) // d = 3.012
Dim i As Integer
i = Max(4, 8, 1, 9, 13, 11, 4) // i = 13
Page 474
Xojo
Return Value
Returns the minimum of all the values.
Return Value
Returns the nearest whole number to the value.
Sample Code
Some rounding examples:
Using Xojo.Math
Dim
d =
d =
d =
d =
d As Double
Round(1.499) //
Round(1.500) //
Round(1.1) // d
Round(1.7) // d
d
d
=
=
= 1
= 2
1
2
Page 475
Xojo
Parameters
value
Return Value
Returns the sign of the number, -1 if the number is negative, 0 if it is zero and 1 if the number is positive.
Sample Code
Using Xojo.Math
Dim numSign As Integer
numSign = Sign(-55) // numSign = -1
numSign = Sign(42) // numSign = 1
numSign = Sign(0) // numSign = 0
Return Value
Returns the arcosine in radians.
The value (in radians) for which you want the sine.
Return Value
Returns the sine in radians.
Sample Code
Calculate the sine:
Using Xojo.Math
Page 476
Xojo
Dim d As Double
d = Sin(0.5) // d = 0.4794255
d = Sin(30 * Pi/180) // d = 0.5, which is the sine of a 30 degree angle
The value (in radians) for which you want the tangent.
Return Value
Returns the tangest in radians.
Sample Code
Calculate the tangent:
Using Xojo.Math
Dim d As Double
d = Tan(45 * Pi/180) // d = 1.0 which is the tangent of a 45 degree angle
Page 477
Xojo
Net
Contains network related classes that work across all target platforms.
Namespace Summary
Name
Xojo.Net
Classes
Targets
Mobile
Platforms
iOS
Related
Page 478
Net
HTTPSocket (Class)
Used to send and receive data via the HTTP 1.1 protocol.
Class Summary
Name
Xojo.Net.HTTPSocket
Type
Class
Inherits
n/a
Implements
n/a
Constants
SizeUnknown
Events
Properties
ValidateCertificates
Methods
Targets
Mobile
Platforms
iOS
Related
TCPSocket
Example Projects
Examples/iOS/Networking/HTTPSocket
Constants
SizeUnknown
-1
Events
AuthenticationRequired(realm As Text, ByRef name As Text, ByRef password As Text) As Boolean
Called when the connection requires authentication. Set the name and password and return True.
Error(err As RuntimeException)
Called when an HTTP error occurs.
Net
Properties
ValidateCertificates As Boolean
Indicates that the socket should validate appropriate certificates.
Methods
ClearRequestHeaders
Clears all of the request headers.
Disconnect
Disconnects the socket.
Net
Page 481
Net
NetException (Class)
Indicates a network error.
Item Summary
Name
Xojo.Net.NetException
Type
Class
Inherits
ErrorException
Implements
n/a
Constants
InvalidCertificate, OperationTimedOut
Targets
Mobile
Platforms
iOS
Related
Constants
InvalidCertificate
10
OperationTimedOut
Page 482
Net
SSLSettings (Class)
Description of the item.
Item Summary
Name
Xojo.Net.SSLSettings
Type
Class
Inherits
n/a
Implements
n/a
Enumerations
SecurityLevels
Properties
SecurityLevel, ValidateCertificates
Targets
Mobile
Platforms
iOS
Related
TCPSocket
Enumerations
SecurityLevels
Security levels that can be used with sockets.
None
No security settings.
SSLv2
SSLv3
TLSv1
Negotiated
Most of the time you should use this setting, which will use the best security level available starting
with TLSv12.
Properties
SecurityLevel As SecurityLevels
Specifies the security level. This defaults to SecurityLevels.Negotiated.
ValidateCertificates As Boolean
Page 483
Net
Indicates that the related certificates should be validated using the specified security level.
Page 484
Net
TCPSocket (Class)
This class is used for TCP/IP communication.
Item Summary
Name
Xojo.Net.TCPSocket
Type
Class
Inherits
n/a
Implements
n/a
Enumerations
HandleTypes
Events
Properties
Methods
Targets
Mobile
Platforms
iOS
Related
SSLSettings
Example Projects
Examples/iOS/Networking/EasyTCPSocket
Examples/iOS/Networking/TCP
Enumerations
HandleTypes
Available handle types.
FileDescriptor
CFReadStream
CFWriteStream
Events
ConfigureSocket
Called when the socket needs to be configured.
Page 485
Net
Connected
Called when the socket connects to another socket or server.
DataAvailable
Called when additional data has come into the internal receive buffer.
Notes
It is your responsibility to read the data from the buffer using the ReadData method.
Disconnected
Called when the socket disconnects after previously being connected.
Error(err As RuntimeException)
Called when an error occurs, with err containing the exception causing the error.
Properties
Address As Text
The TCP/IP address to connect with.
BytesAvailable As UInteger
The number of bytes of data that are available in the internal receive buffer. You can get the data by calling the
ReadData method.
IsConnected As Boolean
Indicates whether the socket is currently connected.
Port As Int32
The port to bind on or connect to.
Notes
On most operating systems, attempting to bind on a port less than 1024 (without administrator priviledges) causes
an Error event.
You need to set the port property explicitly before any call to Connect as the Port property is changed to reflect the
actual port that the OS has bound to.
Page 486
Net
SSLSettings As SSLSettings
Specifies the SSL settings for the socket.
Methods
AvailableData As MemoryBlock
Returns the data available in the receive buffer.
Connect
Attempts to connect to the specified address and port.
Disconnect
Disconnects the socket, resets it, and calls the Disconnected event handler.
WriteData(data As MemoryBlock)
Writes data to the socket.
Page 487
Xojo
Xojo.System
This namespace contains system-specific functions and classes.
Namespace Summary
Name
Xojo.System
Methods
DebugLog, Microseconds,Ticks
Targets
Mobile
Platforms
iOS
Related
Example Projects
Examples/iOS/Framework/TicksExample
Methods
DebugLog(msg As Text)
Outputs information to the system log. This information is displayed in the Messages pane of the Xojo IDE. When
running on the iOS Simulator, it is also captured in the Simulator console log, which you can access from its Debug>System Log menu item.
Microseconds As Double
The number of Microseconds (one billionth of a second / 1,000,000 of a second) that have passed since the
computer/device was started.
Sample Code
Calculate the number of seconds that have elapsed:
Dim start As Double = Xojo.System.Microseconds
// Do a long-running process here
Dim finished As Double = Xojo.System.Microseconds
Dim elapsedSeconds As Double = (finished - start) / 1000000
Ticks As Double
The number of ticks (60ths of a second) that have passed since the computer/device was started.
Page 488
Xojo
Sample Code
Calculate the number of seconds that have elapsed:
Dim start As Double = Xojo.System.Ticks
// Do a long-running process here
Dim finished As Double = Xojo.System.Ticks
Dim elapsedSeconds As Double = (finished - start) / 1000
Page 489
Xojo
Threading
Contains classes related to threading.
Namespace Summary
Name
Xojo.Threading
Classes
Targets
Mobile
Platforms
iOS
Related
Page 490
Threading
CriticalSection (Class)
Used to protect a single resource in a multithreaded environment.
Class Summary
Name
Xojo.Threading.CriticalSection
Type
Class
Inherits
n/a
Implements
n/a
Methods
Targets
Mobile
Platforms
iOS
Related
Semaphore
Constructors
Properties
Methods
Enter
Attempts to get a lock on the resource managed by the CriticalSection.
Leave
Call Leave when you are finished using the protected resource and you want to give it back to the CriticalSection.
TryEnter As Boolean
Attempts to get a lock on the resource managed by the CriticalSection. TryEnter is similar to Enter but returns True
if it succeeds and the thread has exclusive use of the resource. If it fails, it returns False but does not block
execution of the thread.
Page 491
Threading
IllegalLockingException (Class)
Raised when Semaphores and CriticalSections locks are illegal.
Item Summary
Name
Xojo.Threading.IllegalLockingException
Type
Class
Inherits
LogicException
Implements
n/a
Properties
Methods
CallStack, Stack
Targets
Mobile
Platforms
iOS
Related
Page 492
Threading
Semaphore (Class)
Used to coordinate access to a shared resource.
Class Summary
Name
Xojo.Threading.Semaphore
Type
Class
Inherits
n/a
Implements
n/a
Methods
Targets
Mobile
Platforms
iOS
Related
CriticalSection
Constructors
Constructor(Optional numResources As Integer = 1)
Creates a semaphore with an initial count of resources to track.
Methods
Release
Call Release to give a locked resource back to the Semaphore.
Signal
Call Signal to obtain a lock on a resource, blocking until it does. Once you are done with the shared resource, the
thread should call Release to decrement the internal counter.
TrySignal As Boolean
Determines whether there is a lock available. If there is a lock available, you are granted the lock and TrySignal
returns True. When you are finished with the resource, call Release to give it back to the Semaphore. If the lock is
not available, it does not block. Instead, TrySignal returns False to let you know. Do not attempt to use the resource
after it returns False because you are likely to collide with another thread.
Page 493
Threading
Thread (Class)
Used to run code in the background. Xojo threads are co-operative (not pre-emptive).
Class Summary
Name
Xojo.Threading.Thread
Type
Class
Inherits
n/a
Implements
n/a
Constants
Enumerations
ThreadStates
Events
Run
Properties
Methods
Shared Methods
CurrentThread
Targets
Mobile
Platforms
iOS
Related
Example Projects
Examples/iOS/Framework/AdvancedThreading
Examples/iOS/Framework/ThreadExample
Constants
These constants can be used to set the Priority of the thread:
PriorityHigh
10
PriorityLow
PriorityNormal
Enumerations
ThreadStates
These are the various states of a thread.
Page 494
Threading
Running
Waiting
Suspended
Sleeping
NotRunning
Events
Run
Called when the thread is started by calling the Run method. The code you want to run in the thread should be in
this event handler or should be called from it.
Properties
Priority As Integer
Indicates the priority of the thread.
Notes
The main thread for the app has a priority of 5. You can alter the priority of your own threads to give them more or
less time relative to the main thread. The default is also 5.
The higher the priority value, the more time the thread is allocated, in relation to the main thread. For example, if
you set the Priority = 10, then your thread will run twice as often as the main thread (since 10 is 5*2). A Priority
value that is too high might prevent other threads from running at all.
Sample Code
Thread1.Priority = Thread.PriorityLow
StackSize As UInteger
The size of the thread stack, in bytes.
Threading
Case Thread.Running
status = "Running"
Case Thread.Waiting
status = "Waiting"
Case Thread.Sleeping
status = "Waiting"
Case Thread.Suspended
status = "Suspended"
Case Thread.NotRunning
status = "Not running"
End Select
Methods
Resume
Wakes a thread that is sleeping or suspended so that it may continue running.
Sample Code
LongRunningThread.Resume
Run
Starts the thread and calls its Run event handler.
LongRunningThread.Sleep(300)
LongRunningThread.Sleep(1000, True)
Suspend
Puts the thread in a suspended state where it will no longer run. You can allow the thread to continue by calling
Resume.
Page 496
Threading
Notes
When a thread is suspended, it is not allocated any processing time, regardless of its priority.
Sample Code
LongRunningThread.Suspend
// Other code goes here
LongRunningThread.Resume</code>
Shared Methods
CurrentThread As Thread
The currently running thread.
Sample Code
Thread.CurrentThread.Sleep(500)
Page 497