beginningi os part1-bobmccune

61
http://bobmccune.com Beginning iOS Development Monday, March 19, 12

Upload: mobile-march

Post on 10-May-2015

768 views

Category:

Technology


0 download

DESCRIPTION

Mobile March 2012

TRANSCRIPT

Page 1: Beginningi os part1-bobmccune

http://bobmccune.com

Beginning iOS Development

Monday, March 19, 12

Page 2: Beginningi os part1-bobmccune

Beginning iOS DevelopmentAgenda

• Understanding the Tools

• Objective-C Crash Course

• Using Cocoa Touch

Monday, March 19, 12

Page 3: Beginningi os part1-bobmccune

iOS SDK Tools

Monday, March 19, 12

Page 4: Beginningi os part1-bobmccune

Xcode

Monday, March 19, 12

Page 5: Beginningi os part1-bobmccune

Xcode•Apple’s IDE for creating Mac and iOS apps

•Provides visual front end to LLVM and LLDB

•Hub of development process:

Editing

Building

Refactoring

Debugging

API Doc Integration

UI Design

Testing

Model Design

Deployment

Project Configuration

Monday, March 19, 12

Page 6: Beginningi os part1-bobmccune

iOS Simulator

Monday, March 19, 12

Page 7: Beginningi os part1-bobmccune

•Device simulator, runs on your desktop

•Both iPhone and iPad (retina, non-retina)

•Faster code, build, test cycle

•Test behaviors: rotation, shake, multi-touch

•Easier testing of exceptional conditions

• iOS Simulator != iOS Device:

•No memory or CPU limits

•Not all APIs and capabilities available

iOS Simulator

Monday, March 19, 12

Page 8: Beginningi os part1-bobmccune

Instruments

Monday, March 19, 12

Page 9: Beginningi os part1-bobmccune

Instruments

• Dynamic tracing and profiling tool• Uses digital audio workstation-like interface• Large library of standard instruments

• Core Animation, Leaks, Automation, etc.

• The ultra geeky can build custom instruments

Monday, March 19, 12

Page 10: Beginningi os part1-bobmccune

Hands-On Tour

Monday, March 19, 12

Page 11: Beginningi os part1-bobmccune

Objective-C

Monday, March 19, 12

Page 12: Beginningi os part1-bobmccune

Objective-C EssentialsAgenda

• Overview of Objective-C

• Understanding Classes and Objects

• Methods, Messages, and Properties

• Protocols

Monday, March 19, 12

Page 13: Beginningi os part1-bobmccune

The old, new hotnessObjective-C

• Strict superset of ANSI C• Object-oriented extensions

• Additional syntax and types

• Dynamic, Object-Oriented Language:• Dynamic Typing

• Dynamic Binding

• Dynamic Loading

Monday, March 19, 12

Page 14: Beginningi os part1-bobmccune

Creating Classes

Monday, March 19, 12

Page 15: Beginningi os part1-bobmccune

The BlueprintCreating Classes

• Objective-C classes are separated into an interface and an implementation.• Usually defined in separate .h and .m files

•Defines the programming interface

•Can define object instance variables

•Defines the actual implementation code

•Implement one or more initializers to properly initialize an object instance

Monday, March 19, 12

Page 16: Beginningi os part1-bobmccune

Defining the Interface@interface BankAccount : NSObject {}

@end

float accountBalance;NSString *accountNumber;

- (float)withDraw:(float)amount;- (void)deposit:(float)amount;

Monday, March 19, 12

Page 17: Beginningi os part1-bobmccune

Defining the Interface@interface BankAccount : NSObject {}

@end

float accountBalance;NSString *accountNumber;

- (float)withDraw:(float)amount;- (void)deposit:(float)amount;

Monday, March 19, 12

Page 18: Beginningi os part1-bobmccune

Defining the Interface@interface BankAccount : NSObject {}

@end

float accountBalance;NSString *accountNumber;

- (float)withDraw:(float)amount;- (void)deposit:(float)amount;

Monday, March 19, 12

Page 19: Beginningi os part1-bobmccune

Defining the Interface@interface BankAccount : NSObject {}

@end

float accountBalance;NSString *accountNumber;

- (float)withDraw:(float)amount;- (void)deposit:(float)amount;

