62
Objective-C 7/20/2009 [email protected]

Objective C for iPhone Development

Embed Size (px)

DESCRIPTION

This presentation provides basics of obejctive C language used for iPhone development. Covers basics of foundation framework, Memory Management, Classes, protocols, messaging,Interface, Categories, properties , fast enumeration and object allocation.

Citation preview

Page 1: Objective C for iPhone Development

Objective-C

7/20/2009 [email protected]

Page 2: Objective C for iPhone Development

Overview

Objective-C is an object oriented language.follows ANSI C style coding with methods from SmalltalkRelies mostly on libraries written by othersFlexible almost everything is done at runtime.

Dynamic BindingDynamic TypingDynamic Linking

7/20/2009 [email protected]

Page 3: Objective C for iPhone Development

id - The generic object type that canhold a pointer to any type of object. This uses dynamic typing

Isa - The isa variable is used to identify the class to which an object belongs at runtime.nil – represents an invalid object.self - in a method self refers to the receiver of the messageClass – when used as a message returns the class object

Some Special Keywords

7/20/2009 [email protected]

Page 4: Objective C for iPhone Development

Object Messaging

[receiver message]eg. [myRectangle display];[myRectangle setOriginX: 30.0 y: 50.0];

Sending Messages to nilPerson *motherInLaw = [[aPerson spouse] mother];

7/20/2009 [email protected]

Page 5: Objective C for iPhone Development

Polymorphism & Dynamic Binding

The selection of a method implementation happens at runtime. When a message is sent, a runtime messaging routine looks at the receiver and at the method named in the message. It locates the receiver’s implementation of a method matching the name, “calls” the method,

[email protected]/20/2009

Page 6: Objective C for iPhone Development

Interview Buzz iPhone App

7/20/2009 [email protected]

Page 7: Objective C for iPhone Development

Dot Syntax

Compact and convenientInvoke accessor methods .Doesn't access instance variable directly

myInstance.value = 10;Is same as[myInstance setValue:10];

7/20/2009 [email protected]

Page 8: Objective C for iPhone Development

Dot Syntax

myInstance.value is same as[myInstance value];

compiler can signal an error when it detects a write to a read-only property using dot syntax

7/20/2009 [email protected]

Page 9: Objective C for iPhone Development

Key-value coding (KVC)

identify properties with string-based keys

valueForKey:setValue: forKey:

7/20/2009 [email protected]

Page 10: Objective C for iPhone Development

Key-value coding (KVC)

@property NSString *stringProperty;

NSString *string = [objectInstance valueForKey:@"stringProperty"];

