Fugenx Technologies Private Limited

siliconindia

Fugenx Technologies Private Limited

FuGenX Technologies Private Limited

Understanding Cocoa for Effective iOS Programming

© 2011, FuGenX Technologies Confidential

1

1


Model View Controller

� Model : The Model subsystem is composed of the objects that provide the

unique capabilities and information storage for an application. Models contain

all of the rules for processing application data.The Model is the key subsystem

that makes an application valuable. It’s critically important that the Model

subsystem is able to stand alone without dependencies on either theView or

Controller subsystems.

� View : The View subsystem presents information gathered from the Model

and provides a way for users to interact with information.The key to

understanding Views is to recognize that there are invariably a multitude of

Views.For example, there may be a graphical user interface View, a printed

report View, a command line View, a Web-based View, and a scripting

language View that all interact with the same Model.

� Controller : The purpose of the Controller is to decouple the Model from the

Views. User interaction with a View results in requests made to the Controller

sub- system, which in turn may request changes to information in the

Model.The Controller also handles data translation and formatting for

presentation to the user

© 2011, FuGenX Technologies Confidential 2

2


Model View controller - Example

� The controller identifies which Model objects need to be updated based on the new

value.The Controller sends messages to the Model objects to request the updates. In

step 3, the Model objects react to the messages about updates.The Model objects

might constrain the up- dated values to fall within application defined limits or

perform other validation. Application logic is applied to the updated values, and other

Model objects may be updated as a side effect.The Model then notifies the Controller

that the Model has changed. Finally, in step 4, the Controller sends messages to View

objects so that they reflect the changes that occurred in the Model.There may be many

parts of theView that are updated.

Slider

© 2011, FuGenX Technologies Confidential

3 3


MVC in Cocoa

© 2011, FuGenX Technologies Confidential

4

4


NSObject

� NSObject is a base class, it does not inherit from any other objects. However it

does conform to a protocol called NSObject. This protocol gives it a basic

interface to the run-time system. The Apple documentation states that

NSObject is not strictly an abstract class but you can pretty much think of it like

that. NSObject is not only an object but it is also a Protocol, both of which are

necessary for an object to work properly.

� NSObject is the object that gives all other objects access to the alloc and init

methods. These methods are used to allocate and initialize any object that you

have created. Let's take a look at what some of them are. This will also

populate the isa property with a data structure that will describe the class.

© 2011, FuGenX Technologies Confidential

5

5


NSObject Methods

� alloc - The alloc method will return a new instance of the receiving object.

When you use alloc it will store your object in the default memory zone. If you

would like to specify the zone you can use allocWithZone. A default NSZone is

created on start-up and all objects default to being allocated there.

� allocWithZone - This does exactly the same thing as alloc except it allows you

to specify the zone you wish to use. This requires you to pass in an object that

is of type NSZone.

© 2011, FuGenX Technologies Confidential 6

6


NSObject Methods

� init - Initialize the object after the memory has been allocated for it. You must

initialize an object before you can use it.

� description - Returns a string that describes the contents of the receiver. When

you are using the debuggers print object command it will indirectly invoke this

method to tell you more about the object. This is nice because you can specify

what you want returned when something attempts to print out an object.

� dealloc - Just before an object is freed from memory the dealloc method is

called. This allows you to do any cleanup work that you might have to do for the

class.

© 2011, FuGenX Technologies Confidential

7

7


Class Hierarchy - An Overlook

© 2011, FuGenX Technologies Confidential

8

8


Over-riding Base Class Methods

� Example : The Car class’s init method overrides NSObject’s version. When

sent an init message, a car object runs its version, not NSObject’s. At the

same time, the code for init makes sure to call NSObject’s init method via

[super init].

@implementation Car

- (id)init {

if (nil != (self = [super init])) {

// initialize

}

}

@end

return self;

© 2011, FuGenX Technologies Confidential 9

9


Fundamental Design Patterns

�Two-Stage Creation

�Template Method

�Dynamic Creation

�Category

�Selector

�Selector

�Singleton

�Delegates

© 2011, FuGenX Technologies Confidential

10

10


Two Stage Creation

� The Two-Stage Creation pattern separates the first stage, object

memory allocation, from the second stage, object initialization.

� Enable the use of initializers regardless of the way memory is

allocated.

� Avoid the need to implement too many initializers when

subclassing.

� Simplify the creation and use of temporary instances.