Monday, March 19, 12

Page 20: Beginningi os part1-bobmccune

Defining the Interface@interface BankAccount : NSObject {}

@end

float accountBalance;NSString *accountNumber;

- (float)withDraw:(float)amount;- (void)deposit:(float)amount;

Monday, March 19, 12

Page 21: Beginningi os part1-bobmccune

Defining the Interface@interface BankAccount : NSObject {}

@end

float accountBalance;NSString *accountNumber;

- (float)withDraw:(float)amount;- (void)deposit:(float)amount;

Monday, March 19, 12

Page 22: Beginningi os part1-bobmccune

Defining the Implementation#import "BankAccount.h"

@implementation BankAccount

- (id)init { self = [super init]; return self;}

- (float)withdraw:(float)amount { // calculate valid withdrawal return amount;}

- (void)deposit:(float)amount { // record transaction}@end

Monday, March 19, 12

Page 23: Beginningi os part1-bobmccune

Defining the Implementation#import "BankAccount.h"

@implementation BankAccount

- (id)init { self = [super init]; return self;}

- (float)withdraw:(float)amount { // calculate valid withdrawal return amount;}

- (void)deposit:(float)amount { // record transaction}@end

Monday, March 19, 12

Page 24: Beginningi os part1-bobmccune

Defining the Implementation#import "BankAccount.h"

@implementation BankAccount

- (id)init { self = [super init]; return self;}

- (float)withdraw:(float)amount { // calculate valid withdrawal return amount;}

- (void)deposit:(float)amount { // record transaction}@end

Monday, March 19, 12

Page 25: Beginningi os part1-bobmccune

Defining the Implementation#import "BankAccount.h"

@implementation BankAccount

- (id)init { self = [super init]; return self;}

- (float)withdraw:(float)amount { // calculate valid withdrawal return amount;}

- (void)deposit:(float)amount { // record transaction}@end

Monday, March 19, 12

Page 26: Beginningi os part1-bobmccune

Understanding the SyntaxDefining Methods

• Class methods

• Prefixed with a +

• Tied to class, not instance

• Instance Methods• Instance methods prefix with a -

• Modifies state of an object instance

- (NSString *)description;

Monday, March 19, 12

Page 27: Beginningi os part1-bobmccune

Understanding the SyntaxDefining Methods

• Class methods

• Prefixed with a +

• Tied to class, not instance

• Instance Methods• Instance methods prefix with a -

• Modifies state of an object instance

- (BOOL)respondsToSelector:(SEL)aSelector;

Monday, March 19, 12

Page 28: Beginningi os part1-bobmccune

Understanding the SyntaxDefining Methods

• Class methods

• Prefixed with a +

• Tied to class, not instance

• Instance Methods• Instance methods prefix with a -

• Modifies state of an object instance

+ (void)transitionWithView:(UIView *)view duration:(NSTimeInterval)duration options:(UIViewAnimationOptions)options animations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion;

Monday, March 19, 12

Page 29: Beginningi os part1-bobmccune

Talking to yourself

-(id)init { self = [super init]; if (self) { // do initialization } return self;}

• Methods have implicit reference to owning object called self

• Additionally have access to superclass methods using super

self and super

Monday, March 19, 12

Page 30: Beginningi os part1-bobmccune

Working with Objects

Monday, March 19, 12

Page 31: Beginningi os part1-bobmccune

Two-Stage Creation• NSObject defines class method called alloc

• Dynamically allocates memory for object

• Returns new instance of receiving class

BankAccount *account = [BankAccount alloc];

• NSObject defines instance method init

• Implemented by subclasses to initialize instance after memory for it has been allocated

• Subclasses commonly define several initializers

• alloc and init calls should always nested into single line

account = [account init];

BankAccount *account = [[BankAccount alloc] init];

Monday, March 19, 12

Page 32: Beginningi os part1-bobmccune

Messages

• Methods are invoked by passing messages• Methods are never directly invoked

• Messages dynamically bound to method implementations at runtime

• Simple messages take the form:• [object message];

• Can pass one or more arguments:• [object methodWithArg1:arg1 arg2:arg2];

Communicating with Objects

Monday, March 19, 12

Page 33: Beginningi os part1-bobmccune

Messaging an ObjectNSMutableDictionary *person =

[NSMutableDictionary dictionary];

[person setObject:children forKey:@"children"];

[person setObject:@"Joe Smith" forKey:@"name"];

NSString *address = @"123 Street";NSString *house = [address substringWithRange:NSMakeRange(0, 3)];[person setObject:house forKey:@"houseNumber"];

NSArray *children = [NSArray arrayWithObjects:@"Jack", @"Susie", nil];

Monday, March 19, 12

Page 34: Beginningi os part1-bobmccune

Declared Properties

Monday, March 19, 12

Page 35: Beginningi os part1-bobmccune

Declared Properties

• Most common methods we write are accessors

• Objective-C can automatically generate accessors

• Much less verbose, less error prone

• Highly configurable

• Declared properties are defined in two parts:

• @property definition in the interface

• @synthesize statement in the implementation

Simplifying Accessors

Monday, March 19, 12

Page 36: Beginningi os part1-bobmccune

Declaring Properties

Attribute Impacts

nonatomic Concurrency

readonly/readwrite Mutability

strong/copy/weak/assign Storage

getter/setter API

@property (attributes) type variable;

Monday, March 19, 12

Page 37: Beginningi os part1-bobmccune

Declaring Properties

Attribute Impacts

nonatomic Concurrency

readonly/readwrite Mutability

strong/copy/weak/assign Storage

getter/setter API

@property (attributes) type variable;

@property (readonly) BOOL active;

Monday, March 19, 12

Page 38: Beginningi os part1-bobmccune

Declaring Properties

Attribute Impacts

nonatomic Concurrency

readonly/readwrite Mutability

strong/copy/weak/assign Storage

getter/setter API

@property (attributes) type variable;

@property (nonatomic, readonly) BOOL active;

Monday, March 19, 12

Page 39: Beginningi os part1-bobmccune

Declaring Properties

Attribute Impacts

nonatomic Concurrency

readonly/readwrite Mutability

strong/copy/weak/assign Storage

getter/setter API

@property (attributes) type variable;

@property (nonatomic, strong) NSDate *activeDate;

Monday, March 19, 12

Page 40: Beginningi os part1-bobmccune

Declaring Properties

Attribute Impacts

nonatomic Concurrency

readonly/readwrite Mutability

strong/copy/weak/assign Storage

getter/setter API

@property (attributes) type variable;

@property (readonly, getter=isValid) BOOL valid;

Monday, March 19, 12

Page 41: Beginningi os part1-bobmccune

Defining the InterfaceDeclaring Properties

@interface BankAccount : NSObject

@property (nonatomic, copy) NSString *accountNumber;@property (nonatomic, strong) NSDecimalNumber *balance;@property (readonly, strong) NSDecimalNumber *fees;@property (getter=isCurrent) BOOL accountCurrent;

@end

Monday, March 19, 12

Page 42: Beginningi os part1-bobmccune

Generating the AccessorsSynthesizing Properties

@implementation BankAccount

@synthesize accountNumber = _accountNumber;@synthesize balance = _balance;@synthesize fees = _fees;@synthesize accountCurrent = _accountCurrent;

@end

Monday, March 19, 12

Page 43: Beginningi os part1-bobmccune

Accessing Properties• Generated properties are standard methods

• Accessed through normal messaging syntax

[object property];[object setProperty:newValue];

• Objective-C property access via dot notationobject.property;object.property = newValue;

Dot notation is just syntactic sugar. Still uses accessor methods. Doesn't get/set values directly.

Monday, March 19, 12

Page 44: Beginningi os part1-bobmccune

Protocols

Monday, March 19, 12

Page 45: Beginningi os part1-bobmccune

Object-Oriented ContractsProtocols

• Abstract methods to be implemented• Methods are not tied to a specific class

• Analogous to C# and Java interfaces

• Useful in defining:• Capturing similarities among classes that aren't

hierarchically related

• Declaring an interface while hiding its particular class

• Delegate callback methods

Monday, March 19, 12

Page 46: Beginningi os part1-bobmccune

NSCodingDefining a Protocol

@protocol NSCoding

- (void)encodeWithCoder:(NSCoder *)aCoder;- (id)initWithCoder:(NSCoder *)aDecoder;

@end

* NSCoding defined in Foundation Framework

Monday, March 19, 12

Page 47: Beginningi os part1-bobmccune

Conforming to the ContractAdopting a Protocol

@interface User : NSObject <NSCoding>

@property (nonatomic, copy) NSString *username;@property (nonatomic, copy) NSString *password;

@end

Monday, March 19, 12

Page 48: Beginningi os part1-bobmccune

Conforming to the ContractAdopting a Protocol

@interface User : NSObject <NSCoding>

@property (nonatomic, copy) NSString *username;@property (nonatomic, copy) NSString *password;

@end

Monday, March 19, 12

Page 49: Beginningi os part1-bobmccune

Conforming to the ContractAdopting a Protocol

@implementation User

-(id)initWithCoder:(NSCoder *)coder { if (self = [super init]) { self.username = [coder decodeObjectForKey:@"username"]; self.password = [coder decodeObjectForKey:@"password"]; } return self;}

-(void)encodeWithCoder:(NSCoder *)coder { [coder encodeObject:self.username forKey:@"username"]; [coder encodeObject:self.username forKey:@"password"];}

@end

Monday, March 19, 12

Page 50: Beginningi os part1-bobmccune

Time to Code!

Monday, March 19, 12

Page 51: Beginningi os part1-bobmccune

Using Cocoa Touch

Monday, March 19, 12

Page 52: Beginningi os part1-bobmccune

Cocoa Touch

• Core framework for non-UI functionality

• Operating System Classes• threading, archiving, filesystem

• Collections• Common collection types: arrays, dictionaries, sets

• Networking support

• XML Processing

Foundation Framework

Monday, March 19, 12

Page 53: Beginningi os part1-bobmccune

Cocoa Touch

• Framework for building iOS user interfaces

• User Interface Elements

• Tables, buttons, images, etc.

• Views and View Controllers

• Multitouch Event Handling

• High-level Drawing Routines

UIKit Framework

Monday, March 19, 12

Page 54: Beginningi os part1-bobmccune

Model, View, ControllerUnderstanding MVC

Model View

Controller

Monday, March 19, 12

Page 55: Beginningi os part1-bobmccune

The “V” in MVC

• Base class for iOS user interface components• Drawing and animation

• Layout and subview management

• Multitouch event handling

• Xcode’s Interface Builder used to build UI• Archived version of UI stored in XIB/NIB file

• Dynamically loaded at runtime by controller

• Can be created programmatically

UIView

Monday, March 19, 12

Page 56: Beginningi os part1-bobmccune

The “C” in MVC

• The heart of every iOS app

• Provides the “glue code” between the model and view

• Responsible for managing the view hierarchy and lifecycle

• Key view lifecycle methods:

UIViewController

- (void)loadView;- (void)viewDidLoad;- (void)viewDidUnload;

Monday, March 19, 12

Page 57: Beginningi os part1-bobmccune

Is view nil?

controller.view

View Controller

View loadView viewDidLoad

1) Overridden2) Loaded from NIB3) Return empty UIView

UIViewController: View Loading

Monday, March 19, 12

Page 58: Beginningi os part1-bobmccune

View Unloading

• didReceiveMemoryWarning• Called by OS when low memory encountered

• If possible, will release controller’s view

• Can override, but must call super

• viewDidUnload invoked if root view released• Override to release anything that can be

recreated in loadView/viewDidLoad

Dealing with low memory conditions

Monday, March 19, 12

Page 59: Beginningi os part1-bobmccune

Display-related Callbacks

viewWillAppear• Called immediately prior to being presented

viewDidAppear• Called upon view being added to window

viewWillDisappear• Called immediately before view is removed

from window or is covered by another viewviewDidDisappear

• Called after view is removed from window or is covered by another view

Monday, March 19, 12

Page 60: Beginningi os part1-bobmccune

Wiring the View and View ControllerOutlets and Actions

• Provides metadata to Interface Builder to allow connections between objects

• IBOutlet

• Property reference to XIB/NIB objects

• Null-defined C macro

• IBAction

• Used by Interface Builder to determine available actions

• Void-defined C macro

Monday, March 19, 12

Page 61: Beginningi os part1-bobmccune

Time to Code!

Monday, March 19, 12