[objectInstance setValue:[NSString @”constantString”] forKey:@“stringProperty"];

7/20/2009 [email protected]

Page 11: Objective C for iPhone Development

Dynamic Language

Almost everything is done at runtimeUses dynamic typing, linking, and bindingThis allows for greater flexibilityMinimizes RAM and CPU usage

7/20/2009 [email protected]

Page 12: Objective C for iPhone Development

To Import or Include?

C/C++’s #include will insert head.h into the code even if its been added before.Obj-C’s #import checks if head.h has been imported beforehand.

#import head.h

7/20/2009 [email protected]

Page 13: Objective C for iPhone Development

Messages

Almost every object manipulation is done by sending objects a messageTwo words within a set of brackets, the object identifier and the message to send.

Because of dynamic binding, the message and receiver are joined at runtime

[Identifier message ]

7/20/2009 [email protected]

Page 14: Objective C for iPhone Development

Interview Buzz On App Store

7/20/2009 [email protected]

Free promotinal codes for App : WXPN3FWTRP3X andR3F73AA4RP4P .can be used only once on US store for iPhone 3.0Please give +ve Feedback in review section

Page 15: Objective C for iPhone Development

Type Instrospection

[anObject isMemberOfClass:someClass]

[anObject isKindOfClass:someClass]

receiver is an instance of a particular class

Checks whether receiver inherits from or is an instance of a particular class:

7/20/2009 [email protected]

Page 16: Objective C for iPhone Development

Memory Allocation

Objects are created dynamically through the keyword, “alloc”Objects are dynamically deallocated using the words “release” and “autorelease”autorelease dealocates the object once it goes out of scope.NOTE: None of these words are built-in

7/20/2009 [email protected]

Page 17: Objective C for iPhone Development

Ownership

Objects are initially owned by the id that created them.Like C++ pointers, multiple IDs can use the same object.However, like in C++ if one ID releases the object, then any remaining pointers will be referencing invalid memory.A method like “retain” can allow the object to stay if one ID releases it.

7/20/2009 [email protected]

Page 18: Objective C for iPhone Development

Prototyping functions

When declaring or implementing functions for a class, they must begin with a + or -+ indicates a “class method” that can only be used by the class itself. In other words, they’re for private functions.- indicates “instance methods” to be used by the client program (public functions).

7/20/2009 [email protected]

Page 19: Objective C for iPhone Development

Class Declaration (Interface)

#import <Cocoa/Cocoa.h>@interface Node : NSObject {Node *link;int contents; }+(id)new;-(void)setContent:(int)number;-(void)setLink:(Node*)next;-(int)getContent;-(Node*)getLink;@end

node.h

7/20/2009 [email protected]

Page 20: Objective C for iPhone Development

Class Definition (Implementation)#import "node.h”@implementation Node+(id)new{ return [Node alloc];}-(void)setContent:(int)number{contents = number;}-(void)setLink:(Node*)next {[link autorelease];link = [next retain];}-(int)getContent{return contents;}-(Node*)getLink{return link;}@end

node.m

7/20/2009 [email protected]

Page 21: Objective C for iPhone Development

Class Object

One per classResponsible for producing instancesClass methods are for class objectAll class objects are of type class.Class name stands for the class object only as the receiver in a message expression

7/20/2009 [email protected]

Page 22: Objective C for iPhone Development

Class Object

int versionNumber = [Rectangle version];Retrieving class object id

id aClass = [anObject class];id rectClass = [Rectangle class];

class objects can also be more specifically typed to the Class data type:

Class aClass = [anObject class];7/20/2009 [email protected]

Page 23: Objective C for iPhone Development

Allocation and Intitalization

myRectangle = [Rectangle alloc];allocates memory for the new object’s instance variables and initializes them all to 0. isa connects new instance to its class.

myRectangle = [[Rectangle alloc] init];Initialize the newly allocated memory to appropriate values

7/20/2009 [email protected]

Page 24: Objective C for iPhone Development

Returned Object

Init method can return object other than newly allocated receiver or even return nil.

Use the value returned by the initialization method, not just that returned by alloc or allocWithZone:

7/20/2009 [email protected]

Page 25: Objective C for iPhone Development

Brief About Interview Buzz

7/20/2009 [email protected]

Interview Buzz is an app with complete Q&A for Behavioral or HR interviews. No need to buy an expensive book or search through 100’s of websites. This app covers almost all questions that you might expect on an HR, Behavioral or round one of interviews. It includes Do’s, Dont’s and attire tips for the interview.

Page 26: Objective C for iPhone Development

Returned Object

id anObject = [SomeClass alloc];[anObject init];[anObject someOtherMessage];

Code is dangerous since it ignores return of init.

Safe Initialization: combine allocation and initialization

id anObject = [[SomeClass alloc] init];[anObject someOtherMessage];

7/20/2009 [email protected]

Page 27: Objective C for iPhone Development

Custom Initializer Name must begin with init e.g. initWithFormatReturn type should be idinvoke the superclass’s designated initializerassign self to the value returned by the designated initializerreturn self, unless the initializer fails in which case you return nilif there is a problem during an initialization method, you should call [self release] and return nil.

- (id)init {// Assign self to value returned by super's designated initializer// Designated initializer for NSObject is initif (self = [super init]) {creationDate = [[NSDate alloc] init];}return self;}7/20/2009 [email protected]

Page 28: Objective C for iPhone Development

Designated Initializer

Method that guarantees inherited instance variables are initialized (by sending a message to super to perform an inherited method).

Designated initializers are chained to each other through messages to super.

Other initialization methods are chained to designated initializers through messages to self.

7/20/2009 [email protected]

Page 29: Objective C for iPhone Development

Designated Initializer- (id)initWithName:(NSString *)string{if ( self = [super init] ) {name = [string copy];}return self;}

- init{return [self initWithName:"default"];}

7/20/2009 [email protected]

Page 30: Objective C for iPhone Development

Using Super

- negotiate{...return [super negotiate];}overrides existing method to modify or add and still incorporates the original method.

7/20/2009 [email protected]

Page 31: Objective C for iPhone Development

Using Super

Initialization with init- (id)init{ if (self = [super init]) {...}}

sends an init message to super to have the classes it inherits from initialize their instance variables.

7/20/2009 [email protected]

Page 32: Objective C for iPhone Development

Redefining self in Class MethodsClass methods are often concerned not with the class object, but with instances of the class.+ (Rectangle*)rectangleOfColor:(NSColor *) color

{self = [[Rectangle alloc] init]; // BAD[self setColor:color];return [self autorelease]; }self here refers to class object.

7/20/2009 [email protected]

Page 33: Objective C for iPhone Development

Redefining self in Class Methods

To avoid confusion, use a variable other than self to refer to an instance inside a class method:

+ (id)rectangleOfColor:(NSColor *)color{id newInstance = [[Rectangle alloc] init]; // GOOD[newInstance setColor:color];return [newInstance autorelease];}

7/20/2009 [email protected]

Page 34: Objective C for iPhone Development

Redefining self in Class Methods

Rather than sending the alloc message to the class in a class method, it’s often better to send alloc to self. This way, if the class is subclassed, and the rectangleOfColor: message is received by a subclass,the instance returned will be the same type as the subclass+ (id)rectangleOfColor:(NSColor *)color

{id newInstance = [[self alloc] init]; // EXCELLENT[newInstance setColor:color];return [newInstance autorelease];}

7/20/2009 [email protected]

Page 35: Objective C for iPhone Development

Super vs. Self

super - is simply a flag to the compiler telling it where to begin searching for the method to perform; it’s used only as the receiver of a message.self - is a local variable within method and it can be used in any number of ways, even assigned a new value

7/20/2009 [email protected]

Page 36: Objective C for iPhone Development

Declared Propertiesshorthand for declaring accessor methodsprovides a clear, explicit specification of how the accessor methods behavecompiler can synthesize accessor methods for youProperties are represented syntactically as identifiers and are scopedyou have less code to write and maintain

NSTextField *textField;@property (retain) IBOutlet NSTextField *textField;@synthesize textField;

7/20/2009 [email protected]

Page 38: Objective C for iPhone Development

Property Declaration

@property(attributes) type name;

is equivalent to:- (float)value;- (void)setValue:(float)newValue;

7/20/2009 [email protected]

Page 39: Objective C for iPhone Development

Property Declaration

Attributes- readwrite- readonly- assign- retain- copy- nonatomic

7/20/2009 [email protected]

Page 40: Objective C for iPhone Development

Using Properties

Property Re-declarationRe-declare a property in a subclass, but you must repeat its attributes in whole in the subclassesIf you declare a property in one class as readonly, you can redeclare it as readwrite in a class extension

7/20/2009 [email protected]

Page 41: Objective C for iPhone Development

Re-declare readonly to readwrite// public header file@interface MyObject : NSObject {NSString *language;}@property (readonly, copy) NSString *language;@end// private implementation file@interface MyObject ()@property (readwrite, copy) NSString *language;@end@implementation MyObject@synthesize language;@end

using a class extension to provide a property that is declared as read-only in the public header but is redeclared privately as read/write

7/20/2009 [email protected]

Page 42: Objective C for iPhone Development

Copy Attribute

value is copied during assignment@property (nonatomic, copy) NSString *string;string = [newString copy];

synthesized method uses the copy methodCopy returns immutable version of collection.Provide your own implementation for mutable arrays or collections

7/20/2009 [email protected]

Page 43: Objective C for iPhone Development

Copy For mutable Array@interface MyClass : NSObject {NSMutableArray *myArray;}@property (nonatomic, copy) NSMutableArray *myArray;@end@implementation MyClass@synthesize myArray;- (void)setMyArray:(NSMutableArray *)newArray {

if (myArray != newArray) {[myArray release];myArray = [newArray mutableCopy];

}}@end

7/20/2009 [email protected]

Page 44: Objective C for iPhone Development

Category

Allows you to add methods to an existing class without subclassing.Additional instance variables can not be added using category.No difference between methods declared in class implementation and declared as category.Category methods are inherited by all subclasses of the class.All instance variables within the scope of the class are also within the scope of the category

7/20/2009 [email protected]

Page 45: Objective C for iPhone Development

Category Declaration

#import "ClassName.h"@interface ClassName ( CategoryName )// method declarations

@end

#import "ClassName+CategoryName.h"@implementation ClassName ( CategoryName )// method definitions

@end

7/20/2009 [email protected]

Page 46: Objective C for iPhone Development

Category

A category can also override methods declared in the class interface.Cannot reliably override methods declared in another category of the same class.Not a substitute for subcalss.Use categories to distribute the implementation of a new class into separate source files

7/20/2009 [email protected]

Page 47: Objective C for iPhone Development

Protocols

Objective C protocols are similar to java’s interfaces.Declare methods that any class can implement. Declare the interface to an object while concealing its class.List of methods declarations, unattached to class definition.Formal and informal protocols.

7/20/2009 [email protected]

Page 48: Objective C for iPhone Development

Formal protocols

@protocol ProtocolNamemethod declarations@end

@protocol NSCopying- (id)copyWithZone: (NSZone *)zone;@end

@optional & @required(default)7/20/2009 [email protected]

Page 49: Objective C for iPhone Development

Informal ProtocolsCategory that lists a group of methods but does not implement them.Typically declared for root NSObject class.Implementing class need to declare methods again in interface file and define with other methods in implementation file.No type checking at compile time nor a check at runtime to see whether an object conforms to the protocol.

@interface NSObject ( MyXMLSupport )- initFromXMLRepresentation:(NSXMLElement *)XMLElement;@property (nonatomic, readonly) (NSXMLElement *)XMLRepresentation;@end

7/20/2009 [email protected]

Page 50: Objective C for iPhone Development

Conform & Adopt a protocol

[receiver conformsToProtocol:@protocol(MyXMLSupport)]

@interface ClassName : ItsSuperclass < protocol list >

@interface Formatter : NSObject < Formatting, Prettifying >

Protocol adopting protocol

@protocol Drawing3D<Drawing>

7/20/2009 [email protected]

Page 51: Objective C for iPhone Development

Type Checking

- (id <Formatting>)formattingService;id <MyXMLSupport> anObject;

anObject will contain objects which conform to MyXMLSupport protocol.

7/20/2009 [email protected]

Page 52: Objective C for iPhone Development

Fast Enumeration

Type existingItem;for ( existingItem in expression ) { statements }

NSArray, NSDictionary, and NSSet—adopt NSFastEnumeration protocol

NSArray *array = [NSArray arrayWithObjects:@"One", @"Two", @"Three", @"Four", nil];for (NSString *element in array) {NSLog(@"element: %@", element);}

7/20/2009 [email protected]

Page 53: Objective C for iPhone Development

Exception Handling

Similar to java and C++@try, @catch, @throw, and @finally directives and NSException

Cup *cup = [[Cup alloc] init];@try {[cup fill];}@catch (NSException *exception) {NSLog(@"main: Caught %@: %@", [exception name], [exception reason]);}@finally {[cup release];}

7/20/2009 [email protected]

Page 54: Objective C for iPhone Development

Exception Handling

Throwing an exceptioninside catch block throw exception usinf @throw directive

NSException *exception = [NSException exceptionWithName:@"HotTeaException"reason:@"The tea is too hot" userInfo:nil];@throw exception;

7/20/2009 [email protected]

Page 55: Objective C for iPhone Development

Selectors

Two Meaning Name of the method when used inside source code message to object.Unique identifier when the source code is compiled.SEL and @selectorUse @selector directive to refer to compiled selector.SEL setWidthHeight;setWidthHeight = @selector(setWidth:height:);

7/20/2009 [email protected]

Page 56: Objective C for iPhone Development

Selectors

String to selectorsetWidthHeight = NSSelectorFromString(aBuffer);

Selector to StringNSStringFromSelector function returns a method name for a selector:

NSString *method;method = NSStringFromSelector(setWidthHeight)

7/20/2009 [email protected]

Page 57: Objective C for iPhone Development

Memory Management

No garbage collection for iphoneAuto release pool

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];adds certain arrays, strings, dictionaries to this pool

[pool drain];

Pool contains reference to objects to be released.[anObject autorelease] adds anObject to autorelase pool.

7/20/2009 [email protected]

Page 58: Objective C for iPhone Development

Memory Management

Auto release pool is must for using foundation objects.

[NSString stringWithString: @”string 2”];

Reference Counting.[anObject retain][anObject release][anObject retainCount]

Constant strings have no reference-counting mechanism because they can never be released

7/20/2009 [email protected]

Page 59: Objective C for iPhone Development

Reference count & Instance variables

-(void) setName: (NSString *) theName{name = theName;}

NSString *newName;...[myCard setName: newName];

-(void) setName: (NSString *) theName{[name release];name = [[NSString alloc] initWithString: theName];}

7/20/2009 [email protected]

Page 60: Objective C for iPhone Development

Dealloc and Autorelease-(void) dealloc {

[name release];[super dealloc];

}@endClassA *myA = [[ClassA alloc] init];.......[myA release];

ClassA *myA = [[ClassA alloc] init];[myA autorelease];

7/20/2009 [email protected]

Page 61: Objective C for iPhone Development

Interview Buzz

7/20/2009 [email protected]

Page 62: Objective C for iPhone Development

Thanks

7/20/2009 [email protected]