2. Introduction
• Runtime - Obj-C performs many tasks at runtime (object
allocation, method invocation)
→ require also a runtime environment ←
• Objects - An object associate data with operations that can
use or affect the data.
• id - General data type for any kind of object
• Object Messages - To get an object to do something, you
send it a message telling it to apply a method. Messages are
enclosed in brackets (e.g. [receiver message]; ). Methods in
message are called selectors.
• Classes - In Obj-C you define objects by defining their
class. The class definition is a prototype for a kind of object.
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
3. Memory management
• Reference counting (retain, release)
• Manually managed or through the auto-
release pool
• Garbage collector (not used in iPhone
programming, but in Cocoa).
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
7. An Example
The difference between self and super becomes clear in a hierarchy of three
Messages to self and super
that we create an object belonging to a class called Low. Low’s superclass is M
All three classes define a method called negotiate, which they use for a var
Mid defines an ambitious method called makeLastingPeace, which also has n
This is illustrated in Figure 2-2:
Figure 2-2 High, Mid, Low
- reposition superclass
{ High – negotiate
...
[self negotiate];
...
superclass
}
Mid – negotiate
– makeLastingPeace
- reposition
{ superclass
...
Low – negotiate
[super negotiate];
...
}
We now send a message to our Low object to perform the makeLastingPea
makeLastingPeace, in turn, sends a negotiate message to the same Low
object self,
www.MitAPP.com http://paoloquadrani.blogspot.com/
- makeLastingPeace http://twitter.com/MitAPP
{
8. Class Initialization
• By convention initializer method begins with
init e.g. initWithColor: ...
• The return type should be id.
• You should assign self to the value returned by the
initializer.
• Setting value of member variables, use direct
assignment, not accessors.
• If initializer fails, return nil, otherwise return self.
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
9. Initializer Example
- (id)init {
// Assign self to value returned by super's designated initializer
// Designated initializer for NSObject is init
if (self = [super init]) {
creationDate = [[NSDate alloc] init];
}
return self;
}
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
10. Combining Allocation
and Initialization
• Some classes combine allocation and
initialization returning a new, initialized
instance of the class. Convenience
constructors
• Examples:+ (id)stringWithFormat:(NSString *)format
+ (id)arrayWithObject:(id)anObject;
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
11. Protocols
• Protocols declare methods that can be
implemented in any class.
Useful in:
• Declare methods that others are expected
to implement
• Declare the interface to an object
• Capture similarity among classes that are
not hierarchically related
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
14. Declared Properties
• Declared properties provides a way to
declare and implement an object’s accessor
methods
• The compiler can synthesize accessor
methods for you
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
16. Property Attributes
@property(attributes) type name;
• Writability
• readwrite (the default)
• readonly
• Setter Semantics
• assign (the default) - Used for scalar types such as NSInteger
• retain - Used for objects on assignment. The previous value is sent a
release.
• copy - A copy of the object is used for the assignment. The previous
value is sent a release.
• Atomicity
• nonatomic (by default) - The synthesized method provide robust access
in a multi-threading environment.
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
18. Property
Implementation
• Provide one of these Implementation
Directives inside the @implementation block:
• @synthesize
• @dynamic
• Direct implement setter and getter
methods
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
22. Selectors
• In Objective-C selector has two meanings:
• It refers to a name of a method
• It refers to a unique identifier that
replace the name when the code is
compiled
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
23. SEL and @selector
• Selectors are assigned to special type SEL
• Valid selectors are never 0
• @selector() directive lets you refer to
compiled selectors
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
24. Examples of selectors
SEL setWidthHeight;
setWidthHeight = @selector(setWidth:height:);
setWidthHeight = NSSelectorFromString(aBuffer);
NSString *method;
method = NSStringFromSelector(setWidthHeight);
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
25. Using a selector
• NSObject protocol defines three methods
that use selectors:
• performSelector:
• performSelector:withObject:
• performSelector:withObject:withObject:
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
26. Example
[friend performSelector:@selector(gossipAbout:)
withObject:aNeighbor];
is equivalent to:
[friend gossipAbout:aNeighbor];
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
27. Varying message at
runtime
• performSelector: and the other two allows
you to varying messages at runtime. Using
variables you can:
id helper = getTheReceiver();
SEL request = getTheSelector();
[helper performSelector:request];
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
28. Avoiding Messaging
Errors
• Selectors send a message to an object at
runtime
• An object that doesn’t implement a method
generate an error if someone try to send it
a request to execute a non existent
method
• respondsToSelector: is used to check the
existence of a method
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
29. Example
if ( [anObject respondsToSelector:@selector(setOrigin::)] )
[anObject setOrigin:0.0 :0.0];
else
fprintf(stderr, "%s can’t be placedn",
[NSStringFromClass([anObject class]) UTF8String]);
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
30. Using C++ with
Objective-C
• C++ can be used inside Objective-C code
• This hybrid is called Objective-C++
• Inheritance of Objective-C classes from C+
+ classes (and vice-versa) are not permitted
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
31. Example of mix
#import <Foundation/Foundation.h>
class Hello {
private:
id greeting_text; // holds an NSString
public:
Hello() {
greeting_text = @"Hello, world!";
}
Hello(const char* initial_greeting_text) {
greeting_text = [[NSString alloc]
initWithUTF8String:initial_greeting_text];
}
void say_hello() {
printf("%sn", [greeting_text UTF8String]);
}
};
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
34. iPhone
Main UI arguments
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
35. Arguments
• Dealing with data: User Defaults, SQLite
• Touch events and Multi-Touch
• Address book
• Image Picker
• Localization
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
36. Arguments
• Dealing with data: User Defaults, SQLite
• Touch events and Multi-Touch
• Address book
• Image Picker
• Localization
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
37. Dealing with data
• Property Lists
• iPhone File System
• Archiving Objects
• SQLite
• Web Services
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
38. Dealing with data
• Property Lists
• iPhone File System
• Archiving Objects
• SQLite
• Web Services
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
39. Property Lists
• Convenient way to store small amount of data
• Array, dictionaries, strings, numbers
• XML or binary format
• NOT use it if
• data is more then few KB, loading is all or nothing
• Complex object graphs
• Custom object types
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
41. Dealing with data
• Property Lists
• iPhone File System
• Archiving Objects
• SQLite
• Web Services
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
42. iPhone File System
• Each Application
• Has its own sand-box
• Has its own set of directories
• Can read-write within its own directory
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
44. Include Writable Files in
Your Application
• Build it as part of your app bundle
• You can’t modify the content of your app
bundle, so:
• On first launch, copy the writable to
your Documents directory
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
45. Dealing with data
• Property Lists
• iPhone File System
• Archiving Objects
• SQLite
• Web Services
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
46. Archiving Objects
• Used for serialization of custom object types
• Used by Interface Builder for NIBs
• Archivable objects has to conform to the
<NSCoding> protocol
• Implement the two protocol methods:
- (void)encodeWithCoder:(NSCoder *)coder;
- (void)initWithCoder:(NSCoder *)coder;
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
47. Example Coder
// Encode an object for an archive
- (void)encodeWithCoder:(NSCoder *)coder {
[super encodeWithCoder:coder];
[coder encodeObject: name forKey:@”Name”];
[coder encodeIntger: numberOfSides forKey:@”Sides”];
}
// Decode an object from an archive
- (id)initWithCoder: (NSCoder *)coder {
self = [super initWithCoder: coder];
name = [[coder decodeObjectForKey: @”Name”] retain];
numberOfSides = [coder decodeIntegerForKey: @”Side”];
}
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
48. Dealing with data
• Property Lists
• iPhone File System
• Archiving Objects
• SQLite
• Web Services
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
49. SQLite
• Complete SQL database in an ordinary file
• Simple, compact, fast, reliable
• No server is needed
• Great for embedded devices
• Included on the iPhone platform
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
50. When not to use
SQLite
• Multi-gigabyte database
• High concurrency (multiple writers)
• Client-server application
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
51. SQLite C API basic
• Open the DB
int sqlite3_open(const char *filename, sqlite3 **db);
• Execute a SQL statement
int sqlite3_exec(sqlite3 *db, const char *sql,
int (*callback)(void*, int, char **, char **),
void *context, char **error);
// Your callback
int callback(void *context, int count,
char **values, char **columns);
• Close the DB
int sqlite3_close(sqlite3 *db);
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
52. SQLITE 3
• DEMO (10-15’):
Real application with Sqlite3
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
53. Core Data
• Object graph management and persistence
framework
• Make it easy to save and load model objects
• Higher-level abstraction then SQLite or
property lists
• Available on the MAC OSX desktop
• Available only on iPhone OS 3.x and later
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
54. Dealing with data
• Property Lists
• iPhone File System
• Archiving Objects
• SQLite
• Web Services
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
55. Integrating with Web Services
• Many are exposed via RESTful interface with XML
or JSON
• Options for Parsing XML are:
• libxml2 - C library
• NSXMLParser - simpler but less powerful
than the previous one
• JavaScript Object Notation
• More lightweight then XML
• Looks like a property list
• open source json-framework wrapper for Obj-C
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
56. JSON & XML PARSER
• DEMO (10-15’):
Real application with Json (Flickr API) & XML parser
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
57. Arguments
• Dealing with data: User Defaults, SQLite
• Touch events and Multi-Touch
• Address book
• Image Picker
• Localization
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
58. Single Touch Sequence
• UITouch represent a single finger
• There are three phases in touch:
• touchBegan
• touchMoved
• touchEnded
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
59. UIEvent: Collection of UITouch
• UIEvent is a container for UITouch
• Can give information on:
• all touches
• all touches in a window
• all touches in a view
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
60. Receiving touches
• UIResponder is the base class of touches
‘listener’
• Methods called are:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
61. Multiple Touches
• Same events are generated then Single
Touch
• You must enable it to make it works
BOOL multipleTouchEnabled;
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
62. Arguments
• Dealing with data: User Defaults, SQLite
• Touch events and Multi-Touch
• Address book
• Image Picker
• Localization
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
63. Address Book basics
• Create a person and set
some properties
• Create a
ABPersonViewController
• Push the view controller
onto the navigation stack
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
64. Get people from the
Address Book
ABAddressBookRef ab = ABAddressBookCreate();
CFArrayRef people = ABAddressBookCopyPeopleWithName(ab, name);
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
65. Person
• ABRecordRef
• A collection of properties
• First and last name
• Image
• Phone numbers, emails, etc...
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
66. Properties
• Properties can have different types
• String
• Date
• Dictionary, Data...
• Some properties may have multiple values
• Telephone: home, work, mobile...
• Person properties in ABPerson.h
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
67. Retrieve and Set Single
Value Properties
// Retrieve the first name of a person
CFStringRef first = ABRecordCopyValue(person, kABPersonFirstNameProperty);
// Update or Set the birthday of a person
CFDateRef date = CFDateCreate( ... );
ABRecordSetValue(person, kABPersonBirthdayProperty, date, &error);
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
68. Retrieve Multi Value
Properties (ABMultiValueRef)
// Getting multiplicity
CFIndex count = ABMultiValueGetCount(multiValue);
// and getting the value
CFTypeRef value = ABMultiValueCopyValueAtIndex(mv, index);
// and getting the lable
CFStringRef label = ABMultiValueCopyLabelAtIndex(mv, index);
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
69. Update Multi Value
Properties
// Get the multi value reference
ABMultiValueRef urls = ABRecordCopyValue(person, kABPersonURLProperty);
// Create the multi value mutable copy
ABMutableMultiValueRef urlCopy = ABMultiValueCreateMutableCopy(urls);
// Add the new value
ABMultiValueAddValueAndLabel(urlCopy, “the url”, “url label”, NULL);
ABRecordSetValue(person, urlCopy, kABPersonURLProperty);
// Save the Address Book
ABAddressBookSave(ab, &error);
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
71. Arguments
• Dealing with data: User Defaults, SQLite
• Touch events and Multi-Touch
• Address book
• Image Picker
• Localization
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
72. Image Picker Interface
• UIImagePickerController class
• Handles all user and device interactions
• Built on top of UIViewController
• UIImagePickerControllerDelegate protocol
• Implemented by your delegate object
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
73. Displaying the Image
Picker
• Check the source available
• Assign a delegate object
• Present the controller modality
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
78. Manipulating the
returned Image
• If allowsImageEditing property is YES:
• User allowed to crop the returned image
• Image metadata returned in “info”
NSDictionary
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
79. Arguments
• Dealing with data: User Defaults, SQLite
• Touch events and Multi-Touch
• Address book
• Image Picker
• Localization
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
80. Localizing an
Application
• Multiple Languages and locales in a single
built application
• Keep localized resources separate from
everything else
• Strings
• Images
• User Interfaces
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
82. Localized Strings
• For user-visible strings in application code
• Map from an non localized key to a
localized string
• Stored in .strings files
• Key-value pairs
• Use UTF-16 for encoding
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
83. Example of .strings
• en.lproj/Greetings.strings
“Hello” = “Hello”;
“Welcome to %@” = “Welcome to%@”;
• it.lproj/Greetings.strings
“Hello” = “Ciao”;
“Welcome to %@” = “Benvenuto a %@”;
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
84. Accessing localized
strings
// By default, uses Localizable.strings
NSLocalizedString(@”Hello”, @”Greeting for welcome screen”);
// Specify a table, uses Greetings.strings
NSLocalizedStringFromTable(@”Hello”, @”Greetings”,
@”Greeting for welcome screen”);
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
85. genstrings
• Tool to scan your code and produce
a .strings file
• Inserts comments found in code as clues to
localizer
• Run the tool over your *.m files
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP
86. Localizing XIBs
• Xcode allows you to
generate localized
version of your User
Interface
www.MitAPP.com http://paoloquadrani.blogspot.com/ http://twitter.com/MitAPP