© 2011, FuGenX Technologies Confidential

11

11


Two - Stage Creation

An Example of Allocation and initialization done together in a

single method :

+ (id)circleWithCenter:(NSPoint)aPoint radius:(float)radius {

// allocation and partial initialization are provided by superclass

id newInstance = [[super new] autorelease];

}

Text

if(nil != newInstance) // verify new instance was created {

}

[newInstance setCenter:aPoint]; [newInstance setRadius:radius];

[newInstance setLabel:@”default”];

return newInstance;

© 2011, FuGenX Technologies Confidential

12


Two - Stage Creation

Due to so many possible ways an object can be initialized there

can be a huge list of initializer methods.

An Example :

+imageFromRegularMemoryWithContentsOfFile:

+imageFromRegularMemoryWithContentsOfURL:

+imageFromRegularMemoryWithData:

+imageFromRegularMemoryWithPasteboard:

+imageFromRegularMemoryWithSize:

+imageFromGraphicsMemory:(MYCardID)aCard withContentsOfFile:

+imageFromGraphicsMemory:(MYCardID)aCard withContentsOfURL:

+imageFromGraphicsMemory:(MYCardID)aCard withData:

+imageFromGraphicsMemory:(MYCardID)aCard withPasteboard:

+imageFromGraphicsMemory:(MYCardID)aCard withSize:

© 2011, FuGenX Technologies Confidential

13


Two - Stage Creation

Coming back to NSObject’s base class method :

The +alloc and +allocWithZone: methods each return a

pointer to a newly allocated block of memory large enough to store an

instance of the class that executed the method.

The allocated memory contains zeros except for the one instance

variable, isa, that all Objective-C objects are required to have.The

isa variable is automatically initialized to point to the class object

that allocated the memory and is the tie-in to the Objective-C language

run- time that enables the instance to receive messages such as -init

that are used to complete initialization.

© 2011, FuGenX Technologies Confidential

14


Two - Stage Creation

Zones

Memory zones are a feature of Cocoa intended to improve application

performance by keeping the memory for objects that are used together

close together in the computer’s address space.

@interface MYCircle : NSObject {

Text

NSPoint center;

floatradius;

NSString *label;

}

// Designated Initializer

- (id)initWithCenter:(NSPoint)aPoint radius:(float)aRadius;

@end

© 2011, FuGenX Technologies Confidential

15


@implementation MYCircle

// Designated Initializer

Two Stage Creation

