com
Objective-C
CONTENTS INCLUDE:
n
An Introduction to the Language and Tools
n
The Syntax
n
Memory Management
Tools
n
Debugging
n
XCode Keyboard Shortcuts and more...
By Ben Ellingson and Matthew McCullough
An Introduction to the Language and tools The keyword @interface can distract developers
coming from some languages such as Java,
Objective-C is the primary language used to create Hot suggesting this is a mere contract. However,
applications for Apple’s Mac OS X and iOS (iPhone and iPad) Tip @interface is indeed the keyword for defining the
platforms. Objective-C was created by Brad Cox and Tom Love properties and method signatures of a concrete
in the early 1980s. In 1988, Objective-C was licensed by NeXT, class in Obj-C.
a company founded and helmed by Steve Jobs during his
absence from Apple. Apple acquired NeXT in 1996, bringing Interfaces
Objective-C to the Macintosh platform. Objective-C interfaces are created using the @protocol
declaration. Any class can implement multiple interfaces.
Objective-C is an object oriented superset of ANSI C. Its Interfaces are typically declared in a .h header file and can be
object syntax is derived from Smalltalk. It supports single included via #import statements in the .h header file of other
inheritance, implementation of multiple interfaces via the classes.
@protocol syntax, and the redefinition and augmentation of
www.dzone.com
Inheritance
Class inheritance is specified in the .h interface file with the
syntax: @interface <MyClass> : <ParentClass>. The following
example tells the compiler that the Employee class inherits
from (extends) the Person class.
// Employee.h file
@interface Employee : Person {
}
@end
double Same as float with twice the accuracy or size Using Dot Notation Method Invocation
Objective-C 2.0 added the ability to invoke property accessor
char Store a single character such as the letter ‘a’
methods (getters/setters) using “.” notation.
BOOL Boolean values with the constants YES or NO
// Using dot notation calls the book instance’s setAuthor method
book.author = @”Herman Melville”;
Common Object Data Types // equivalent to
[book setAuthor: @”Herman Melville”];
NSObject Root class of the object hierarchy
Dynamic Typing
Objective-C supports dynamic typing via the id keyword. Properties using @property and @synthesize
Objective-C 2.0 added property declaration syntax in order to
NSString *name1 = @”Bob”;
// name2 is a dynamically typed NSString object reduce verbose coding of getter and setter methods.
id name2 = @”Bob”;
if ([name1 isEqualToString:name2]) {
// do something // use of @property declaration for the title variable is equivalent to
} // declaring a “setTitle” mutator and “title” accessor method.
@interface Book : NSObject {
NSString *title;
Methods }
@property (retain, nonatomic) NSString *title;
Methods are declared in the .h header file and implemented in @end
the .m implementation file. // use the @synthesize declaration in the .m implementation file
// to automatically implement setter and getter methods.
@implementation Book
// Book.h: Declare methods in the header file @synthesize title, author; //Multiple variables
@interface Book : NSObject { @synthesize pages; //Single variable
} @end
- (void) setPages: (int) p;
- (int) pages;
@end
Multiple variables may be included in a single @synthesize
// Book.m: Implement methods in the implementation file
@implementation Book declaration. Alternatively, a class may include multiple
- (void) setPages: (int) p {
pages = p; @synthesize declarations.
}
- (int) pages {
return pages; @property Attributes
}
@end Property attributes specify behaviors of generated getter
and setter methods. Attribute declarations are placed in
Method Declaration Syntax parenthesis () after the @property declaration. The most
Method type return type parameter type common values used are (retain, nonatomic). retain
(class or instance)
method name parameter name indicates that the [retain] method should be called on the
newly assigned value object. See the memory management
- (void) setPages: (int) p; section for further explanation. nonatomic indicates that
the assignment operation does not check for thread access
Method Invocation Syntax protection, which may be necessary in multi-threaded
Method invocations are written using square bracket [] environments. readonly may be specified to indicate the
notation. property’s value can not be set.
method target parameter value
method name Object Initialization
Object instances are created in two steps. First, with a call to
[book setPages: 100]; alloc and second, with a call to init.
Using NSDictionary
#import Statements NSDictionary *di = [NSDictionary dictionaryWithObjectsAndKeys:
@”One”,[NSNumber numberWithInt:1],
#import statements are required to declare the classes and @”Two”,[NSNumber numberWithInt:2],nil];
NSString *one = [di objectForKey: [NSNumber numberWithInt:1]];
frameworks used by your class. #import statements can be NSMutableDictionary *di2 = [[NSMutableDictionary alloc] init];
[di2 setObject:@”One” forKey:[NSNumber numberWithInt:1]];
included at the top of both .h header and .m implementation
files. Memory Management
Objective-C 2.0 includes garbage collection. However,
// import a class
#import “Book.h” garbage collection is not available for iOS apps. iOS apps
// import a framework must manage memory by following a set of object ownership
#import <MapKit/MapKit.h>
rules. Each object has a retain count which indicates the
number of objects with an ownership interest in that object.
Control Flow Ownership of an object is automatically taken when you call a
// basic for loop
for (int x=0; x < 10; x++) {
method beginning with alloc, prefixed with new, or containing
NSLog(@”x is: %d”,x); copy. Ownership is manually expressed by calling the retain
}
method. You relinquish object ownership by calling release or
// for-in loop
NSArray *values = [NSArray arrayWithObjects:@”One”,@”Two”,@”Three”,nil]; autorelease.
objects that have received an autorelease message. When the primary tool in the suite of utilities that ship with the SDK.
autorelease pool is deallocated, it sends a release message to Xcode has a long history but has been given a dramatic set
all objects in the pool. Using an autorelease pool may simplify of feature additions in the modern iPhone and iPad releases,
memory management; however, it is less fine grained and may including detection of common user-coded memory leaks and
allow an application to hold onto more memory than it really quick-fixing of other syntax and coding mistakes.
needs. Be watchful of which types and size of objects you use
Plain text editors and command line Make files can be used to
with autorelease.
produce iOS applications. However, Xcode offers compelling
// call autorelease on allocated instance to add it to the autorelease pool
Book *book = [[[Book alloc] init] autorelease];
features such as syntax highlighting and code completion.
These features make writing Objective-C in the Xcode IDE a
Categories delight and a favorite of developers everywhere.
Categories are a powerful language feature which allows
you to add methods to an existing class without subclassing.
Categories are useful to extend the features of existing classes
and to split the implementation of large classes into several
files. Categories are not subclasses. Generally, do not use
methods in a category to extend existing methods except
when you wish to globally erase and redefine the original
method. Categories can not add instance variables to a class. Once the code is in a valid-syntax state, compile it by choosing
// BookPlusPurchaseInfo.h adds purchase related methods to the Book class Build Build from the menus, or ⌘B. If there are code errors,
#import “Book.h”
@interface Book (PurchaseInfo) they will appear as a yellow or red icon in the lower right corner
- (NSArray *) findRetailers;
@end of the IDE. Clicking on the icon will reveal a panel detailing the
// BookPlusPurchaseInfo.m implements the purchase related methods
#import “BookPlusPurchaseInfo.h” warnings and errors.
@implementation Book (PurchaseInfo)
- (NSArray *) findRetailers {
return [NSArray arrayWithObjects:@”Book World”,nil];
}
@end
Tools
Xcode
The IDE included in the iOS SDK is named Xcode. It is the
Debugging
The Xcode platform provides a robust debugger and
supplementary mechanisms for stepping through code.
Breakpoints are easily set by single clicking in the gutter next
to any line of code. A blue arrow indicates a breakpoint is set
and active.
Simulator
Once a breakpoint is hit, variables can be inspected and The iPhone and iPad Simulator is another distinct application
the stack examined via the key combination ⌘ + ⇧ + Y. The in the iPhone SDK that communicates and integrates with the
bottommost panel is called the console, and is where all Xcode IDE and with Interface Builder. In the Xcode section, we
logging output, written via calls such as NSLog(@“My counter saw how to deploy our application to the Simulator, which both
is: %d”, myIntCount), is routed. installs the application and launches it.
Interface Builder
A tool as powerful as Xcode is Interface Builder. Its name
clearly expresses its use for designing Objective-C NIBs and
XIBs, which are the binary and XML form of user interface
The Simulator ships with a limited number of core applications;
definition files on the Mac, iPhone, and iPad.
namely, the Photos, Settings, Camera, Contacts and
NIBs, though graphically designed, actually instantiate the Safari programs. These are the applications that offer API
objects declared via the tool when called upon via code. connectivity from the source code of your application. For a
Accordingly, it may help to think of IB (as it is known in the broader set of programs and more realistic mobile horsepower
CPUs, testing on an actual iOS device is critical. Commercial Unit Testing and Code Coverage
apps that you’ve purchased from the iTunes App Store cannot Currently, the unit testing tools for Objective-C are less mature
be installed on the Simulator for DRM reasons and the vast than those of other languages. XCode currently includes
difference in CPU architecture of x86 desktops and ARM the OCUnit unit testing framework. OCUnit tests are coded
mobile devices. similarly to those of xUnit tests in languages such as Java. The
Xcode Keyboard Shortcuts Google Toolbox for Mac provides several useful enhancements
Common XCode Shortcuts to OCUnit and is the testing solution currently recommended
⌘ = command ⎇ = alt ▲ = up ⇧ = shift ⏎ = return ^ = control by ThoughtWorks for the iOS platform. Complementing
OCUnit is OCMock, an Objective-C implementation of mock
⎇⌘▲ toggle between .h and .m file
objects. CoverStory can be used in concert with OCUnit and
⌘⇧d quickly open a file via search dialog OCMock to check the code coverage of your tests.
⌘b build
Resources
⌘⏎ build and run
SDK
⌘⇧k clean the build Apple Developer Programs - http://developer.apple.com/
iOS SDK - http://developer.apple.com/iphone/index.action
⌘⇧r go to console view
^1 while in file editor - show / navigate list of recent files Blogs, Videos, Books
WWDC 2010 Session Videos - http://developer.apple.com/videos/wwdc/2010/
^2 while in file editor - show / navigate list of class methods
Objective-C Basics -
⌘y build and debug http://en.wikibooks.org/wiki/Cocoa_Programming/Objective-C_basics
iPhone Development Wiki - http://iphonedevwiki.net/index.php/Main_Page
⎇⌘p debugger continue The Objective-C Programming Language -
http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/ObjectiveC/
⎇ double-click open quick documentation for class at mouse cursor
Bookmarks - http://delicious.com/matthew.mccullough/objectivec
#82
CONTENTS INCLUDE:
■
■
About Cloud Computing
Usage Scenarios Getting Started with
Aldon Cloud#64Computing
■
Underlying Concepts
Cost
by...
■
Upcoming Refcardz
youTechnologies ®
■
Data
t toTier
brough Comply.
borate.
Platform Management and more...
■
Chan
ge. Colla By Daniel Rubio
tion:
dz. com
tegra ternvasll
ABOUT CLOUD COMPUTING one time events. TEN TS
INC ■
HTML LUD E:
us Ind Anti-PPaat
Basics
Automated growthHTM
ref car
nuorn
■
Valid
ation one time events, cloud ML
connected to what is now deemed the ‘cloud’. Having the capability to support
Apache Ant
Usef
Du
ti
■
ul M.
computing platforms alsoulfacilitate
#84
Open the gradual growth curves
n an
Page Source
o
■
s
Vis it
C
faced by web applications. Tools
Core
By Key ■
Elem
Patte
has changed substantially in recent years, especially with Structur
E: al Elem ents
INC LUD gration the entrance of service providers like Amazon, Google and Large scale growth scenarios involvingents
specialized
NTS and mor equipment
rdz !
HTML
CO NTE Microsoft. es e... away by
(e.g. load balancers and clusters) are all but abstracted
Continu at Every e chang
m
About ns to isolat
relying on a cloud computing platform’s technology.
Software i-patter
space
Hadoop
rdz .co
■
n
Re fca
e Work
Build
riptio
and Ant
Desc
These companies have a Privat
are in long deployed
trol repos
itory
webmana applications
ge HTM
L BAS
■
Build
re
Buil Repo
This Refcard active
will introduce are within
to you to cloud riente computing, with an
d units
RATION etc. Some platforms ram support large grapRDBMS deployments.
■
The src
dy Ha
softw
e ine loping and Java s written in hical on of
INTEG attribute
task-o it all
softwar emphasis onDeve es by
Mainl these
ines providers, so youComm can better understand
also rece JavaScri user interfac web develop and the rris
Vis it
Spring Security
codel chang desc
INUOU ding Task Level as the
e code
w ww.dzone.com
Label
Build
manu
al
d tool
depe deplo t need but as if
eve , a ) stalle the same nmen for stan overlap uen
(i.e. , inef Build t, use target enviro Amazon EC2: Industry standard it has
software and uagvirtualization ine. HTM , so <a>< tly are) nest
with terns problem ce pre-in whether dards
ated b></
ory. ns (i.e. Autom Redu ymen
has bec become e with a> is
via pat ticular d deploEAR) in each very little L
Subversion
reposit -patter s that Pay only cieswhat you consume
tagge or Amazon’s cloud
the curr you cho platform
computing isome
heavily based moron fine. b></ ed insid
lained ) and anti the par solution duce nden For each (e.g. WAR es t
ent stan ose to writ more e imp a></ e
not lega each othe
x” b> is
be exp text to “fi are al Depeapplication deployment
Web ge until t a
librarifew years agonmen
t enviro was similar that will softwaredard
industry standard and virtualization app
e HTM technology.
orta nt,
tterns to pro Minim packa nden
Mo re
CI can ticular con used can rity all depe all targe
s will L or XHT arent. Reg the HTM l, but r. Tags
etimes Anti-pa they
tend
es, but to most phone services:
y Integ alizeplans with le that
late fialloted resources, ts with an and XHT simplify all help ML, und ardless
L VS
XHTM <a><
in a par hes som
Centr
end,
Binar
pro cess. the practic enti ng incurred costgeme
nt
whether e a single
such
temp
resources on
were consumed
t enviro
nmen
orthenot. Virtualization MLaare your
othe
you prov
erst of L
b></
in muchallows physical piece of hardware to
ide be HTM
rily bad
Mana based
approac ed with the cial, but, implem anding
Creat targe es to actually r web
nden
cy rties are nt
of the a solid L has
into differe coding.resources
necessa pared to
chang
efi Depe prope itting utilized by multiple operating
function systems.simplerThis allows foundati job adm been arou
associat to be ben
er
Ge t
te builds commo
are not Fortuna
late Verifi e comm than on
n com Cloud computing asRun it’sremo
known etoday has changed this.
befor alitytohas irably, nd for
They they
etc.
Temp Build (e.g. bandwidth, n memory, CPU) be allocated exclusively to tely exp that som
lts whe
ually,
appear effects. Privat y, contin Every elem mov used
to be, HTML
ecte job e time
ed resu The various resourcesPerfo rm a
consumed by webperio applications
dicall (e.g. nt team
pag
individual operating entsinstances. ed to CSS
system Brow d. Earl
y HTM has expand . Whi
gration
opme because
adverse unintend d Builds sitory Build r to devel common e (HTML . ser ed far le it has don
ous Inte web dev manufacture L had very
Stage Repo
e bandwidth, memory, CPU) areIntegtallied
ration on a per-unit CI serve basis or XHT
produc tinu e Build rm an from
extensio .) All are more e its
e.com
DZone, Inc.
Cloud Computing
the
s on
expand
ISBN-13: 978-1-934238-75-2
140 Preston Executive Dr. ISBN-10: 1-934238-75-9
Suite 100
50795
Cary, NC 27513