Introduc) On To Objec) Ve - C: Jussi Pohjolainen Tampere University of Applied Sciences
Introduc) On To Objec) Ve - C: Jussi Pohjolainen Tampere University of Applied Sciences
to
Objec)ve-C
Jussi
Pohjolainen
Tampere
University
of
Applied
Sciences
QUICKSTART
Background
Objec)ve-C
is
layered
on
top
of
the
C
language
Based
on
SmallTalk-80
Designed
in
early
1980s
NeXT SoLware licensed Objec)ve-C in 1988 Apple Computer acquired NeXT in 1996 Today: na)ve language for developing Mac OS X - and iPhone - apps
Simple
makele
MyPoint : MyPoint.m main.m clang -fno-objc-arc -framework foundation MyPoint.m main.m -o MyPoint run : ./MyPoint clean : rm MyPoint
Instan)a)ng
an
Object
// Declare a pointer to the object MyPoint* point; // Allocate memory for the object point = [MyPoint alloc]; // Initialize the object point = [point init];
Messages
(Methods)
- (void) setX: (int) n;!
return type
selector name
argument type
argument name
EXERCISES
In Java, garbage collector takes care of the release. Separate thread looking for objects that can be released In Obj-C and C/C++, programmer is responsible about the release.
About
Pointers
int
a
=
5;
Holds
one
integer
value
The
integer
is
stored
in
some
memory
address
Where?
You
can
get
the
memory
address
by
using
&
in
front
of
the
variable:
&a
Pointers
Pointer
is
a
variable
that
stores
memory
address
int
a;
holds
integer
variable
int*
b;
holds
memory
address
that
points
to
integer
value
int*
b
=
&a;
Now
b
has
the
memory
address
of
a
// prints 5 NSLog(@"%i", a); // prints something like 0x7fff5fbff9cc NSLog(@"%p", &a); // prints something like 0x7fff5fbff9cc NSLog(@"%p", b); // prints 5 NSLog(@"%i", *b); return 0; }
Memory
Areas
Memory
can
be
divided
into
three
categories
1. Global
or
sta)c
2. Stack
3. Heap
Sta)c
When
something
is
in
sta)c
memory,
it's
there
all
the
)me
when
app
is
running
So
when
star)ng
the
app,
the
memory
is
allocated
an
when
the
app
closes,
the
memory
is
deallocated
The
variable
is
stored
in
the
same
memory
address
all
the
)me.
Stack
-
Memory
Stack
memoryarea
is
usually
small
If
you
put
too
much
"stu"
into
stack,
you
might
get
stack
overow
Local
variables
are
stored
in
stack!
Variables
are
released
when
out
of
scope
Heap
-
Memory
Heap
memory
is
the
large
memory
area
where
almost
all
of
the
objects
go.
Programmer
is
responsible
for
releasing
the
objects!
Crea)ng
a
Object
The
crea)on
of
an
object
is
done
in
two
parts
1)
Alloca)ng
memory
MyPoint* point = [MyPoint alloc];
Combined
MyPoint* point = [[MyPoint alloc] init];
MyPoint* point = [MyPoint new];
Two
things!
MyPoint* p; p = [MyPoint alloc];
Problem?
#import "MyPoint.h" int main(int argc, char *argv[]) { if(YES) { MyPoint* point = [MyPoint alloc]; } [point release]; return 0; }
Problem?
#import "MyPoint.h" int main(int argc, char *argv[]) { MyPoint* point = [MyPoint alloc]; point = [MyPoint alloc]; [point release]; return 0; }
init-method?
init-method
is
implemented
in
NSObject You
can
however
implement
your
own
init- method
- (id) initWithName: (NSString*) aName { if(self = [super init]) { name = aName; } return self; }
Other
init-methods
Like
in
Java
and
C++,
one
can
have
mul)ple
constructors
In
Obj-C,
one
can
have
mul)ple
init-methods
- (id) init - (id) initWithX: (int) aX; - (id) initWithX: (int) aX andY: (int) aY
dealloc
You
can
implement
a
dealloc
method
(void) dealloc { // Some code [super dealloc]; }
Since reference count is 0, dealloca)on occurs. This means, that the Cat does not have a name anymore.
Since reference count is 1, dealloca)on does not occur and the Cat s)ll has it's name.
Copying
a
Object
- (void)setName:(NSString *)theName } [name release]; name = [theName copy]; }
Autorelease
Pool
Every
Founda)on
program
must
set
up
autorelease
pool
for
the
Founda)on
objects
Pool
keeps
track
of
your
objects
for
later
release
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; ... [pool drain];
Method
Names
If
method
name
includes
alloc
or
copy,
it
returns
a
object
that
must
be
released
// Must be released NSObject* object = [[NSObject alloc] init]; // Must be released NSObject* copy = [object copy]; // Do not have to release NSMutableString* string = [NSMutableString string];
Problem
// Programmer A code [[someObject giveCat] eat];
// Programmer B code - (Cat*) giveCat { // Must be released! Cat* myCat = [[Cat alloc] init]; // But where? Should the programmer who calls this method be // responsible for deallocation of the Cat? How does the programmer // know this? return myCat; } ..
Solu)on
// Programmer A code [[someObject giveCat] eat];
// Programmer B code - (Cat*) giveCat { // Must be released! Cat* myCat = [[Cat alloc] init]; // But where? When autopool is drained! [myCat autorelease]; return myCat; }
Delayed
Release
Autorelease
means
"send
release
message
later".
Release
message
is
sent
when
Autorelease
Pool
is
released
Autorelease
Pool
is
created
and
released
in
UIKit
programs
automa=cally!
Pool
is
created
at
the
beginning
of
an
event
cycle
Pool
is
released
at
the
end
of
an
event
cycle
Autorelease
Pools
Event
loop
Pool
released
Pool created App Loaded Wait for Event Handle event Exit app
Rules
If
method
name
contains
"alloc",
"new"
or
"copy",
you
must
remember
to
use
release or
autorelease
Example:
alloc, newObject, mutableCopy
If you retain something, you must use release or autorelease Instance Variables: retain or copy autorelease means "send release later"
Cat.h
#import <Foundation/Foundation.h> @interface Cat : NSObject { @private NSString* name; } (id) (void) (NSString*) (void) initWithName: (NSString*) aName; setName: (NSString*) aName; getName; dealloc;
@end
Cat.m
#import "Cat.h" @implementation Cat - (id) initWithName: (NSString*) aName { if(self = [super init]) { [self setName: aName]; } return self; } - (NSString*) getName { return name; } - (void) setName: (NSString*) aName { if(aName != name) { [name release]; name = aName; [name retain]; } }
main.m
#import "Cat.h" int main(int argc, char *argv[]) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // Create the string NSString* catName = [[NSString alloc] initWithString: @"Jack"]; // Create cat with the string Cat* cat = [[Cat alloc] initWithName: catName]; // Just testing. This does not deallocate catName! [catName release]; // Get the name NSString* name = [cat getName]; // Print the name NSLog(name); // Release name and cat [cat release]; [pool drain]; return 0; }
ARC?
ARC
(Automa=c
Reference
Coun=ng)
Compiler
does
automa/c
reference
coun/ng
by
examining
the
source
code
and
then
add
the
retain
and
release
messages
to
objects
Not garbage collec)on, no background process of dealloca)on of objects! Inserts retain and release statements based on some xed rules OS X 10.7 and iOS 5 for all features
Guidelines
Dont
call!
retain, release, retainCount, autorelease or dealloc
makele
MyPoint : Car.m Motor.m main.m clang -fobjc-arc -framework foundation Car.m Motor.m main.m -o App run : ./App clean : rm App
main.m
motor.h
motor.m
car.h
car.m
PROPERTIES
Autosynthesize
Autosynthesize
readwrite
Indicates
that
the
property
is
read/write.
Default
readonly
Only
read
Generates
only
geoer
method
Seoer
Seman)cs
assign weak
Non-owning
rela)onship
with
an
object
If
object
is
deallocated,
the
property
is
set
to
nil
Simple
seoer.
Default.
strong
Owning
rela)onship
with
an
object
copy
Species
that
a
copy
of
the
object
should
be
used
for
assignment
Atomicity
nonatomic
Species
that
accessor
are
non-atomic.
Car.h
Motor.h
Main.m
Change! Car.h
STRINGS
About
Strings
C
String
char * // Array of characters
NSString
Object,
that
holds
array
of
Unicode
characters
Is
immutable,
contents
cannot
be
changed
aLerwards!
NSMutableString
String
that
can
be
modied
aLerwards
Crea)ng
Strings
// Simple way NSString *temp1 = @"Hello World!"; // Appending, notice that this produces new string NSString *beginning = @"beginning"; NSString *alphaAndOmega = [beginning stringByAppendingString:@" and end"];
Formapng
Formapng
NSString *string1 = [NSString stringWithFormat:@"A string: %@, a float: %1.2f",@"string", 31415.9265]; // string1 is "A string: string, a float: 31415.93"
Format
Speciers?
http://developer.apple.com/iphone/ library/documentation/Cocoa/Conceptual/ Strings/Articles/formatSpecifiers.html#// apple_ref/doc/uid/TP40004265-SW1
NSString
methods
See:
http://developer.apple.com/documentation/ Cocoa/Reference/Foundation/Classes/ NSString_Class/Reference/NSString.html
NSMutableString methods
NSMutableString inherites
NSString With
NSMutableString you
can
modify
the
string
with
these
methods
appendFormat: appendString: deleteCharactersInRange: insertString:atIndex: replaceCharactersInRange:withString: replaceOccurrencesOfString:withString:options:range: setString:
PROTOCOLS
Protocols?
Compared
to
Java,
protocols
are
interfaces
You
dene
methods
that
some
object
must
implement
Using
Protocols
// MyProtocolName.h // Notice that the protocol inherites NSObject // protocol! @protocol MyProtocolName <NSObject> //Method declarations go here @end // MyObject @interface Class: NSObject <MyProtocolName>
Protocol
as
Variable
In
Java
MyInterface object = new MyObject(); id<MyProtocolName> object = [[MyObject alloc] init];
FOUNDATION CLASSES
NSObject
NSObject
is
the
root
class
of
Most
Obj-C
classes
Crea)ng,
copying,
dealloca)ng
objects
Collec)ons
Array:
Ordered
Collec/ons
Dic)onary:
Collec/ons
of
Keys
and
Values
Set:
Unordered
Collec/ons
of
Objects
Counted
Sets:
Unordered
Collec/on
of
Indis/nct
Objects
Enumera)on:
Traversing
a
Collec/on's
Elements
Mutable
and
immutable
versions!
Other
Classes
NSNumber,
wrapper
for
standard
number
types
NSDate,
NSCalendarDate