4. Introduction about iOS
• What is iOS?
iOS (known as iPhone OS prior to June 2010) is Apple’s mobile operating
system.
Originally developed for the iPhone, it has since been extended to support
other Apple devices such as the iPod Touch, iPad and Apple TV.
• iOS & Devices - History & Evolution
iOS version:
Common: iOS 4.0 & later
Newest: iOS 6.0
Our support: iOS 3.0 & later
Device:
iPhone:
1st Generation, 3G, 3GS
4, 4S - Retina Display
iPod Touch: 1st, 2nd, 3rd, 4th (Retina display) Generation
iPad: 1, 2, New iPad (Retina display)
Apple TV
• Types of iOS Applications
Native applications
Web applications
4
15. Objective-C knowledge
Introduction
• Mix C with Smalltalk.
• Message passing (defining method).
• Single inheritance, classes inherit from one and only one superclass.
• Dynamic binding.
• It’s OOP language.
17. Objective-C knowledge
OOP
• Class: defines the grouping of data and code, the “type” of an object.
• Instance: a specific allocation of a class.
• Method: a “function” that an object knows how to perform.
• Instance Variable (or “ivar”): a specific piece of data belonging to an object.
• Encapsulation
• Polymorphism
• Inheritance
Use self to access methods, properties,...
Use super to access methods, properties,... of parent class.
20. Objective-C knowledge
Objective-C syntax : Message syntax
(BOOL) sendMailTo: (NSString*) address withBody: (NSString*) body;
BOOL : Return type
sendMailTo :First part of method name.
withBody :Second part of method name.
sendMailTo: withBody: :full method name or is called selector.
address :first argument.
body :second argument.
sendMailTo: (NSString*) address :First message.
withBody: (NSString*) body :second message.
BOOL isSuccess = [self sendMailTo: @”yp@yp.com” withBody: @”YP”];
21. Objective-C knowledge
Objective-C syntax : Instance method
• Starts with a dash
- (BOOL) sendMailTo: (NSString*) address withBody: (NSString*) body;
•“Normal” methods you are used to
• Can access instance variables inside as if they were locals
• Can send messages to self and super inside
• Example calling syntax:
BOOL isSuccess = [account sendMailTo: @”yp@yp.com” withBody: @”YP”];
22. Objective-C knowledge
Objective-C syntax : Class method
• Starts with a plus. Used for allocation, singletons, utilities
+ (id) alloc;
+ (NSString*) stringWithString: (NSString*) string;
• Can not access instance variables inside
• Example calling syntax (a little different from instance methods)
NSString *string = [NSString stringWithString:@"YP"];
23. Objective-C knowledge
Objective-C syntax : Instance Variables
- By default, instance variables are @protected (only the class and
subclasses can access).
-Can be marked @private (only the class can access) or @public
(anyone can access).
@interface Person: NSObject
{
int age;
@private @private: heart
int heart; @protected: age, hand, leg
@protected @public: face, body
int hand;
int leg;
@public
int face;
int body;
}
24. Objective-C knowledge
Objective-C syntax : Properties
@interface MyObject : NSObject @interface MyObject : NSObject
{ {
@private @private
int age; int age;
} }
- (int) age; @property int age;
- (void)setAge:(int)anInt; @end
@end
- Mark all of your instance variables @private.
- Generate set/get method declarations.
- @property (readonly) int age; // does not declare a setAge method
- Use “dot notation” to access instance variables.
- By default, get/set is thread-safe method.
+ @property (nonatomic) int age; no thread-safe method
25. Objective-C knowledge
Objective-C syntax : Properties
Other typing ways to define a property
@interface MyObject : NSObject @interface MyObject : NSObject
{ {
int iAge;
} }
@property int age; @property int age;
@end @end
But whatever you declare, you must then implement
29. Objective-C knowledge
Objective-C syntax : Properties
Let the compiler help you with implementation using @synthesize!
.h .m
@interface MyObject : NSObject @implementation MyObject
@property int age; @synthesize age;
@end @end
@interface MyObject : NSObject{ @implementation MyObject
int age; @synthesize age;
} @end
@property int age;
@end
@interface MyObject : NSObject{ @implementation MyObject
int iAge; @synthesize age= iAge;
} @end
@property int age;
@end
30. Objective-C knowledge
Objective-C syntax : Properties
If you use @synthesize, you can still implement one or the other
@implementation MyObject
@synthesize age;
- (void)setAge:(int)anInt {
if (anInt > 0) age= anInt;
}
@end
31. Objective-C knowledge
Objective-C syntax : Properties
How to use?
int x = self.age;
int x = [self age];
self.age = x;
[self setAge: x];
And, there’s more to think about when a @property is an object. We
will discuss later.
32. Objective-C knowledge
Objective-C syntax : Dynamic Binding
- Decision about code to run on message send happens at runtime
Not at compile time.
If neither the class of the receiving object nor its superclasses implements
that method: crash!
- It is legal (and sometimes even good code) to “cast” a pointer
But we usually do it only after we’ve used “introspection” to find out more
about the object.
id obj = [[MyObject alloc] init];
NSString *s = (NSString *)obj; // dangerous ... best know what you are
doing
[s setAge: 1]; //warning…crash when runtime
id obj = [[Person alloc] init];
NSString *s = (NSString *)obj; // dangerous ... best know what you are
doing
[s setAge: 1]; //warning…work well.
33. Objective-C knowledge
Objective-C syntax : Introspection
All objects that inherit from NSObject know these methods
- isKindOfClass: returns true whether an object is that kind of class
(inheritance included)
- isMemberOfClass: returns true whether an object is that kind of class (no
inheritance)
Ex:
if ([obj isKindOfClass:[Person class]]) {
int age = [obj age];
}
- respondsToSelector: returns true whether an object responds to a given
method
Ex:
if ([obj respondsToSelector:@selector(setAge:)]) {
[obj setAge: 20];
}
35. Objective-C knowledge
Objective-C syntax : Struct, Enum, BOOL & nil
BOOL
YES or NO instead of true or false
YES = true
NO = false
nil
- An object pointer that does not point to anything.
- Sending messages to nil is ok.
If the method returns a value, it will return zero ( or nil ).
int i = [obj methodWhichReturnsAnInt]; //i = 0 if obj = nil
Person *p = [obj getPerson]; //p = nil if obj = nil
Be careful if the method returns a C struct. Return value is
undefined.
CGPoint p = [obj getLocation]; //p = undefined value if obj = nil
36. Objective-C knowledge
Object Lifecycle & Memory Managenment
How to create object?
It is a two step operation to create an object in Objective-C
Allocating: allocate memory to store the object.
+ alloc: Class method that knows how much memory is needed
Initializing: initialize object state.
- init: Instance method to set initial values, perform other setup
Ex: Person *person = [[Person alloc] init];
How to destroy object?
Dealloc: will free memory. However, never call -dealloc directly
37. Objective-C knowledge
Object Lifecycle & Memory Managenment
How to destroy object?
• Every object has a retaincount
■ Defined on NSObject
■ As long as retaincount is > 0, object is alive and valid
• +alloc and -copy create objects with retaincount == 1
• -retain increments retaincount
• -release decrements retaincount
• When retaincount reaches 0, object is destroyed
• -dealloc method invoked automatically
■ One-way street, once you’re in -dealloc there’s no turning back
Why must call retain/release to increments/decrements retain count
instead of free as C??
38. Objective-C knowledge
Object Lifecycle & Memory Managenment
When do you take ownership?
- You immediately own any object you get by sending a message starting
with new, alloc or copy.
- If you get an object from any other source you do not own it, but you can
take ownership by using retain.
How do you give up ownership when you are done?
Using release.
Importane: do not release to an object you do not own. This is very bad.
39. Objective-C knowledge
Object Lifecycle & Memory Managenment
-(void) doSample{
Person *person = [[Person alloc] init]; //person take ownership
Person *personA = person; //personA do not take ownership
//right methods
[person doSomething];
[personA doSomething];
[personA release]; //personA do not take ownership, so do not release
object
[personA retain]; //personA take ownership on object, retaincount is 2
[personA release]; //right, personA give up ownership, retaincount is 1
[person release]; //right, person give up ownership, retaincount is 0,
object will be dealloc.
}
40. Objective-C knowledge
Object Lifecycle & Memory Managenment
Autorelease & Autorelease pool
Person *person = [Person returnPerson];
person do not take ownership, so it do not call release anyway.
So, how to free memory of object is returned from [Person returnPerson]?
Using “autorelease” to flags an object to be sent release at some point in
the future
41. Objective-C knowledge
Object Lifecycle & Memory Managenment
Autorelease & Autorelease pool
Person *person = [Person returnPerson];
-(Person*) returnPerson{
.Person *person = [[Person alloc] init];
return person;
//wrong, object person will nerver be destroyed.
}
-(Person*) returnPerson{
.Person *person = [[Person alloc] init];
[person release];
return person;
//wrong, object person will be destroyed, so app will crash if any
message is sent to person.
}
-(Person*) returnPerson{
.Person *person = [[Person alloc] init];
[person autorelease];
return person;
//right, object person will have more time to alive.
}
42. Objective-C knowledge
Object Lifecycle & Memory Managenment
Autorelease & Autorelease pool
How does -autorelease work?
• Object is added to current autorelease pool
• Autorelease pools track objects scheduled to be released
■ When the pool itself is released, it sends -release to all its objects
• UIKit automatically wraps a pool around every event dispatch
• If you need to hold onto those objects you need to retain them
44. Objective-C knowledge
Object Lifecycle & Memory Managenment
Property with Memory management
- Understand who owns an object returned from a getter or passed to a setter.
- Getter methods usually return instance variables directly (if return object, it’s
autoreleased object).
- If you use @synthesize to implement setter? Is retain automatically sent?
…Maybe.
There are three options for setters made by @synthesize
@property (retain) Person *person;
- (Person*)setPerson:(Person*)aPerson{
[person release];
person = [aPerson retain];
}
@property (copy) Person *person;
- (Person*)setPerson:(Person*)aPerson{
[person release];
person = [aPerson copy];
}
@property (assign) Person *person;
- (Person*)setPerson:(Person*)aPerson{
person = [aPerson retain];
}
45. Objective-C knowledge
Object Lifecycle & Memory Managenment
Summary, you have 2 ways to get object:
- Using alloc/init ( or new, copy ): will return a object with ownership (retained
object)
NSString *string =[ [NSString alloc] initWithString:@”Hello”];
NSString *stringCopy = [string copy];
- Take object from other soure: will return an object without
ownership(autoreleased object), and use retain if you want to hold on that
object.
NSString *string = [NSString stringWithFormat:@”%@”, @”Hello”];
NSString *string2 = [string stringByAppendingString:@”World”];
NSString *string2 = [[string stringByAppendingString:@”World”] retain];
46. Objective-C knowledge
Foundation Frameworks
NSObject
- Base class for pretty much every object in the iOS SDK
- Implements memory management primitives (and more…)
NSString
- International (any language) strings using Unicode.
- An NSString instance can not be modified! They are immutable.
- Usual usage pattern is to send a message to an NSString and it will
return you a new one.
- Important methods:
- stringByAppendingString:
- isEqualToString:
- componentsSeparatedByString:
- substringFromIndex:
- dataUsingEncoding:
– stringByReplacingOccurrencesOfString:withString:
– rangeOfString:
+ stringWithString:
+ stringWithFormat:
47. Objective-C knowledge
Foundation Frameworks
NSMutableString
- Mutable version of NSString.
- Can do some of the things NSString can do without creating a new one
(i.e. in-place changes).
- Important methods:
NSMutableString *mutString = [[NSMutableString alloc]
initWithString:@“Hello”];
[mutString appendString: @”YP”];
NSDate
- Used to find out the time right now or to store past or future times/dates.
- See also NSCalendar, NSDateFormatter, NSDateComponents.
48. Objective-C knowledge
Foundation Frameworks
NSNumber
- Object wrapper around primitive types like int, float, double, BOOL, etc.
NSNumber *num = [NSNumber numberWithFloat:77.7];
float f = [num floatValue];
- Useful when you want to put these primitive types in a collection (e.g.
NSArray or NSDictionary).
NSValue
- Generic object wrapper for other non-object data types.
- Important methods:
CGPoint point = CGPointMake(25.0, 15.0);
NSValue *val = [NSValue valueWithCGPoint:point];
NSData
- “Bag of bits.”
- Used to save/restore/transmit data throughout the iOS SDK.
49. Objective-C knowledge
Foundation Frameworks
NSArray
- Ordered collection of objects.
- Immutable. That’s right, you cannot add or remove objects to it once it’s
created.
- Important methods:
+ (id)arrayWithObjects:(id)firstObject, ...;
- (int)count;
- (id)objectAtIndex:(int)index;
NSMutableArray
- Mutable version of NSArray.
- Important methods:
- (void)addObject:(id)anObject;
- (void)insertObject:(id)anObject atIndex:(int)index;
- (void)removeObjectAtIndex:(int)index;
50. Objective-C knowledge
Foundation Frameworks
NSDictionary
- Hash table. Look up objects using a key to get a value.
- Immutable. That’s right, you cannot add or remove objects to it
once it’s created.
- Keys are usually NSString objects.
- Important methods:
- (int)count;
- (id)objectForKey:(id)key;
- (NSArray *)allKeys;
- (NSArray *)allValues;
NSMutableDictionary
- Mutable version of NSDictionary.
- Important methods:
- (void)setObject:(id)anObject forKey:(id)key;
- (void)removeObjectForKey:(id)key;
- (void)addEntriesFromDictionary:(NSDictionary*)
otherDictionary;
Cocoa Touch LayerThe Cocoa Touch layer contains the key frameworks for building iOS applications. This layer defines the basic application infrastructure and support for key technologies such as multitasking, touch-based input, push notifications, and many high-level system services.Media LayerThe Media layer contains the graphics, audio, and video technologies geared toward creating the best multimedia experience available on a mobile device.Core Services Layer The Core Services layer contains the fundamental system services that all applications use. Even if you do not use these services directly, many parts of the system are built on top of them.Core OS Layer The Core OS layer contains the low-level features that most other technologies are built upon. Even if you do not use these technologies directly in your applications, they are most likely being used by other frameworks. And in situations where you need to explicitly deal with security or communicating with an external hardware accessory, you do so using the frameworks in this layer. For more infomations about iOS Layers: http://developer.apple.com/library/ios/#documentation/Miscellaneous/Conceptual/iPhoneOSTechOverview/iPhoneOSTechnologies/iPhoneOSTechnologies.html#//apple_ref/doc/uid/TP40007898-CH3-SW1
Cocoa Touch LayerThe Cocoa Touch layer contains the key frameworks for building iOS applications. This layer defines the basic application infrastructure and support for key technologies such as multitasking, touch-based input, push notifications, and many high-level system services.Media LayerThe Media layer contains the graphics, audio, and video technologies geared toward creating the best multimedia experience available on a mobile device.Core Services Layer The Core Services layer contains the fundamental system services that all applications use. Even if you do not use these services directly, many parts of the system are built on top of them.Core OS Layer The Core OS layer contains the low-level features that most other technologies are built upon. Even if you do not use these technologies directly in your applications, they are most likely being used by other frameworks. And in situations where you need to explicitly deal with security or communicating with an external hardware accessory, you do so using the frameworks in this layer. For more infomations about iOS Layers: http://developer.apple.com/library/ios/#documentation/Miscellaneous/Conceptual/iPhoneOSTechOverview/iPhoneOSTechnologies/iPhoneOSTechnologies.html#//apple_ref/doc/uid/TP40007898-CH3-SW1