- (id)initWithCenter:(NSPoint)aPoint radius:(float)aRadius {

self = [super init];

if(nil != self) {

center = aPoint;

radius = aRadius;

label = [[NSString allocFromZone:[self zone]

initWithString:@”default”];

}

return self;

}

© 2011, FuGenX Technologies Confidential

16


Two - Stage creation

� Regardless of whether zones are used, when an object is

deallocated, its dealloc method is called.

- (void)dealloc

{

[label release];

[super dealloc];

}

© 2011, FuGenX Technologies Confidential

17


Template Method

� A Template Method is a special case of a method that is

expected to be overridden in subclasses.

� Cocoa automatically calls –dealloc when needed. Another

prominent Template Method is the –drawRect: method

provided by the NSView class. Like –dealloc, -drawRect:

should almost never be called directly except to invoke the

superclass implementation and is instead called

automatically by Cocoa.

© 2011, FuGenX Technologies Confidential

18

18


Default Template Methods

Template Method

Any class that provides Template Methods should provide

reasonable default implementations for the methods. Default

implementations fall into three general categories that

correspond to whether the default implementation can, should,

or must be called by overridden versions.

© 2011, FuGenX Technologies Confidential

19


Template Method

When You Can Call the Default Implementation

In many cases, a default implementation does nothing. In such

cases, it’s safe for the override to call the default

implementation, but it certainly doesn’t need to call it.The

NSView –drawRect: method is such an example: It can be

called, but it doesn’t do anything.

© 2011, FuGenX Technologies Confidential

20


Template Method

When You Should Call the Default Implementation

NSView provides another Template Method called –hitTest:

It returns the most appropriate object to receive a mouse event

at a specified point.When overriding –hitTest:, the default

implementation should almost always be called because the

selection of the most appropriate object is based on complex but

standard logic that you most likely don’t want to re-implement.

You might however want to simulate a round NSView subclass

or provide other unique application behavior.

© 2011, FuGenX Technologies Confidential

21


Template Method

When You Must Call the Default Implementation

The –dealloc Template Method must be called by any overriding

method. If the over- ridden version isn’t called from the subclass’

version, your program will most likely contain memory leaks, which

has serious consequences.

© 2011, FuGenX Technologies Confidential

22


NSObject Template Methods

Template Methods

-(id)awakeAfterUsingCoder:(NSCoder *)aDecoder

-(Class)classForArchiver

-(Class)classForCoder

-(Class)classForKeyedArchiver

-(Class)classForPortCoder

-(id)replacementObjectForArchiver:(NSArchiver *)anArchiver

+(NSArray *)classFallbacksForKeyedArchiver

-(id)copyWithZone:(NSZone *)zone

-(id)mutableCopyWithZone:(NSZone *)zone

-(void)forwardInvocation:(NSInvocation *)anInvocation

-(NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector

© 2011, FuGenX Technologies Confidential

23


Dynamic Creation

Cocoa utilizes many features of the underlying Objective-C runtime.

One powerful feature is the ability to create instances of classes that

did not exist at the time an application was compiled and dynamically

load and link new classes at runtime.

Decouple classes from each other and postpone decisions about

which class to use until runtime.

© 2011, FuGenX Technologies Confidential

24


Dynamic Creation

The basis of this pattern is a single function,

NSClassFromString().It takes a single argument, an NSString

containing the name of a class. Once a class object has been obtained, it

can be instantiated or otherwise manipulated.

Developers can use Dynamic Creation themselves to create code that

isn’t directly coupled to other code.This is especially useful for creating

plug-in architectures. It can also be employed to develop frameworks

that are easily extended.

© 2011, FuGenX Technologies Confidential

25


Category

The Category pattern adds methods to existing classes and provides an

alternative to subclassing in many situations.

The added methods are inherited by all subclasses of the extended

class and are indistinguishable at runtime from methods originally

compiled into the class.

Unlike subclasses, categories can’t be used to add instance variables to

an existing class, however the Associative Storage pattern provides a

way to simulate the existence of additional instance variables within a

category implementation.

© 2011, FuGenX Technologies Confidential

26


Category

We use the Category pattern to accomplish the following:

- Extend existing classes without subclassing.

- Create informal protocols.

- Implement different methods of the same class in different

frameworks.

- Spread the implementation of individual classes across multiple

source files.

- Simplify development when multiple programmers contribute to

the definition of individual classes.

© 2011, FuGenX Technologies Confidential

27


Category

As an example, the following category adds convenient methods

to Cocoa’s NSMutableArray class:

@interface NSMutableArray (MYAdditions)

- (void)addObjectIfAbsent:(id)anObject;

@end

© 2011, FuGenX Technologies Confidential

28


Category

@implementation NSMutableArray (MYAdditions)

// Adds useful methods to mutable arrays

- (void)addObjectIfAbsent:(id)anObject

// Adds anObject to the receiver if and only if anObject is not

// nil and already contained by receiver

{

if((nil != anObject) && ![self containsObject:anObject]) {

[self addObject:anObject];

}

@end

© 2011, FuGenX Technologies Confidential

29


Selectors

Selectors identify the messages that are sent to Objective-C

objects.They’re used by the receivers of messages to select

which methods will be performed.

Using selectors, Cocoa objects can be asked to perform

methods immediately or after arbitrary time delays. Delaying the

performance of methods can be very handy and is sometimes

used to keep a user interface responsive while long-running

tasks complete, implement animation, or provide other timebased

application features.

© 2011, FuGenX Technologies Confidential

30


Singleton

� The Singleton pattern is used when there must be exactly

one instance of a class, and it must be easily accessible to

other objects in an application.

�� Usually, the Cocoa documentation uses the term shared

instance when the Singleton pattern is in use.

© 2011, FuGenX Technologies Confidential

31


Singleton

� Encapsulate a shared resource.

� Provide a standard way to create one shared instance.

� Provide a standard way to access the one shared instance.

© 2011, FuGenX Technologies Confidential

32


Singleton

Creating and Accessing a Shared Instance with example

To have a shared instance, it is necessary to change the interface of the

example class MYDataManager so that the management is done with

instance methods. A class method also needs to be added to allow for

access to the shared instance.A commonly chosen name

is+sharedInstance.

© 2011, FuGenX Technologies Confidential

33


Here is the new interface:

@interface MYDataManager : NSObject {

}

+ (id)sharedInstance;

Singleton

- (void)registerScore:(NSNumber *)score

playerName:(NSString *)name;

- (NSEnumerator *)scoreEnumerator;

© 2011, FuGenX Technologies Confidential

34


Singleton

A basic implementation of the +sharedInstance method might be

like this:

+ (MYDataManager *)sharedInstance {

static MYDataManager *myInstance = nil;

if (!myInstance) {

myInstance = [[[self class] alloc] init];

}

return myInstance;

}

© 2011, FuGenX Technologies Confidential

35


Controlling Instantiation

Singleton

To fully implement the Singleton pattern, it is necessary to

prevent the creation of multiple instances of a class.

+ (id)alloc {

return nil;

}

© 2011, FuGenX Technologies Confidential

36


+ (id)new {

return [self alloc];

}

Singleton

+ (id)allocWithZone:(NSZone *)zone {

return [self alloc];

}

© 2011, FuGenX Technologies Confidential

37


Singleton

- (id)copyWithZone:(NSZone *)zone {

[self retain];

return self;

}

- (id)mutableCopyWithZone:(NSZone *)zone {

return [self copyWithZone:zone];

}

© 2011, FuGenX Technologies Confidential

38


Deallocation

Singleton

+ (void)attemptDealloc {

if ([myInstance retainCount] != 1)

return;

[myInstance release];

myInstance = nil;

}

© 2011, FuGenX Technologies Confidential

39


Singleton

Determining if the Singleton Has Been Created

+ (BOOL)sharedInstanceExists {

return (nil != myInstance);

}

This how you can create a shared Instance

myInstance = (MyDataManager *)[[MyDataManager class]

sharedInstance];

© 2011, FuGenX Technologies Confidential

40


Delegates

� A delegate is an object that’s given an opportunity to react

to changes in another object or influence the behavior of

another object

� Delegates simplify the customization of object behavior

while minimizing coupling between objects

© 2011, FuGenX Technologies Confidential

41


Delegates

© 2011, FuGenX Technologies Confidential

42


Delegates

© 2011, FuGenX Technologies Confidential

43


Delegates

© 2011, FuGenX Technologies Confidential

44


Delegates

Slider

© 2011, FuGenX Technologies Confidential

45


#import “Model.h”

#import “Slider.h”

Delegates

@interface Controller : NSObject

{

Model *obj_Model;

Slider *obj_Slider;

}

@property (nonatomic, retain) Model *obj_Model;

@property (nonatomic, retain) Slider *obj_Slider;

© 2011, FuGenX Technologies Confidential

46


@implementation Controller

Delegates

-(id) init

{

if(nil != [super init])

{

obj_Model = [[Model alloc] init];

obj_Model.delegate = self;

}

}

obj_Slider = [[Slider alloc] init];

obj_Slider.delegate = self;

© 2011, FuGenX Technologies Confidential

47


Delegates

-(void)processUserInput:(float)pObjInput

{

[obj_Model processThis:pObjInput];

}

-(void)showProcessedValue:(float)pObjOutput

{

[obj_Slider showThis:pObjInput];

}

@end

© 2011, FuGenX Technologies Confidential

48


Delegates

@protocol ModelDelegate

{

-(void) processingDone:(float)pObjOutPut;

}

@interface Model : NSObject

{

id delegate;

}

@property (nonatomic, retain) id delegate;

-(void)processThis:(float)pObjInput;

© 2011, FuGenX Technologies Confidential

49


@implementation Model

Delegates

-(void)processThis:(float)pObjInput

{

float outPut = x* pObjInput + x_Offset;

[delegate processingDone:outPut];

}

@end

50

© 2011, FuGenX Technologies Confidential 50


Delegates

@protocol SliderDelegate

{

-(void)changedUserInput:(float)pObjInPut;

}

@interface Slider : UISlider

{

}

-(void)showThis:(float)pObjOutput;

© 2011, FuGenX Technologies Confidential

51


@implementation Slider

Delegates

-(void)sliderValueDidChangeTo:(float)pObjIput

{

[delegate changedUserInput: pObjIput];

}

-(void)showThis:(float)pObjOutput

{

// Code to show the numeric value on screen

}

@end

© 2011, FuGenX Technologies Confidential

52


Thank You

© 2011, FuGenX Technologies Confidential

53

More magazines by this user
Similar magazines