Top Banner
Giuseppe Arici § The Preacher Objective-C L’ABC del Linguaggio
142

Objective-C

May 08, 2015

Download

Technology

pragmamark

L'ABC del linguaggio.
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Objective-C

Giuseppe Arici sect The Preacher

Objective-CLrsquoABC del Linguaggio

iOS Bootcamp

Giuseppe Arici

Apple iOS amp Mac OS X Addicted DeveloperSuperpartes Innovation Campus amp H-Farm

Group Founder amp Cocoa Preacher Pragma Mark ― pragmamarkorg

A Social amp Lazy Connected Node[ tt | in | fb | ] giuseppearici

Mail Forwarder amp Spammergiuseppearicigmailcom

Im n

ot a

Fanb

oy )

vCar

d rarr

gius

eppe

arici

com

iOS Bootcamp

Alzi la mano chi

iOS Bootcamp

Agenda

Storia amp Filosofia

Matematica amp Fisica

iOS Bootcamp

The History

iOS Bootcamp

1971 1981 1991 2001 2011

40 Years

iOS Bootcamp

1969 - 1973

Dennis Ritchie Bell Labs

iOS Bootcamp

1972 - 1980

Alan Kay Xerox PARC

iOS Bootcamp

1976

Steve Jobs amp Steve Wozniak

iOS Bootcamp

1979

Apple Team Xerox PARC

iOS Bootcamp

1980

Brad Cox amp Tom Love ITT

iOS Bootcamp

1981

Byte Magazine Agosto1981

iOS Bootcamp

The ldquoOOPCrdquo

1982

iOS Bootcamp

1983

StepStone (formerly PPI)

iOS Bootcamp

1986

OOP An Evolutionary Approach

iOS Bootcamp

1985

Steve Jobs John Sculley

iOS Bootcamp

1986

NeXT Computer (∡28deg)

iOS Bootcamp

1988

NeXT reg Objective-C StepStone

iOS Bootcamp

1991

WWW amp Doom amp Mathematica

NeXTcube

iOS Bootcamp

1993

NeXT + Sun = OpenStep API

ldquoJava Was Strongly Influenced by Objective-CrdquoPatrick Naughton co-creator of Java Programming Language

NSObject

iOS Bootcamp

1996

NeXT sube Apple

iOS Bootcamp

1997

Code Name ldquoRhapsodyrdquo

iOS Bootcamp

2001

Mac OS X v100

iOS Bootcamp

2006

Objective-C 20

prop

erty

fast

enu

mer

atio

n f

or in

optio

nal p

roto

col

garb

age

colle

ctio

n

OS

X

clas

s ex

tens

ions

new

run

time

iOS Bootcamp

2007

The iPhone

iOS Bootcamp

2008

The iPhone SDK

iOS Bootcamp

2005

Chris Lattner

Source httpnondotorgsabreResumehtml

Director and Architect Low-Level ToolsSeptember 2011 - Ongoing

Senior Manager and Architect Low-Level ToolsJune 2010 - September 2011

Senior Manager of Compilers and Low-Level Tools Compiler ArchitectSeptember 2009 - June 2010

Manager of Compilers and Low-Level Tools Compiler ArchitectJuly 2008 - September 2009

LLVM Compiler Group Manager and Compiler ArchitectDecember 2006 - July 2008

Senior Compiler Engineer and Tech LeadJune 2005 - December 2006

iOS Bootcamp

2007

LLVM Compiler Infrastructure

Source The Architecture of Open Source Applications httpwwwaosabookorgenllvmhtml

iOS Bootcamp

2009

Clang (Static Analyzer)

iOS Bootcamp

2009

^ Blocks amp GCD

iOS Bootcamp

2010

Xcode 4

iOS Bootcamp

2011

Automatic Reference Counting

Messaggio Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Modern Objective-CO

bjec

t lite

rals

Enum

s w

ith fi

xed

unde

rlyin

g ty

pe

Subs

crip

ting

met

hods

Uno

rder

ed m

etho

d de

clar

atio

ns

sy

nthe

size

by d

efau

lt

Boxe

d Ex

pres

sions

2012WWDC 2012 Session 405 Modern Objective-C by Patrick C Beard

iOS Bootcamp

TIOBE Top 10 July 2012

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Long Term Trends

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Objective-C

Source httpwwwtiobecomindexphppaperinfotpciObjective-Chtml

Programming Language of the Year

2011

iOS Bootcamp

Ipse dixit Tom Love C++

ldquoObjective-C and C++ both started from C but they went in two very different directions Which approach do you prefer now

Tom Therersquos the successful direction and then therersquos the approach that Bjarne took with C++ In one case it was a small simple mdash dare I say elegant mdash programming language that was very crisp and well defined In the other case it was a pretty ugly complicated difficult language that had some really troublesome features I think those are the distinctions between the twordquo

iOS Bootcamp

Intervallo

iOS Bootcamp

The Language

iOS Bootcamp

Fundamental Laws

iOS Bootcamp

A strict superset of C

bull Objective-C is not inspired by C language like Java or C

bull Objective-C is a strict superset of the C language

bull Objective-C has only added some concepts and their associated keywords

bull Like with C++ a well-written C program should be compile-able as Objective-C

bull Unlike with C++ there is no risk of incompatibility between C names and Objective-C keywords

iOS Bootcamp

A strict superset of C

( ) [ ] catchclassdefsdynamicencodeendfinallyimplementationinterfaceoptional

privatepropertyprotectedprotocolpublicrequiredselectorsynchronizedsynthesizethrowtry

SELIMPnil Nil

BOOLYESNOid typ

edef

selfsuper

hidde

n par

amete

rsinoutinoutbycopy

byrefonewaygettersetter

readwritereadonlyassignretain

copynonatomicstrongweak av

ailab

le in

parti

cular

cont

exts

iOS Bootcamp

Requirements

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 2: Objective-C

iOS Bootcamp

Giuseppe Arici

Apple iOS amp Mac OS X Addicted DeveloperSuperpartes Innovation Campus amp H-Farm

Group Founder amp Cocoa Preacher Pragma Mark ― pragmamarkorg

A Social amp Lazy Connected Node[ tt | in | fb | ] giuseppearici

Mail Forwarder amp Spammergiuseppearicigmailcom

Im n

ot a

Fanb

oy )

vCar

d rarr

gius

eppe

arici

com

iOS Bootcamp

Alzi la mano chi

iOS Bootcamp

Agenda

Storia amp Filosofia

Matematica amp Fisica

iOS Bootcamp

The History

iOS Bootcamp

1971 1981 1991 2001 2011

40 Years

iOS Bootcamp

1969 - 1973

Dennis Ritchie Bell Labs

iOS Bootcamp

1972 - 1980

Alan Kay Xerox PARC

iOS Bootcamp

1976

Steve Jobs amp Steve Wozniak

iOS Bootcamp

1979

Apple Team Xerox PARC

iOS Bootcamp

1980

Brad Cox amp Tom Love ITT

iOS Bootcamp

1981

Byte Magazine Agosto1981

iOS Bootcamp

The ldquoOOPCrdquo

1982

iOS Bootcamp

1983

StepStone (formerly PPI)

iOS Bootcamp

1986

OOP An Evolutionary Approach

iOS Bootcamp

1985

Steve Jobs John Sculley

iOS Bootcamp

1986

NeXT Computer (∡28deg)

iOS Bootcamp

1988

NeXT reg Objective-C StepStone

iOS Bootcamp

1991

WWW amp Doom amp Mathematica

NeXTcube

iOS Bootcamp

1993

NeXT + Sun = OpenStep API

ldquoJava Was Strongly Influenced by Objective-CrdquoPatrick Naughton co-creator of Java Programming Language

NSObject

iOS Bootcamp

1996

NeXT sube Apple

iOS Bootcamp

1997

Code Name ldquoRhapsodyrdquo

iOS Bootcamp

2001

Mac OS X v100

iOS Bootcamp

2006

Objective-C 20

prop

erty

fast

enu

mer

atio

n f

or in

optio

nal p

roto

col

garb

age

colle

ctio

n

OS

X

clas

s ex

tens

ions

new

run

time

iOS Bootcamp

2007

The iPhone

iOS Bootcamp

2008

The iPhone SDK

iOS Bootcamp

2005

Chris Lattner

Source httpnondotorgsabreResumehtml

Director and Architect Low-Level ToolsSeptember 2011 - Ongoing

Senior Manager and Architect Low-Level ToolsJune 2010 - September 2011

Senior Manager of Compilers and Low-Level Tools Compiler ArchitectSeptember 2009 - June 2010

Manager of Compilers and Low-Level Tools Compiler ArchitectJuly 2008 - September 2009

LLVM Compiler Group Manager and Compiler ArchitectDecember 2006 - July 2008

Senior Compiler Engineer and Tech LeadJune 2005 - December 2006

iOS Bootcamp

2007

LLVM Compiler Infrastructure

Source The Architecture of Open Source Applications httpwwwaosabookorgenllvmhtml

iOS Bootcamp

2009

Clang (Static Analyzer)

iOS Bootcamp

2009

^ Blocks amp GCD

iOS Bootcamp

2010

Xcode 4

iOS Bootcamp

2011

Automatic Reference Counting

Messaggio Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Modern Objective-CO

bjec

t lite

rals

Enum

s w

ith fi

xed

unde

rlyin

g ty

pe

Subs

crip

ting

met

hods

Uno

rder

ed m

etho

d de

clar

atio

ns

sy

nthe

size

by d

efau

lt

Boxe

d Ex

pres

sions

2012WWDC 2012 Session 405 Modern Objective-C by Patrick C Beard

iOS Bootcamp

TIOBE Top 10 July 2012

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Long Term Trends

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Objective-C

Source httpwwwtiobecomindexphppaperinfotpciObjective-Chtml

Programming Language of the Year

2011

iOS Bootcamp

Ipse dixit Tom Love C++

ldquoObjective-C and C++ both started from C but they went in two very different directions Which approach do you prefer now

Tom Therersquos the successful direction and then therersquos the approach that Bjarne took with C++ In one case it was a small simple mdash dare I say elegant mdash programming language that was very crisp and well defined In the other case it was a pretty ugly complicated difficult language that had some really troublesome features I think those are the distinctions between the twordquo

iOS Bootcamp

Intervallo

iOS Bootcamp

The Language

iOS Bootcamp

Fundamental Laws

iOS Bootcamp

A strict superset of C

bull Objective-C is not inspired by C language like Java or C

bull Objective-C is a strict superset of the C language

bull Objective-C has only added some concepts and their associated keywords

bull Like with C++ a well-written C program should be compile-able as Objective-C

bull Unlike with C++ there is no risk of incompatibility between C names and Objective-C keywords

iOS Bootcamp

A strict superset of C

( ) [ ] catchclassdefsdynamicencodeendfinallyimplementationinterfaceoptional

privatepropertyprotectedprotocolpublicrequiredselectorsynchronizedsynthesizethrowtry

SELIMPnil Nil

BOOLYESNOid typ

edef

selfsuper

hidde

n par

amete

rsinoutinoutbycopy

byrefonewaygettersetter

readwritereadonlyassignretain

copynonatomicstrongweak av

ailab

le in

parti

cular

cont

exts

iOS Bootcamp

Requirements

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 3: Objective-C

iOS Bootcamp

Alzi la mano chi

iOS Bootcamp

Agenda

Storia amp Filosofia

Matematica amp Fisica

iOS Bootcamp

The History

iOS Bootcamp

1971 1981 1991 2001 2011

40 Years

iOS Bootcamp

1969 - 1973

Dennis Ritchie Bell Labs

iOS Bootcamp

1972 - 1980

Alan Kay Xerox PARC

iOS Bootcamp

1976

Steve Jobs amp Steve Wozniak

iOS Bootcamp

1979

Apple Team Xerox PARC

iOS Bootcamp

1980

Brad Cox amp Tom Love ITT

iOS Bootcamp

1981

Byte Magazine Agosto1981

iOS Bootcamp

The ldquoOOPCrdquo

1982

iOS Bootcamp

1983

StepStone (formerly PPI)

iOS Bootcamp

1986

OOP An Evolutionary Approach

iOS Bootcamp

1985

Steve Jobs John Sculley

iOS Bootcamp

1986

NeXT Computer (∡28deg)

iOS Bootcamp

1988

NeXT reg Objective-C StepStone

iOS Bootcamp

1991

WWW amp Doom amp Mathematica

NeXTcube

iOS Bootcamp

1993

NeXT + Sun = OpenStep API

ldquoJava Was Strongly Influenced by Objective-CrdquoPatrick Naughton co-creator of Java Programming Language

NSObject

iOS Bootcamp

1996

NeXT sube Apple

iOS Bootcamp

1997

Code Name ldquoRhapsodyrdquo

iOS Bootcamp

2001

Mac OS X v100

iOS Bootcamp

2006

Objective-C 20

prop

erty

fast

enu

mer

atio

n f

or in

optio

nal p

roto

col

garb

age

colle

ctio

n

OS

X

clas

s ex

tens

ions

new

run

time

iOS Bootcamp

2007

The iPhone

iOS Bootcamp

2008

The iPhone SDK

iOS Bootcamp

2005

Chris Lattner

Source httpnondotorgsabreResumehtml

Director and Architect Low-Level ToolsSeptember 2011 - Ongoing

Senior Manager and Architect Low-Level ToolsJune 2010 - September 2011

Senior Manager of Compilers and Low-Level Tools Compiler ArchitectSeptember 2009 - June 2010

Manager of Compilers and Low-Level Tools Compiler ArchitectJuly 2008 - September 2009

LLVM Compiler Group Manager and Compiler ArchitectDecember 2006 - July 2008

Senior Compiler Engineer and Tech LeadJune 2005 - December 2006

iOS Bootcamp

2007

LLVM Compiler Infrastructure

Source The Architecture of Open Source Applications httpwwwaosabookorgenllvmhtml

iOS Bootcamp

2009

Clang (Static Analyzer)

iOS Bootcamp

2009

^ Blocks amp GCD

iOS Bootcamp

2010

Xcode 4

iOS Bootcamp

2011

Automatic Reference Counting

Messaggio Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Modern Objective-CO

bjec

t lite

rals

Enum

s w

ith fi

xed

unde

rlyin

g ty

pe

Subs

crip

ting

met

hods

Uno

rder

ed m

etho

d de

clar

atio

ns

sy

nthe

size

by d

efau

lt

Boxe

d Ex

pres

sions

2012WWDC 2012 Session 405 Modern Objective-C by Patrick C Beard

iOS Bootcamp

TIOBE Top 10 July 2012

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Long Term Trends

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Objective-C

Source httpwwwtiobecomindexphppaperinfotpciObjective-Chtml

Programming Language of the Year

2011

iOS Bootcamp

Ipse dixit Tom Love C++

ldquoObjective-C and C++ both started from C but they went in two very different directions Which approach do you prefer now

Tom Therersquos the successful direction and then therersquos the approach that Bjarne took with C++ In one case it was a small simple mdash dare I say elegant mdash programming language that was very crisp and well defined In the other case it was a pretty ugly complicated difficult language that had some really troublesome features I think those are the distinctions between the twordquo

iOS Bootcamp

Intervallo

iOS Bootcamp

The Language

iOS Bootcamp

Fundamental Laws

iOS Bootcamp

A strict superset of C

bull Objective-C is not inspired by C language like Java or C

bull Objective-C is a strict superset of the C language

bull Objective-C has only added some concepts and their associated keywords

bull Like with C++ a well-written C program should be compile-able as Objective-C

bull Unlike with C++ there is no risk of incompatibility between C names and Objective-C keywords

iOS Bootcamp

A strict superset of C

( ) [ ] catchclassdefsdynamicencodeendfinallyimplementationinterfaceoptional

privatepropertyprotectedprotocolpublicrequiredselectorsynchronizedsynthesizethrowtry

SELIMPnil Nil

BOOLYESNOid typ

edef

selfsuper

hidde

n par

amete

rsinoutinoutbycopy

byrefonewaygettersetter

readwritereadonlyassignretain

copynonatomicstrongweak av

ailab

le in

parti

cular

cont

exts

iOS Bootcamp

Requirements

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 4: Objective-C

iOS Bootcamp

Agenda

Storia amp Filosofia

Matematica amp Fisica

iOS Bootcamp

The History

iOS Bootcamp

1971 1981 1991 2001 2011

40 Years

iOS Bootcamp

1969 - 1973

Dennis Ritchie Bell Labs

iOS Bootcamp

1972 - 1980

Alan Kay Xerox PARC

iOS Bootcamp

1976

Steve Jobs amp Steve Wozniak

iOS Bootcamp

1979

Apple Team Xerox PARC

iOS Bootcamp

1980

Brad Cox amp Tom Love ITT

iOS Bootcamp

1981

Byte Magazine Agosto1981

iOS Bootcamp

The ldquoOOPCrdquo

1982

iOS Bootcamp

1983

StepStone (formerly PPI)

iOS Bootcamp

1986

OOP An Evolutionary Approach

iOS Bootcamp

1985

Steve Jobs John Sculley

iOS Bootcamp

1986

NeXT Computer (∡28deg)

iOS Bootcamp

1988

NeXT reg Objective-C StepStone

iOS Bootcamp

1991

WWW amp Doom amp Mathematica

NeXTcube

iOS Bootcamp

1993

NeXT + Sun = OpenStep API

ldquoJava Was Strongly Influenced by Objective-CrdquoPatrick Naughton co-creator of Java Programming Language

NSObject

iOS Bootcamp

1996

NeXT sube Apple

iOS Bootcamp

1997

Code Name ldquoRhapsodyrdquo

iOS Bootcamp

2001

Mac OS X v100

iOS Bootcamp

2006

Objective-C 20

prop

erty

fast

enu

mer

atio

n f

or in

optio

nal p

roto

col

garb

age

colle

ctio

n

OS

X

clas

s ex

tens

ions

new

run

time

iOS Bootcamp

2007

The iPhone

iOS Bootcamp

2008

The iPhone SDK

iOS Bootcamp

2005

Chris Lattner

Source httpnondotorgsabreResumehtml

Director and Architect Low-Level ToolsSeptember 2011 - Ongoing

Senior Manager and Architect Low-Level ToolsJune 2010 - September 2011

Senior Manager of Compilers and Low-Level Tools Compiler ArchitectSeptember 2009 - June 2010

Manager of Compilers and Low-Level Tools Compiler ArchitectJuly 2008 - September 2009

LLVM Compiler Group Manager and Compiler ArchitectDecember 2006 - July 2008

Senior Compiler Engineer and Tech LeadJune 2005 - December 2006

iOS Bootcamp

2007

LLVM Compiler Infrastructure

Source The Architecture of Open Source Applications httpwwwaosabookorgenllvmhtml

iOS Bootcamp

2009

Clang (Static Analyzer)

iOS Bootcamp

2009

^ Blocks amp GCD

iOS Bootcamp

2010

Xcode 4

iOS Bootcamp

2011

Automatic Reference Counting

Messaggio Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Modern Objective-CO

bjec

t lite

rals

Enum

s w

ith fi

xed

unde

rlyin

g ty

pe

Subs

crip

ting

met

hods

Uno

rder

ed m

etho

d de

clar

atio

ns

sy

nthe

size

by d

efau

lt

Boxe

d Ex

pres

sions

2012WWDC 2012 Session 405 Modern Objective-C by Patrick C Beard

iOS Bootcamp

TIOBE Top 10 July 2012

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Long Term Trends

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Objective-C

Source httpwwwtiobecomindexphppaperinfotpciObjective-Chtml

Programming Language of the Year

2011

iOS Bootcamp

Ipse dixit Tom Love C++

ldquoObjective-C and C++ both started from C but they went in two very different directions Which approach do you prefer now

Tom Therersquos the successful direction and then therersquos the approach that Bjarne took with C++ In one case it was a small simple mdash dare I say elegant mdash programming language that was very crisp and well defined In the other case it was a pretty ugly complicated difficult language that had some really troublesome features I think those are the distinctions between the twordquo

iOS Bootcamp

Intervallo

iOS Bootcamp

The Language

iOS Bootcamp

Fundamental Laws

iOS Bootcamp

A strict superset of C

bull Objective-C is not inspired by C language like Java or C

bull Objective-C is a strict superset of the C language

bull Objective-C has only added some concepts and their associated keywords

bull Like with C++ a well-written C program should be compile-able as Objective-C

bull Unlike with C++ there is no risk of incompatibility between C names and Objective-C keywords

iOS Bootcamp

A strict superset of C

( ) [ ] catchclassdefsdynamicencodeendfinallyimplementationinterfaceoptional

privatepropertyprotectedprotocolpublicrequiredselectorsynchronizedsynthesizethrowtry

SELIMPnil Nil

BOOLYESNOid typ

edef

selfsuper

hidde

n par

amete

rsinoutinoutbycopy

byrefonewaygettersetter

readwritereadonlyassignretain

copynonatomicstrongweak av

ailab

le in

parti

cular

cont

exts

iOS Bootcamp

Requirements

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 5: Objective-C

iOS Bootcamp

The History

iOS Bootcamp

1971 1981 1991 2001 2011

40 Years

iOS Bootcamp

1969 - 1973

Dennis Ritchie Bell Labs

iOS Bootcamp

1972 - 1980

Alan Kay Xerox PARC

iOS Bootcamp

1976

Steve Jobs amp Steve Wozniak

iOS Bootcamp

1979

Apple Team Xerox PARC

iOS Bootcamp

1980

Brad Cox amp Tom Love ITT

iOS Bootcamp

1981

Byte Magazine Agosto1981

iOS Bootcamp

The ldquoOOPCrdquo

1982

iOS Bootcamp

1983

StepStone (formerly PPI)

iOS Bootcamp

1986

OOP An Evolutionary Approach

iOS Bootcamp

1985

Steve Jobs John Sculley

iOS Bootcamp

1986

NeXT Computer (∡28deg)

iOS Bootcamp

1988

NeXT reg Objective-C StepStone

iOS Bootcamp

1991

WWW amp Doom amp Mathematica

NeXTcube

iOS Bootcamp

1993

NeXT + Sun = OpenStep API

ldquoJava Was Strongly Influenced by Objective-CrdquoPatrick Naughton co-creator of Java Programming Language

NSObject

iOS Bootcamp

1996

NeXT sube Apple

iOS Bootcamp

1997

Code Name ldquoRhapsodyrdquo

iOS Bootcamp

2001

Mac OS X v100

iOS Bootcamp

2006

Objective-C 20

prop

erty

fast

enu

mer

atio

n f

or in

optio

nal p

roto

col

garb

age

colle

ctio

n

OS

X

clas

s ex

tens

ions

new

run

time

iOS Bootcamp

2007

The iPhone

iOS Bootcamp

2008

The iPhone SDK

iOS Bootcamp

2005

Chris Lattner

Source httpnondotorgsabreResumehtml

Director and Architect Low-Level ToolsSeptember 2011 - Ongoing

Senior Manager and Architect Low-Level ToolsJune 2010 - September 2011

Senior Manager of Compilers and Low-Level Tools Compiler ArchitectSeptember 2009 - June 2010

Manager of Compilers and Low-Level Tools Compiler ArchitectJuly 2008 - September 2009

LLVM Compiler Group Manager and Compiler ArchitectDecember 2006 - July 2008

Senior Compiler Engineer and Tech LeadJune 2005 - December 2006

iOS Bootcamp

2007

LLVM Compiler Infrastructure

Source The Architecture of Open Source Applications httpwwwaosabookorgenllvmhtml

iOS Bootcamp

2009

Clang (Static Analyzer)

iOS Bootcamp

2009

^ Blocks amp GCD

iOS Bootcamp

2010

Xcode 4

iOS Bootcamp

2011

Automatic Reference Counting

Messaggio Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Modern Objective-CO

bjec

t lite

rals

Enum

s w

ith fi

xed

unde

rlyin

g ty

pe

Subs

crip

ting

met

hods

Uno

rder

ed m

etho

d de

clar

atio

ns

sy

nthe

size

by d

efau

lt

Boxe

d Ex

pres

sions

2012WWDC 2012 Session 405 Modern Objective-C by Patrick C Beard

iOS Bootcamp

TIOBE Top 10 July 2012

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Long Term Trends

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Objective-C

Source httpwwwtiobecomindexphppaperinfotpciObjective-Chtml

Programming Language of the Year

2011

iOS Bootcamp

Ipse dixit Tom Love C++

ldquoObjective-C and C++ both started from C but they went in two very different directions Which approach do you prefer now

Tom Therersquos the successful direction and then therersquos the approach that Bjarne took with C++ In one case it was a small simple mdash dare I say elegant mdash programming language that was very crisp and well defined In the other case it was a pretty ugly complicated difficult language that had some really troublesome features I think those are the distinctions between the twordquo

iOS Bootcamp

Intervallo

iOS Bootcamp

The Language

iOS Bootcamp

Fundamental Laws

iOS Bootcamp

A strict superset of C

bull Objective-C is not inspired by C language like Java or C

bull Objective-C is a strict superset of the C language

bull Objective-C has only added some concepts and their associated keywords

bull Like with C++ a well-written C program should be compile-able as Objective-C

bull Unlike with C++ there is no risk of incompatibility between C names and Objective-C keywords

iOS Bootcamp

A strict superset of C

( ) [ ] catchclassdefsdynamicencodeendfinallyimplementationinterfaceoptional

privatepropertyprotectedprotocolpublicrequiredselectorsynchronizedsynthesizethrowtry

SELIMPnil Nil

BOOLYESNOid typ

edef

selfsuper

hidde

n par

amete

rsinoutinoutbycopy

byrefonewaygettersetter

readwritereadonlyassignretain

copynonatomicstrongweak av

ailab

le in

parti

cular

cont

exts

iOS Bootcamp

Requirements

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 6: Objective-C

iOS Bootcamp

1971 1981 1991 2001 2011

40 Years

iOS Bootcamp

1969 - 1973

Dennis Ritchie Bell Labs

iOS Bootcamp

1972 - 1980

Alan Kay Xerox PARC

iOS Bootcamp

1976

Steve Jobs amp Steve Wozniak

iOS Bootcamp

1979

Apple Team Xerox PARC

iOS Bootcamp

1980

Brad Cox amp Tom Love ITT

iOS Bootcamp

1981

Byte Magazine Agosto1981

iOS Bootcamp

The ldquoOOPCrdquo

1982

iOS Bootcamp

1983

StepStone (formerly PPI)

iOS Bootcamp

1986

OOP An Evolutionary Approach

iOS Bootcamp

1985

Steve Jobs John Sculley

iOS Bootcamp

1986

NeXT Computer (∡28deg)

iOS Bootcamp

1988

NeXT reg Objective-C StepStone

iOS Bootcamp

1991

WWW amp Doom amp Mathematica

NeXTcube

iOS Bootcamp

1993

NeXT + Sun = OpenStep API

ldquoJava Was Strongly Influenced by Objective-CrdquoPatrick Naughton co-creator of Java Programming Language

NSObject

iOS Bootcamp

1996

NeXT sube Apple

iOS Bootcamp

1997

Code Name ldquoRhapsodyrdquo

iOS Bootcamp

2001

Mac OS X v100

iOS Bootcamp

2006

Objective-C 20

prop

erty

fast

enu

mer

atio

n f

or in

optio

nal p

roto

col

garb

age

colle

ctio

n

OS

X

clas

s ex

tens

ions

new

run

time

iOS Bootcamp

2007

The iPhone

iOS Bootcamp

2008

The iPhone SDK

iOS Bootcamp

2005

Chris Lattner

Source httpnondotorgsabreResumehtml

Director and Architect Low-Level ToolsSeptember 2011 - Ongoing

Senior Manager and Architect Low-Level ToolsJune 2010 - September 2011

Senior Manager of Compilers and Low-Level Tools Compiler ArchitectSeptember 2009 - June 2010

Manager of Compilers and Low-Level Tools Compiler ArchitectJuly 2008 - September 2009

LLVM Compiler Group Manager and Compiler ArchitectDecember 2006 - July 2008

Senior Compiler Engineer and Tech LeadJune 2005 - December 2006

iOS Bootcamp

2007

LLVM Compiler Infrastructure

Source The Architecture of Open Source Applications httpwwwaosabookorgenllvmhtml

iOS Bootcamp

2009

Clang (Static Analyzer)

iOS Bootcamp

2009

^ Blocks amp GCD

iOS Bootcamp

2010

Xcode 4

iOS Bootcamp

2011

Automatic Reference Counting

Messaggio Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Modern Objective-CO

bjec

t lite

rals

Enum

s w

ith fi

xed

unde

rlyin

g ty

pe

Subs

crip

ting

met

hods

Uno

rder

ed m

etho

d de

clar

atio

ns

sy

nthe

size

by d

efau

lt

Boxe

d Ex

pres

sions

2012WWDC 2012 Session 405 Modern Objective-C by Patrick C Beard

iOS Bootcamp

TIOBE Top 10 July 2012

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Long Term Trends

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Objective-C

Source httpwwwtiobecomindexphppaperinfotpciObjective-Chtml

Programming Language of the Year

2011

iOS Bootcamp

Ipse dixit Tom Love C++

ldquoObjective-C and C++ both started from C but they went in two very different directions Which approach do you prefer now

Tom Therersquos the successful direction and then therersquos the approach that Bjarne took with C++ In one case it was a small simple mdash dare I say elegant mdash programming language that was very crisp and well defined In the other case it was a pretty ugly complicated difficult language that had some really troublesome features I think those are the distinctions between the twordquo

iOS Bootcamp

Intervallo

iOS Bootcamp

The Language

iOS Bootcamp

Fundamental Laws

iOS Bootcamp

A strict superset of C

bull Objective-C is not inspired by C language like Java or C

bull Objective-C is a strict superset of the C language

bull Objective-C has only added some concepts and their associated keywords

bull Like with C++ a well-written C program should be compile-able as Objective-C

bull Unlike with C++ there is no risk of incompatibility between C names and Objective-C keywords

iOS Bootcamp

A strict superset of C

( ) [ ] catchclassdefsdynamicencodeendfinallyimplementationinterfaceoptional

privatepropertyprotectedprotocolpublicrequiredselectorsynchronizedsynthesizethrowtry

SELIMPnil Nil

BOOLYESNOid typ

edef

selfsuper

hidde

n par

amete

rsinoutinoutbycopy

byrefonewaygettersetter

readwritereadonlyassignretain

copynonatomicstrongweak av

ailab

le in

parti

cular

cont

exts

iOS Bootcamp

Requirements

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 7: Objective-C

iOS Bootcamp

1969 - 1973

Dennis Ritchie Bell Labs

iOS Bootcamp

1972 - 1980

Alan Kay Xerox PARC

iOS Bootcamp

1976

Steve Jobs amp Steve Wozniak

iOS Bootcamp

1979

Apple Team Xerox PARC

iOS Bootcamp

1980

Brad Cox amp Tom Love ITT

iOS Bootcamp

1981

Byte Magazine Agosto1981

iOS Bootcamp

The ldquoOOPCrdquo

1982

iOS Bootcamp

1983

StepStone (formerly PPI)

iOS Bootcamp

1986

OOP An Evolutionary Approach

iOS Bootcamp

1985

Steve Jobs John Sculley

iOS Bootcamp

1986

NeXT Computer (∡28deg)

iOS Bootcamp

1988

NeXT reg Objective-C StepStone

iOS Bootcamp

1991

WWW amp Doom amp Mathematica

NeXTcube

iOS Bootcamp

1993

NeXT + Sun = OpenStep API

ldquoJava Was Strongly Influenced by Objective-CrdquoPatrick Naughton co-creator of Java Programming Language

NSObject

iOS Bootcamp

1996

NeXT sube Apple

iOS Bootcamp

1997

Code Name ldquoRhapsodyrdquo

iOS Bootcamp

2001

Mac OS X v100

iOS Bootcamp

2006

Objective-C 20

prop

erty

fast

enu

mer

atio

n f

or in

optio

nal p

roto

col

garb

age

colle

ctio

n

OS

X

clas

s ex

tens

ions

new

run

time

iOS Bootcamp

2007

The iPhone

iOS Bootcamp

2008

The iPhone SDK

iOS Bootcamp

2005

Chris Lattner

Source httpnondotorgsabreResumehtml

Director and Architect Low-Level ToolsSeptember 2011 - Ongoing

Senior Manager and Architect Low-Level ToolsJune 2010 - September 2011

Senior Manager of Compilers and Low-Level Tools Compiler ArchitectSeptember 2009 - June 2010

Manager of Compilers and Low-Level Tools Compiler ArchitectJuly 2008 - September 2009

LLVM Compiler Group Manager and Compiler ArchitectDecember 2006 - July 2008

Senior Compiler Engineer and Tech LeadJune 2005 - December 2006

iOS Bootcamp

2007

LLVM Compiler Infrastructure

Source The Architecture of Open Source Applications httpwwwaosabookorgenllvmhtml

iOS Bootcamp

2009

Clang (Static Analyzer)

iOS Bootcamp

2009

^ Blocks amp GCD

iOS Bootcamp

2010

Xcode 4

iOS Bootcamp

2011

Automatic Reference Counting

Messaggio Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Modern Objective-CO

bjec

t lite

rals

Enum

s w

ith fi

xed

unde

rlyin

g ty

pe

Subs

crip

ting

met

hods

Uno

rder

ed m

etho

d de

clar

atio

ns

sy

nthe

size

by d

efau

lt

Boxe

d Ex

pres

sions

2012WWDC 2012 Session 405 Modern Objective-C by Patrick C Beard

iOS Bootcamp

TIOBE Top 10 July 2012

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Long Term Trends

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Objective-C

Source httpwwwtiobecomindexphppaperinfotpciObjective-Chtml

Programming Language of the Year

2011

iOS Bootcamp

Ipse dixit Tom Love C++

ldquoObjective-C and C++ both started from C but they went in two very different directions Which approach do you prefer now

Tom Therersquos the successful direction and then therersquos the approach that Bjarne took with C++ In one case it was a small simple mdash dare I say elegant mdash programming language that was very crisp and well defined In the other case it was a pretty ugly complicated difficult language that had some really troublesome features I think those are the distinctions between the twordquo

iOS Bootcamp

Intervallo

iOS Bootcamp

The Language

iOS Bootcamp

Fundamental Laws

iOS Bootcamp

A strict superset of C

bull Objective-C is not inspired by C language like Java or C

bull Objective-C is a strict superset of the C language

bull Objective-C has only added some concepts and their associated keywords

bull Like with C++ a well-written C program should be compile-able as Objective-C

bull Unlike with C++ there is no risk of incompatibility between C names and Objective-C keywords

iOS Bootcamp

A strict superset of C

( ) [ ] catchclassdefsdynamicencodeendfinallyimplementationinterfaceoptional

privatepropertyprotectedprotocolpublicrequiredselectorsynchronizedsynthesizethrowtry

SELIMPnil Nil

BOOLYESNOid typ

edef

selfsuper

hidde

n par

amete

rsinoutinoutbycopy

byrefonewaygettersetter

readwritereadonlyassignretain

copynonatomicstrongweak av

ailab

le in

parti

cular

cont

exts

iOS Bootcamp

Requirements

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 8: Objective-C

iOS Bootcamp

1972 - 1980

Alan Kay Xerox PARC

iOS Bootcamp

1976

Steve Jobs amp Steve Wozniak

iOS Bootcamp

1979

Apple Team Xerox PARC

iOS Bootcamp

1980

Brad Cox amp Tom Love ITT

iOS Bootcamp

1981

Byte Magazine Agosto1981

iOS Bootcamp

The ldquoOOPCrdquo

1982

iOS Bootcamp

1983

StepStone (formerly PPI)

iOS Bootcamp

1986

OOP An Evolutionary Approach

iOS Bootcamp

1985

Steve Jobs John Sculley

iOS Bootcamp

1986

NeXT Computer (∡28deg)

iOS Bootcamp

1988

NeXT reg Objective-C StepStone

iOS Bootcamp

1991

WWW amp Doom amp Mathematica

NeXTcube

iOS Bootcamp

1993

NeXT + Sun = OpenStep API

ldquoJava Was Strongly Influenced by Objective-CrdquoPatrick Naughton co-creator of Java Programming Language

NSObject

iOS Bootcamp

1996

NeXT sube Apple

iOS Bootcamp

1997

Code Name ldquoRhapsodyrdquo

iOS Bootcamp

2001

Mac OS X v100

iOS Bootcamp

2006

Objective-C 20

prop

erty

fast

enu

mer

atio

n f

or in

optio

nal p

roto

col

garb

age

colle

ctio

n

OS

X

clas

s ex

tens

ions

new

run

time

iOS Bootcamp

2007

The iPhone

iOS Bootcamp

2008

The iPhone SDK

iOS Bootcamp

2005

Chris Lattner

Source httpnondotorgsabreResumehtml

Director and Architect Low-Level ToolsSeptember 2011 - Ongoing

Senior Manager and Architect Low-Level ToolsJune 2010 - September 2011

Senior Manager of Compilers and Low-Level Tools Compiler ArchitectSeptember 2009 - June 2010

Manager of Compilers and Low-Level Tools Compiler ArchitectJuly 2008 - September 2009

LLVM Compiler Group Manager and Compiler ArchitectDecember 2006 - July 2008

Senior Compiler Engineer and Tech LeadJune 2005 - December 2006

iOS Bootcamp

2007

LLVM Compiler Infrastructure

Source The Architecture of Open Source Applications httpwwwaosabookorgenllvmhtml

iOS Bootcamp

2009

Clang (Static Analyzer)

iOS Bootcamp

2009

^ Blocks amp GCD

iOS Bootcamp

2010

Xcode 4

iOS Bootcamp

2011

Automatic Reference Counting

Messaggio Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Modern Objective-CO

bjec

t lite

rals

Enum

s w

ith fi

xed

unde

rlyin

g ty

pe

Subs

crip

ting

met

hods

Uno

rder

ed m

etho

d de

clar

atio

ns

sy

nthe

size

by d

efau

lt

Boxe

d Ex

pres

sions

2012WWDC 2012 Session 405 Modern Objective-C by Patrick C Beard

iOS Bootcamp

TIOBE Top 10 July 2012

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Long Term Trends

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Objective-C

Source httpwwwtiobecomindexphppaperinfotpciObjective-Chtml

Programming Language of the Year

2011

iOS Bootcamp

Ipse dixit Tom Love C++

ldquoObjective-C and C++ both started from C but they went in two very different directions Which approach do you prefer now

Tom Therersquos the successful direction and then therersquos the approach that Bjarne took with C++ In one case it was a small simple mdash dare I say elegant mdash programming language that was very crisp and well defined In the other case it was a pretty ugly complicated difficult language that had some really troublesome features I think those are the distinctions between the twordquo

iOS Bootcamp

Intervallo

iOS Bootcamp

The Language

iOS Bootcamp

Fundamental Laws

iOS Bootcamp

A strict superset of C

bull Objective-C is not inspired by C language like Java or C

bull Objective-C is a strict superset of the C language

bull Objective-C has only added some concepts and their associated keywords

bull Like with C++ a well-written C program should be compile-able as Objective-C

bull Unlike with C++ there is no risk of incompatibility between C names and Objective-C keywords

iOS Bootcamp

A strict superset of C

( ) [ ] catchclassdefsdynamicencodeendfinallyimplementationinterfaceoptional

privatepropertyprotectedprotocolpublicrequiredselectorsynchronizedsynthesizethrowtry

SELIMPnil Nil

BOOLYESNOid typ

edef

selfsuper

hidde

n par

amete

rsinoutinoutbycopy

byrefonewaygettersetter

readwritereadonlyassignretain

copynonatomicstrongweak av

ailab

le in

parti

cular

cont

exts

iOS Bootcamp

Requirements

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 9: Objective-C

iOS Bootcamp

1976

Steve Jobs amp Steve Wozniak

iOS Bootcamp

1979

Apple Team Xerox PARC

iOS Bootcamp

1980

Brad Cox amp Tom Love ITT

iOS Bootcamp

1981

Byte Magazine Agosto1981

iOS Bootcamp

The ldquoOOPCrdquo

1982

iOS Bootcamp

1983

StepStone (formerly PPI)

iOS Bootcamp

1986

OOP An Evolutionary Approach

iOS Bootcamp

1985

Steve Jobs John Sculley

iOS Bootcamp

1986

NeXT Computer (∡28deg)

iOS Bootcamp

1988

NeXT reg Objective-C StepStone

iOS Bootcamp

1991

WWW amp Doom amp Mathematica

NeXTcube

iOS Bootcamp

1993

NeXT + Sun = OpenStep API

ldquoJava Was Strongly Influenced by Objective-CrdquoPatrick Naughton co-creator of Java Programming Language

NSObject

iOS Bootcamp

1996

NeXT sube Apple

iOS Bootcamp

1997

Code Name ldquoRhapsodyrdquo

iOS Bootcamp

2001

Mac OS X v100

iOS Bootcamp

2006

Objective-C 20

prop

erty

fast

enu

mer

atio

n f

or in

optio

nal p

roto

col

garb

age

colle

ctio

n

OS

X

clas

s ex

tens

ions

new

run

time

iOS Bootcamp

2007

The iPhone

iOS Bootcamp

2008

The iPhone SDK

iOS Bootcamp

2005

Chris Lattner

Source httpnondotorgsabreResumehtml

Director and Architect Low-Level ToolsSeptember 2011 - Ongoing

Senior Manager and Architect Low-Level ToolsJune 2010 - September 2011

Senior Manager of Compilers and Low-Level Tools Compiler ArchitectSeptember 2009 - June 2010

Manager of Compilers and Low-Level Tools Compiler ArchitectJuly 2008 - September 2009

LLVM Compiler Group Manager and Compiler ArchitectDecember 2006 - July 2008

Senior Compiler Engineer and Tech LeadJune 2005 - December 2006

iOS Bootcamp

2007

LLVM Compiler Infrastructure

Source The Architecture of Open Source Applications httpwwwaosabookorgenllvmhtml

iOS Bootcamp

2009

Clang (Static Analyzer)

iOS Bootcamp

2009

^ Blocks amp GCD

iOS Bootcamp

2010

Xcode 4

iOS Bootcamp

2011

Automatic Reference Counting

Messaggio Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Modern Objective-CO

bjec

t lite

rals

Enum

s w

ith fi

xed

unde

rlyin

g ty

pe

Subs

crip

ting

met

hods

Uno

rder

ed m

etho

d de

clar

atio

ns

sy

nthe

size

by d

efau

lt

Boxe

d Ex

pres

sions

2012WWDC 2012 Session 405 Modern Objective-C by Patrick C Beard

iOS Bootcamp

TIOBE Top 10 July 2012

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Long Term Trends

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Objective-C

Source httpwwwtiobecomindexphppaperinfotpciObjective-Chtml

Programming Language of the Year

2011

iOS Bootcamp

Ipse dixit Tom Love C++

ldquoObjective-C and C++ both started from C but they went in two very different directions Which approach do you prefer now

Tom Therersquos the successful direction and then therersquos the approach that Bjarne took with C++ In one case it was a small simple mdash dare I say elegant mdash programming language that was very crisp and well defined In the other case it was a pretty ugly complicated difficult language that had some really troublesome features I think those are the distinctions between the twordquo

iOS Bootcamp

Intervallo

iOS Bootcamp

The Language

iOS Bootcamp

Fundamental Laws

iOS Bootcamp

A strict superset of C

bull Objective-C is not inspired by C language like Java or C

bull Objective-C is a strict superset of the C language

bull Objective-C has only added some concepts and their associated keywords

bull Like with C++ a well-written C program should be compile-able as Objective-C

bull Unlike with C++ there is no risk of incompatibility between C names and Objective-C keywords

iOS Bootcamp

A strict superset of C

( ) [ ] catchclassdefsdynamicencodeendfinallyimplementationinterfaceoptional

privatepropertyprotectedprotocolpublicrequiredselectorsynchronizedsynthesizethrowtry

SELIMPnil Nil

BOOLYESNOid typ

edef

selfsuper

hidde

n par

amete

rsinoutinoutbycopy

byrefonewaygettersetter

readwritereadonlyassignretain

copynonatomicstrongweak av

ailab

le in

parti

cular

cont

exts

iOS Bootcamp

Requirements

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 10: Objective-C

iOS Bootcamp

1979

Apple Team Xerox PARC

iOS Bootcamp

1980

Brad Cox amp Tom Love ITT

iOS Bootcamp

1981

Byte Magazine Agosto1981

iOS Bootcamp

The ldquoOOPCrdquo

1982

iOS Bootcamp

1983

StepStone (formerly PPI)

iOS Bootcamp

1986

OOP An Evolutionary Approach

iOS Bootcamp

1985

Steve Jobs John Sculley

iOS Bootcamp

1986

NeXT Computer (∡28deg)

iOS Bootcamp

1988

NeXT reg Objective-C StepStone

iOS Bootcamp

1991

WWW amp Doom amp Mathematica

NeXTcube

iOS Bootcamp

1993

NeXT + Sun = OpenStep API

ldquoJava Was Strongly Influenced by Objective-CrdquoPatrick Naughton co-creator of Java Programming Language

NSObject

iOS Bootcamp

1996

NeXT sube Apple

iOS Bootcamp

1997

Code Name ldquoRhapsodyrdquo

iOS Bootcamp

2001

Mac OS X v100

iOS Bootcamp

2006

Objective-C 20

prop

erty

fast

enu

mer

atio

n f

or in

optio

nal p

roto

col

garb

age

colle

ctio

n

OS

X

clas

s ex

tens

ions

new

run

time

iOS Bootcamp

2007

The iPhone

iOS Bootcamp

2008

The iPhone SDK

iOS Bootcamp

2005

Chris Lattner

Source httpnondotorgsabreResumehtml

Director and Architect Low-Level ToolsSeptember 2011 - Ongoing

Senior Manager and Architect Low-Level ToolsJune 2010 - September 2011

Senior Manager of Compilers and Low-Level Tools Compiler ArchitectSeptember 2009 - June 2010

Manager of Compilers and Low-Level Tools Compiler ArchitectJuly 2008 - September 2009

LLVM Compiler Group Manager and Compiler ArchitectDecember 2006 - July 2008

Senior Compiler Engineer and Tech LeadJune 2005 - December 2006

iOS Bootcamp

2007

LLVM Compiler Infrastructure

Source The Architecture of Open Source Applications httpwwwaosabookorgenllvmhtml

iOS Bootcamp

2009

Clang (Static Analyzer)

iOS Bootcamp

2009

^ Blocks amp GCD

iOS Bootcamp

2010

Xcode 4

iOS Bootcamp

2011

Automatic Reference Counting

Messaggio Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Modern Objective-CO

bjec

t lite

rals

Enum

s w

ith fi

xed

unde

rlyin

g ty

pe

Subs

crip

ting

met

hods

Uno

rder

ed m

etho

d de

clar

atio

ns

sy

nthe

size

by d

efau

lt

Boxe

d Ex

pres

sions

2012WWDC 2012 Session 405 Modern Objective-C by Patrick C Beard

iOS Bootcamp

TIOBE Top 10 July 2012

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Long Term Trends

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Objective-C

Source httpwwwtiobecomindexphppaperinfotpciObjective-Chtml

Programming Language of the Year

2011

iOS Bootcamp

Ipse dixit Tom Love C++

ldquoObjective-C and C++ both started from C but they went in two very different directions Which approach do you prefer now

Tom Therersquos the successful direction and then therersquos the approach that Bjarne took with C++ In one case it was a small simple mdash dare I say elegant mdash programming language that was very crisp and well defined In the other case it was a pretty ugly complicated difficult language that had some really troublesome features I think those are the distinctions between the twordquo

iOS Bootcamp

Intervallo

iOS Bootcamp

The Language

iOS Bootcamp

Fundamental Laws

iOS Bootcamp

A strict superset of C

bull Objective-C is not inspired by C language like Java or C

bull Objective-C is a strict superset of the C language

bull Objective-C has only added some concepts and their associated keywords

bull Like with C++ a well-written C program should be compile-able as Objective-C

bull Unlike with C++ there is no risk of incompatibility between C names and Objective-C keywords

iOS Bootcamp

A strict superset of C

( ) [ ] catchclassdefsdynamicencodeendfinallyimplementationinterfaceoptional

privatepropertyprotectedprotocolpublicrequiredselectorsynchronizedsynthesizethrowtry

SELIMPnil Nil

BOOLYESNOid typ

edef

selfsuper

hidde

n par

amete

rsinoutinoutbycopy

byrefonewaygettersetter

readwritereadonlyassignretain

copynonatomicstrongweak av

ailab

le in

parti

cular

cont

exts

iOS Bootcamp

Requirements

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 11: Objective-C

iOS Bootcamp

1980

Brad Cox amp Tom Love ITT

iOS Bootcamp

1981

Byte Magazine Agosto1981

iOS Bootcamp

The ldquoOOPCrdquo

1982

iOS Bootcamp

1983

StepStone (formerly PPI)

iOS Bootcamp

1986

OOP An Evolutionary Approach

iOS Bootcamp

1985

Steve Jobs John Sculley

iOS Bootcamp

1986

NeXT Computer (∡28deg)

iOS Bootcamp

1988

NeXT reg Objective-C StepStone

iOS Bootcamp

1991

WWW amp Doom amp Mathematica

NeXTcube

iOS Bootcamp

1993

NeXT + Sun = OpenStep API

ldquoJava Was Strongly Influenced by Objective-CrdquoPatrick Naughton co-creator of Java Programming Language

NSObject

iOS Bootcamp

1996

NeXT sube Apple

iOS Bootcamp

1997

Code Name ldquoRhapsodyrdquo

iOS Bootcamp

2001

Mac OS X v100

iOS Bootcamp

2006

Objective-C 20

prop

erty

fast

enu

mer

atio

n f

or in

optio

nal p

roto

col

garb

age

colle

ctio

n

OS

X

clas

s ex

tens

ions

new

run

time

iOS Bootcamp

2007

The iPhone

iOS Bootcamp

2008

The iPhone SDK

iOS Bootcamp

2005

Chris Lattner

Source httpnondotorgsabreResumehtml

Director and Architect Low-Level ToolsSeptember 2011 - Ongoing

Senior Manager and Architect Low-Level ToolsJune 2010 - September 2011

Senior Manager of Compilers and Low-Level Tools Compiler ArchitectSeptember 2009 - June 2010

Manager of Compilers and Low-Level Tools Compiler ArchitectJuly 2008 - September 2009

LLVM Compiler Group Manager and Compiler ArchitectDecember 2006 - July 2008

Senior Compiler Engineer and Tech LeadJune 2005 - December 2006

iOS Bootcamp

2007

LLVM Compiler Infrastructure

Source The Architecture of Open Source Applications httpwwwaosabookorgenllvmhtml

iOS Bootcamp

2009

Clang (Static Analyzer)

iOS Bootcamp

2009

^ Blocks amp GCD

iOS Bootcamp

2010

Xcode 4

iOS Bootcamp

2011

Automatic Reference Counting

Messaggio Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Modern Objective-CO

bjec

t lite

rals

Enum

s w

ith fi

xed

unde

rlyin

g ty

pe

Subs

crip

ting

met

hods

Uno

rder

ed m

etho

d de

clar

atio

ns

sy

nthe

size

by d

efau

lt

Boxe

d Ex

pres

sions

2012WWDC 2012 Session 405 Modern Objective-C by Patrick C Beard

iOS Bootcamp

TIOBE Top 10 July 2012

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Long Term Trends

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Objective-C

Source httpwwwtiobecomindexphppaperinfotpciObjective-Chtml

Programming Language of the Year

2011

iOS Bootcamp

Ipse dixit Tom Love C++

ldquoObjective-C and C++ both started from C but they went in two very different directions Which approach do you prefer now

Tom Therersquos the successful direction and then therersquos the approach that Bjarne took with C++ In one case it was a small simple mdash dare I say elegant mdash programming language that was very crisp and well defined In the other case it was a pretty ugly complicated difficult language that had some really troublesome features I think those are the distinctions between the twordquo

iOS Bootcamp

Intervallo

iOS Bootcamp

The Language

iOS Bootcamp

Fundamental Laws

iOS Bootcamp

A strict superset of C

bull Objective-C is not inspired by C language like Java or C

bull Objective-C is a strict superset of the C language

bull Objective-C has only added some concepts and their associated keywords

bull Like with C++ a well-written C program should be compile-able as Objective-C

bull Unlike with C++ there is no risk of incompatibility between C names and Objective-C keywords

iOS Bootcamp

A strict superset of C

( ) [ ] catchclassdefsdynamicencodeendfinallyimplementationinterfaceoptional

privatepropertyprotectedprotocolpublicrequiredselectorsynchronizedsynthesizethrowtry

SELIMPnil Nil

BOOLYESNOid typ

edef

selfsuper

hidde

n par

amete

rsinoutinoutbycopy

byrefonewaygettersetter

readwritereadonlyassignretain

copynonatomicstrongweak av

ailab

le in

parti

cular

cont

exts

iOS Bootcamp

Requirements

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 12: Objective-C

iOS Bootcamp

1981

Byte Magazine Agosto1981

iOS Bootcamp

The ldquoOOPCrdquo

1982

iOS Bootcamp

1983

StepStone (formerly PPI)

iOS Bootcamp

1986

OOP An Evolutionary Approach

iOS Bootcamp

1985

Steve Jobs John Sculley

iOS Bootcamp

1986

NeXT Computer (∡28deg)

iOS Bootcamp

1988

NeXT reg Objective-C StepStone

iOS Bootcamp

1991

WWW amp Doom amp Mathematica

NeXTcube

iOS Bootcamp

1993

NeXT + Sun = OpenStep API

ldquoJava Was Strongly Influenced by Objective-CrdquoPatrick Naughton co-creator of Java Programming Language

NSObject

iOS Bootcamp

1996

NeXT sube Apple

iOS Bootcamp

1997

Code Name ldquoRhapsodyrdquo

iOS Bootcamp

2001

Mac OS X v100

iOS Bootcamp

2006

Objective-C 20

prop

erty

fast

enu

mer

atio

n f

or in

optio

nal p

roto

col

garb

age

colle

ctio

n

OS

X

clas

s ex

tens

ions

new

run

time

iOS Bootcamp

2007

The iPhone

iOS Bootcamp

2008

The iPhone SDK

iOS Bootcamp

2005

Chris Lattner

Source httpnondotorgsabreResumehtml

Director and Architect Low-Level ToolsSeptember 2011 - Ongoing

Senior Manager and Architect Low-Level ToolsJune 2010 - September 2011

Senior Manager of Compilers and Low-Level Tools Compiler ArchitectSeptember 2009 - June 2010

Manager of Compilers and Low-Level Tools Compiler ArchitectJuly 2008 - September 2009

LLVM Compiler Group Manager and Compiler ArchitectDecember 2006 - July 2008

Senior Compiler Engineer and Tech LeadJune 2005 - December 2006

iOS Bootcamp

2007

LLVM Compiler Infrastructure

Source The Architecture of Open Source Applications httpwwwaosabookorgenllvmhtml

iOS Bootcamp

2009

Clang (Static Analyzer)

iOS Bootcamp

2009

^ Blocks amp GCD

iOS Bootcamp

2010

Xcode 4

iOS Bootcamp

2011

Automatic Reference Counting

Messaggio Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Modern Objective-CO

bjec

t lite

rals

Enum

s w

ith fi

xed

unde

rlyin

g ty

pe

Subs

crip

ting

met

hods

Uno

rder

ed m

etho

d de

clar

atio

ns

sy

nthe

size

by d

efau

lt

Boxe

d Ex

pres

sions

2012WWDC 2012 Session 405 Modern Objective-C by Patrick C Beard

iOS Bootcamp

TIOBE Top 10 July 2012

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Long Term Trends

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Objective-C

Source httpwwwtiobecomindexphppaperinfotpciObjective-Chtml

Programming Language of the Year

2011

iOS Bootcamp

Ipse dixit Tom Love C++

ldquoObjective-C and C++ both started from C but they went in two very different directions Which approach do you prefer now

Tom Therersquos the successful direction and then therersquos the approach that Bjarne took with C++ In one case it was a small simple mdash dare I say elegant mdash programming language that was very crisp and well defined In the other case it was a pretty ugly complicated difficult language that had some really troublesome features I think those are the distinctions between the twordquo

iOS Bootcamp

Intervallo

iOS Bootcamp

The Language

iOS Bootcamp

Fundamental Laws

iOS Bootcamp

A strict superset of C

bull Objective-C is not inspired by C language like Java or C

bull Objective-C is a strict superset of the C language

bull Objective-C has only added some concepts and their associated keywords

bull Like with C++ a well-written C program should be compile-able as Objective-C

bull Unlike with C++ there is no risk of incompatibility between C names and Objective-C keywords

iOS Bootcamp

A strict superset of C

( ) [ ] catchclassdefsdynamicencodeendfinallyimplementationinterfaceoptional

privatepropertyprotectedprotocolpublicrequiredselectorsynchronizedsynthesizethrowtry

SELIMPnil Nil

BOOLYESNOid typ

edef

selfsuper

hidde

n par

amete

rsinoutinoutbycopy

byrefonewaygettersetter

readwritereadonlyassignretain

copynonatomicstrongweak av

ailab

le in

parti

cular

cont

exts

iOS Bootcamp

Requirements

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 13: Objective-C

iOS Bootcamp

The ldquoOOPCrdquo

1982

iOS Bootcamp

1983

StepStone (formerly PPI)

iOS Bootcamp

1986

OOP An Evolutionary Approach

iOS Bootcamp

1985

Steve Jobs John Sculley

iOS Bootcamp

1986

NeXT Computer (∡28deg)

iOS Bootcamp

1988

NeXT reg Objective-C StepStone

iOS Bootcamp

1991

WWW amp Doom amp Mathematica

NeXTcube

iOS Bootcamp

1993

NeXT + Sun = OpenStep API

ldquoJava Was Strongly Influenced by Objective-CrdquoPatrick Naughton co-creator of Java Programming Language

NSObject

iOS Bootcamp

1996

NeXT sube Apple

iOS Bootcamp

1997

Code Name ldquoRhapsodyrdquo

iOS Bootcamp

2001

Mac OS X v100

iOS Bootcamp

2006

Objective-C 20

prop

erty

fast

enu

mer

atio

n f

or in

optio

nal p

roto

col

garb

age

colle

ctio

n

OS

X

clas

s ex

tens

ions

new

run

time

iOS Bootcamp

2007

The iPhone

iOS Bootcamp

2008

The iPhone SDK

iOS Bootcamp

2005

Chris Lattner

Source httpnondotorgsabreResumehtml

Director and Architect Low-Level ToolsSeptember 2011 - Ongoing

Senior Manager and Architect Low-Level ToolsJune 2010 - September 2011

Senior Manager of Compilers and Low-Level Tools Compiler ArchitectSeptember 2009 - June 2010

Manager of Compilers and Low-Level Tools Compiler ArchitectJuly 2008 - September 2009

LLVM Compiler Group Manager and Compiler ArchitectDecember 2006 - July 2008

Senior Compiler Engineer and Tech LeadJune 2005 - December 2006

iOS Bootcamp

2007

LLVM Compiler Infrastructure

Source The Architecture of Open Source Applications httpwwwaosabookorgenllvmhtml

iOS Bootcamp

2009

Clang (Static Analyzer)

iOS Bootcamp

2009

^ Blocks amp GCD

iOS Bootcamp

2010

Xcode 4

iOS Bootcamp

2011

Automatic Reference Counting

Messaggio Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Modern Objective-CO

bjec

t lite

rals

Enum

s w

ith fi

xed

unde

rlyin

g ty

pe

Subs

crip

ting

met

hods

Uno

rder

ed m

etho

d de

clar

atio

ns

sy

nthe

size

by d

efau

lt

Boxe

d Ex

pres

sions

2012WWDC 2012 Session 405 Modern Objective-C by Patrick C Beard

iOS Bootcamp

TIOBE Top 10 July 2012

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Long Term Trends

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Objective-C

Source httpwwwtiobecomindexphppaperinfotpciObjective-Chtml

Programming Language of the Year

2011

iOS Bootcamp

Ipse dixit Tom Love C++

ldquoObjective-C and C++ both started from C but they went in two very different directions Which approach do you prefer now

Tom Therersquos the successful direction and then therersquos the approach that Bjarne took with C++ In one case it was a small simple mdash dare I say elegant mdash programming language that was very crisp and well defined In the other case it was a pretty ugly complicated difficult language that had some really troublesome features I think those are the distinctions between the twordquo

iOS Bootcamp

Intervallo

iOS Bootcamp

The Language

iOS Bootcamp

Fundamental Laws

iOS Bootcamp

A strict superset of C

bull Objective-C is not inspired by C language like Java or C

bull Objective-C is a strict superset of the C language

bull Objective-C has only added some concepts and their associated keywords

bull Like with C++ a well-written C program should be compile-able as Objective-C

bull Unlike with C++ there is no risk of incompatibility between C names and Objective-C keywords

iOS Bootcamp

A strict superset of C

( ) [ ] catchclassdefsdynamicencodeendfinallyimplementationinterfaceoptional

privatepropertyprotectedprotocolpublicrequiredselectorsynchronizedsynthesizethrowtry

SELIMPnil Nil

BOOLYESNOid typ

edef

selfsuper

hidde

n par

amete

rsinoutinoutbycopy

byrefonewaygettersetter

readwritereadonlyassignretain

copynonatomicstrongweak av

ailab

le in

parti

cular

cont

exts

iOS Bootcamp

Requirements

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 14: Objective-C

iOS Bootcamp

1983

StepStone (formerly PPI)

iOS Bootcamp

1986

OOP An Evolutionary Approach

iOS Bootcamp

1985

Steve Jobs John Sculley

iOS Bootcamp

1986

NeXT Computer (∡28deg)

iOS Bootcamp

1988

NeXT reg Objective-C StepStone

iOS Bootcamp

1991

WWW amp Doom amp Mathematica

NeXTcube

iOS Bootcamp

1993

NeXT + Sun = OpenStep API

ldquoJava Was Strongly Influenced by Objective-CrdquoPatrick Naughton co-creator of Java Programming Language

NSObject

iOS Bootcamp

1996

NeXT sube Apple

iOS Bootcamp

1997

Code Name ldquoRhapsodyrdquo

iOS Bootcamp

2001

Mac OS X v100

iOS Bootcamp

2006

Objective-C 20

prop

erty

fast

enu

mer

atio

n f

or in

optio

nal p

roto

col

garb

age

colle

ctio

n

OS

X

clas

s ex

tens

ions

new

run

time

iOS Bootcamp

2007

The iPhone

iOS Bootcamp

2008

The iPhone SDK

iOS Bootcamp

2005

Chris Lattner

Source httpnondotorgsabreResumehtml

Director and Architect Low-Level ToolsSeptember 2011 - Ongoing

Senior Manager and Architect Low-Level ToolsJune 2010 - September 2011

Senior Manager of Compilers and Low-Level Tools Compiler ArchitectSeptember 2009 - June 2010

Manager of Compilers and Low-Level Tools Compiler ArchitectJuly 2008 - September 2009

LLVM Compiler Group Manager and Compiler ArchitectDecember 2006 - July 2008

Senior Compiler Engineer and Tech LeadJune 2005 - December 2006

iOS Bootcamp

2007

LLVM Compiler Infrastructure

Source The Architecture of Open Source Applications httpwwwaosabookorgenllvmhtml

iOS Bootcamp

2009

Clang (Static Analyzer)

iOS Bootcamp

2009

^ Blocks amp GCD

iOS Bootcamp

2010

Xcode 4

iOS Bootcamp

2011

Automatic Reference Counting

Messaggio Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Modern Objective-CO

bjec

t lite

rals

Enum

s w

ith fi

xed

unde

rlyin

g ty

pe

Subs

crip

ting

met

hods

Uno

rder

ed m

etho

d de

clar

atio

ns

sy

nthe

size

by d

efau

lt

Boxe

d Ex

pres

sions

2012WWDC 2012 Session 405 Modern Objective-C by Patrick C Beard

iOS Bootcamp

TIOBE Top 10 July 2012

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Long Term Trends

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Objective-C

Source httpwwwtiobecomindexphppaperinfotpciObjective-Chtml

Programming Language of the Year

2011

iOS Bootcamp

Ipse dixit Tom Love C++

ldquoObjective-C and C++ both started from C but they went in two very different directions Which approach do you prefer now

Tom Therersquos the successful direction and then therersquos the approach that Bjarne took with C++ In one case it was a small simple mdash dare I say elegant mdash programming language that was very crisp and well defined In the other case it was a pretty ugly complicated difficult language that had some really troublesome features I think those are the distinctions between the twordquo

iOS Bootcamp

Intervallo

iOS Bootcamp

The Language

iOS Bootcamp

Fundamental Laws

iOS Bootcamp

A strict superset of C

bull Objective-C is not inspired by C language like Java or C

bull Objective-C is a strict superset of the C language

bull Objective-C has only added some concepts and their associated keywords

bull Like with C++ a well-written C program should be compile-able as Objective-C

bull Unlike with C++ there is no risk of incompatibility between C names and Objective-C keywords

iOS Bootcamp

A strict superset of C

( ) [ ] catchclassdefsdynamicencodeendfinallyimplementationinterfaceoptional

privatepropertyprotectedprotocolpublicrequiredselectorsynchronizedsynthesizethrowtry

SELIMPnil Nil

BOOLYESNOid typ

edef

selfsuper

hidde

n par

amete

rsinoutinoutbycopy

byrefonewaygettersetter

readwritereadonlyassignretain

copynonatomicstrongweak av

ailab

le in

parti

cular

cont

exts

iOS Bootcamp

Requirements

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 15: Objective-C

iOS Bootcamp

1986

OOP An Evolutionary Approach

iOS Bootcamp

1985

Steve Jobs John Sculley

iOS Bootcamp

1986

NeXT Computer (∡28deg)

iOS Bootcamp

1988

NeXT reg Objective-C StepStone

iOS Bootcamp

1991

WWW amp Doom amp Mathematica

NeXTcube

iOS Bootcamp

1993

NeXT + Sun = OpenStep API

ldquoJava Was Strongly Influenced by Objective-CrdquoPatrick Naughton co-creator of Java Programming Language

NSObject

iOS Bootcamp

1996

NeXT sube Apple

iOS Bootcamp

1997

Code Name ldquoRhapsodyrdquo

iOS Bootcamp

2001

Mac OS X v100

iOS Bootcamp

2006

Objective-C 20

prop

erty

fast

enu

mer

atio

n f

or in

optio

nal p

roto

col

garb

age

colle

ctio

n

OS

X

clas

s ex

tens

ions

new

run

time

iOS Bootcamp

2007

The iPhone

iOS Bootcamp

2008

The iPhone SDK

iOS Bootcamp

2005

Chris Lattner

Source httpnondotorgsabreResumehtml

Director and Architect Low-Level ToolsSeptember 2011 - Ongoing

Senior Manager and Architect Low-Level ToolsJune 2010 - September 2011

Senior Manager of Compilers and Low-Level Tools Compiler ArchitectSeptember 2009 - June 2010

Manager of Compilers and Low-Level Tools Compiler ArchitectJuly 2008 - September 2009

LLVM Compiler Group Manager and Compiler ArchitectDecember 2006 - July 2008

Senior Compiler Engineer and Tech LeadJune 2005 - December 2006

iOS Bootcamp

2007

LLVM Compiler Infrastructure

Source The Architecture of Open Source Applications httpwwwaosabookorgenllvmhtml

iOS Bootcamp

2009

Clang (Static Analyzer)

iOS Bootcamp

2009

^ Blocks amp GCD

iOS Bootcamp

2010

Xcode 4

iOS Bootcamp

2011

Automatic Reference Counting

Messaggio Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Modern Objective-CO

bjec

t lite

rals

Enum

s w

ith fi

xed

unde

rlyin

g ty

pe

Subs

crip

ting

met

hods

Uno

rder

ed m

etho

d de

clar

atio

ns

sy

nthe

size

by d

efau

lt

Boxe

d Ex

pres

sions

2012WWDC 2012 Session 405 Modern Objective-C by Patrick C Beard

iOS Bootcamp

TIOBE Top 10 July 2012

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Long Term Trends

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Objective-C

Source httpwwwtiobecomindexphppaperinfotpciObjective-Chtml

Programming Language of the Year

2011

iOS Bootcamp

Ipse dixit Tom Love C++

ldquoObjective-C and C++ both started from C but they went in two very different directions Which approach do you prefer now

Tom Therersquos the successful direction and then therersquos the approach that Bjarne took with C++ In one case it was a small simple mdash dare I say elegant mdash programming language that was very crisp and well defined In the other case it was a pretty ugly complicated difficult language that had some really troublesome features I think those are the distinctions between the twordquo

iOS Bootcamp

Intervallo

iOS Bootcamp

The Language

iOS Bootcamp

Fundamental Laws

iOS Bootcamp

A strict superset of C

bull Objective-C is not inspired by C language like Java or C

bull Objective-C is a strict superset of the C language

bull Objective-C has only added some concepts and their associated keywords

bull Like with C++ a well-written C program should be compile-able as Objective-C

bull Unlike with C++ there is no risk of incompatibility between C names and Objective-C keywords

iOS Bootcamp

A strict superset of C

( ) [ ] catchclassdefsdynamicencodeendfinallyimplementationinterfaceoptional

privatepropertyprotectedprotocolpublicrequiredselectorsynchronizedsynthesizethrowtry

SELIMPnil Nil

BOOLYESNOid typ

edef

selfsuper

hidde

n par

amete

rsinoutinoutbycopy

byrefonewaygettersetter

readwritereadonlyassignretain

copynonatomicstrongweak av

ailab

le in

parti

cular

cont

exts

iOS Bootcamp

Requirements

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 16: Objective-C

iOS Bootcamp

1985

Steve Jobs John Sculley

iOS Bootcamp

1986

NeXT Computer (∡28deg)

iOS Bootcamp

1988

NeXT reg Objective-C StepStone

iOS Bootcamp

1991

WWW amp Doom amp Mathematica

NeXTcube

iOS Bootcamp

1993

NeXT + Sun = OpenStep API

ldquoJava Was Strongly Influenced by Objective-CrdquoPatrick Naughton co-creator of Java Programming Language

NSObject

iOS Bootcamp

1996

NeXT sube Apple

iOS Bootcamp

1997

Code Name ldquoRhapsodyrdquo

iOS Bootcamp

2001

Mac OS X v100

iOS Bootcamp

2006

Objective-C 20

prop

erty

fast

enu

mer

atio

n f

or in

optio

nal p

roto

col

garb

age

colle

ctio

n

OS

X

clas

s ex

tens

ions

new

run

time

iOS Bootcamp

2007

The iPhone

iOS Bootcamp

2008

The iPhone SDK

iOS Bootcamp

2005

Chris Lattner

Source httpnondotorgsabreResumehtml

Director and Architect Low-Level ToolsSeptember 2011 - Ongoing

Senior Manager and Architect Low-Level ToolsJune 2010 - September 2011

Senior Manager of Compilers and Low-Level Tools Compiler ArchitectSeptember 2009 - June 2010

Manager of Compilers and Low-Level Tools Compiler ArchitectJuly 2008 - September 2009

LLVM Compiler Group Manager and Compiler ArchitectDecember 2006 - July 2008

Senior Compiler Engineer and Tech LeadJune 2005 - December 2006

iOS Bootcamp

2007

LLVM Compiler Infrastructure

Source The Architecture of Open Source Applications httpwwwaosabookorgenllvmhtml

iOS Bootcamp

2009

Clang (Static Analyzer)

iOS Bootcamp

2009

^ Blocks amp GCD

iOS Bootcamp

2010

Xcode 4

iOS Bootcamp

2011

Automatic Reference Counting

Messaggio Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Modern Objective-CO

bjec

t lite

rals

Enum

s w

ith fi

xed

unde

rlyin

g ty

pe

Subs

crip

ting

met

hods

Uno

rder

ed m

etho

d de

clar

atio

ns

sy

nthe

size

by d

efau

lt

Boxe

d Ex

pres

sions

2012WWDC 2012 Session 405 Modern Objective-C by Patrick C Beard

iOS Bootcamp

TIOBE Top 10 July 2012

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Long Term Trends

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Objective-C

Source httpwwwtiobecomindexphppaperinfotpciObjective-Chtml

Programming Language of the Year

2011

iOS Bootcamp

Ipse dixit Tom Love C++

ldquoObjective-C and C++ both started from C but they went in two very different directions Which approach do you prefer now

Tom Therersquos the successful direction and then therersquos the approach that Bjarne took with C++ In one case it was a small simple mdash dare I say elegant mdash programming language that was very crisp and well defined In the other case it was a pretty ugly complicated difficult language that had some really troublesome features I think those are the distinctions between the twordquo

iOS Bootcamp

Intervallo

iOS Bootcamp

The Language

iOS Bootcamp

Fundamental Laws

iOS Bootcamp

A strict superset of C

bull Objective-C is not inspired by C language like Java or C

bull Objective-C is a strict superset of the C language

bull Objective-C has only added some concepts and their associated keywords

bull Like with C++ a well-written C program should be compile-able as Objective-C

bull Unlike with C++ there is no risk of incompatibility between C names and Objective-C keywords

iOS Bootcamp

A strict superset of C

( ) [ ] catchclassdefsdynamicencodeendfinallyimplementationinterfaceoptional

privatepropertyprotectedprotocolpublicrequiredselectorsynchronizedsynthesizethrowtry

SELIMPnil Nil

BOOLYESNOid typ

edef

selfsuper

hidde

n par

amete

rsinoutinoutbycopy

byrefonewaygettersetter

readwritereadonlyassignretain

copynonatomicstrongweak av

ailab

le in

parti

cular

cont

exts

iOS Bootcamp

Requirements

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 17: Objective-C

iOS Bootcamp

1986

NeXT Computer (∡28deg)

iOS Bootcamp

1988

NeXT reg Objective-C StepStone

iOS Bootcamp

1991

WWW amp Doom amp Mathematica

NeXTcube

iOS Bootcamp

1993

NeXT + Sun = OpenStep API

ldquoJava Was Strongly Influenced by Objective-CrdquoPatrick Naughton co-creator of Java Programming Language

NSObject

iOS Bootcamp

1996

NeXT sube Apple

iOS Bootcamp

1997

Code Name ldquoRhapsodyrdquo

iOS Bootcamp

2001

Mac OS X v100

iOS Bootcamp

2006

Objective-C 20

prop

erty

fast

enu

mer

atio

n f

or in

optio

nal p

roto

col

garb

age

colle

ctio

n

OS

X

clas

s ex

tens

ions

new

run

time

iOS Bootcamp

2007

The iPhone

iOS Bootcamp

2008

The iPhone SDK

iOS Bootcamp

2005

Chris Lattner

Source httpnondotorgsabreResumehtml

Director and Architect Low-Level ToolsSeptember 2011 - Ongoing

Senior Manager and Architect Low-Level ToolsJune 2010 - September 2011

Senior Manager of Compilers and Low-Level Tools Compiler ArchitectSeptember 2009 - June 2010

Manager of Compilers and Low-Level Tools Compiler ArchitectJuly 2008 - September 2009

LLVM Compiler Group Manager and Compiler ArchitectDecember 2006 - July 2008

Senior Compiler Engineer and Tech LeadJune 2005 - December 2006

iOS Bootcamp

2007

LLVM Compiler Infrastructure

Source The Architecture of Open Source Applications httpwwwaosabookorgenllvmhtml

iOS Bootcamp

2009

Clang (Static Analyzer)

iOS Bootcamp

2009

^ Blocks amp GCD

iOS Bootcamp

2010

Xcode 4

iOS Bootcamp

2011

Automatic Reference Counting

Messaggio Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Modern Objective-CO

bjec

t lite

rals

Enum

s w

ith fi

xed

unde

rlyin

g ty

pe

Subs

crip

ting

met

hods

Uno

rder

ed m

etho

d de

clar

atio

ns

sy

nthe

size

by d

efau

lt

Boxe

d Ex

pres

sions

2012WWDC 2012 Session 405 Modern Objective-C by Patrick C Beard

iOS Bootcamp

TIOBE Top 10 July 2012

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Long Term Trends

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Objective-C

Source httpwwwtiobecomindexphppaperinfotpciObjective-Chtml

Programming Language of the Year

2011

iOS Bootcamp

Ipse dixit Tom Love C++

ldquoObjective-C and C++ both started from C but they went in two very different directions Which approach do you prefer now

Tom Therersquos the successful direction and then therersquos the approach that Bjarne took with C++ In one case it was a small simple mdash dare I say elegant mdash programming language that was very crisp and well defined In the other case it was a pretty ugly complicated difficult language that had some really troublesome features I think those are the distinctions between the twordquo

iOS Bootcamp

Intervallo

iOS Bootcamp

The Language

iOS Bootcamp

Fundamental Laws

iOS Bootcamp

A strict superset of C

bull Objective-C is not inspired by C language like Java or C

bull Objective-C is a strict superset of the C language

bull Objective-C has only added some concepts and their associated keywords

bull Like with C++ a well-written C program should be compile-able as Objective-C

bull Unlike with C++ there is no risk of incompatibility between C names and Objective-C keywords

iOS Bootcamp

A strict superset of C

( ) [ ] catchclassdefsdynamicencodeendfinallyimplementationinterfaceoptional

privatepropertyprotectedprotocolpublicrequiredselectorsynchronizedsynthesizethrowtry

SELIMPnil Nil

BOOLYESNOid typ

edef

selfsuper

hidde

n par

amete

rsinoutinoutbycopy

byrefonewaygettersetter

readwritereadonlyassignretain

copynonatomicstrongweak av

ailab

le in

parti

cular

cont

exts

iOS Bootcamp

Requirements

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 18: Objective-C

iOS Bootcamp

1988

NeXT reg Objective-C StepStone

iOS Bootcamp

1991

WWW amp Doom amp Mathematica

NeXTcube

iOS Bootcamp

1993

NeXT + Sun = OpenStep API

ldquoJava Was Strongly Influenced by Objective-CrdquoPatrick Naughton co-creator of Java Programming Language

NSObject

iOS Bootcamp

1996

NeXT sube Apple

iOS Bootcamp

1997

Code Name ldquoRhapsodyrdquo

iOS Bootcamp

2001

Mac OS X v100

iOS Bootcamp

2006

Objective-C 20

prop

erty

fast

enu

mer

atio

n f

or in

optio

nal p

roto

col

garb

age

colle

ctio

n

OS

X

clas

s ex

tens

ions

new

run

time

iOS Bootcamp

2007

The iPhone

iOS Bootcamp

2008

The iPhone SDK

iOS Bootcamp

2005

Chris Lattner

Source httpnondotorgsabreResumehtml

Director and Architect Low-Level ToolsSeptember 2011 - Ongoing

Senior Manager and Architect Low-Level ToolsJune 2010 - September 2011

Senior Manager of Compilers and Low-Level Tools Compiler ArchitectSeptember 2009 - June 2010

Manager of Compilers and Low-Level Tools Compiler ArchitectJuly 2008 - September 2009

LLVM Compiler Group Manager and Compiler ArchitectDecember 2006 - July 2008

Senior Compiler Engineer and Tech LeadJune 2005 - December 2006

iOS Bootcamp

2007

LLVM Compiler Infrastructure

Source The Architecture of Open Source Applications httpwwwaosabookorgenllvmhtml

iOS Bootcamp

2009

Clang (Static Analyzer)

iOS Bootcamp

2009

^ Blocks amp GCD

iOS Bootcamp

2010

Xcode 4

iOS Bootcamp

2011

Automatic Reference Counting

Messaggio Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Modern Objective-CO

bjec

t lite

rals

Enum

s w

ith fi

xed

unde

rlyin

g ty

pe

Subs

crip

ting

met

hods

Uno

rder

ed m

etho

d de

clar

atio

ns

sy

nthe

size

by d

efau

lt

Boxe

d Ex

pres

sions

2012WWDC 2012 Session 405 Modern Objective-C by Patrick C Beard

iOS Bootcamp

TIOBE Top 10 July 2012

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Long Term Trends

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Objective-C

Source httpwwwtiobecomindexphppaperinfotpciObjective-Chtml

Programming Language of the Year

2011

iOS Bootcamp

Ipse dixit Tom Love C++

ldquoObjective-C and C++ both started from C but they went in two very different directions Which approach do you prefer now

Tom Therersquos the successful direction and then therersquos the approach that Bjarne took with C++ In one case it was a small simple mdash dare I say elegant mdash programming language that was very crisp and well defined In the other case it was a pretty ugly complicated difficult language that had some really troublesome features I think those are the distinctions between the twordquo

iOS Bootcamp

Intervallo

iOS Bootcamp

The Language

iOS Bootcamp

Fundamental Laws

iOS Bootcamp

A strict superset of C

bull Objective-C is not inspired by C language like Java or C

bull Objective-C is a strict superset of the C language

bull Objective-C has only added some concepts and their associated keywords

bull Like with C++ a well-written C program should be compile-able as Objective-C

bull Unlike with C++ there is no risk of incompatibility between C names and Objective-C keywords

iOS Bootcamp

A strict superset of C

( ) [ ] catchclassdefsdynamicencodeendfinallyimplementationinterfaceoptional

privatepropertyprotectedprotocolpublicrequiredselectorsynchronizedsynthesizethrowtry

SELIMPnil Nil

BOOLYESNOid typ

edef

selfsuper

hidde

n par

amete

rsinoutinoutbycopy

byrefonewaygettersetter

readwritereadonlyassignretain

copynonatomicstrongweak av

ailab

le in

parti

cular

cont

exts

iOS Bootcamp

Requirements

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 19: Objective-C

iOS Bootcamp

1991

WWW amp Doom amp Mathematica

NeXTcube

iOS Bootcamp

1993

NeXT + Sun = OpenStep API

ldquoJava Was Strongly Influenced by Objective-CrdquoPatrick Naughton co-creator of Java Programming Language

NSObject

iOS Bootcamp

1996

NeXT sube Apple

iOS Bootcamp

1997

Code Name ldquoRhapsodyrdquo

iOS Bootcamp

2001

Mac OS X v100

iOS Bootcamp

2006

Objective-C 20

prop

erty

fast

enu

mer

atio

n f

or in

optio

nal p

roto

col

garb

age

colle

ctio

n

OS

X

clas

s ex

tens

ions

new

run

time

iOS Bootcamp

2007

The iPhone

iOS Bootcamp

2008

The iPhone SDK

iOS Bootcamp

2005

Chris Lattner

Source httpnondotorgsabreResumehtml

Director and Architect Low-Level ToolsSeptember 2011 - Ongoing

Senior Manager and Architect Low-Level ToolsJune 2010 - September 2011

Senior Manager of Compilers and Low-Level Tools Compiler ArchitectSeptember 2009 - June 2010

Manager of Compilers and Low-Level Tools Compiler ArchitectJuly 2008 - September 2009

LLVM Compiler Group Manager and Compiler ArchitectDecember 2006 - July 2008

Senior Compiler Engineer and Tech LeadJune 2005 - December 2006

iOS Bootcamp

2007

LLVM Compiler Infrastructure

Source The Architecture of Open Source Applications httpwwwaosabookorgenllvmhtml

iOS Bootcamp

2009

Clang (Static Analyzer)

iOS Bootcamp

2009

^ Blocks amp GCD

iOS Bootcamp

2010

Xcode 4

iOS Bootcamp

2011

Automatic Reference Counting

Messaggio Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Modern Objective-CO

bjec

t lite

rals

Enum

s w

ith fi

xed

unde

rlyin

g ty

pe

Subs

crip

ting

met

hods

Uno

rder

ed m

etho

d de

clar

atio

ns

sy

nthe

size

by d

efau

lt

Boxe

d Ex

pres

sions

2012WWDC 2012 Session 405 Modern Objective-C by Patrick C Beard

iOS Bootcamp

TIOBE Top 10 July 2012

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Long Term Trends

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Objective-C

Source httpwwwtiobecomindexphppaperinfotpciObjective-Chtml

Programming Language of the Year

2011

iOS Bootcamp

Ipse dixit Tom Love C++

ldquoObjective-C and C++ both started from C but they went in two very different directions Which approach do you prefer now

Tom Therersquos the successful direction and then therersquos the approach that Bjarne took with C++ In one case it was a small simple mdash dare I say elegant mdash programming language that was very crisp and well defined In the other case it was a pretty ugly complicated difficult language that had some really troublesome features I think those are the distinctions between the twordquo

iOS Bootcamp

Intervallo

iOS Bootcamp

The Language

iOS Bootcamp

Fundamental Laws

iOS Bootcamp

A strict superset of C

bull Objective-C is not inspired by C language like Java or C

bull Objective-C is a strict superset of the C language

bull Objective-C has only added some concepts and their associated keywords

bull Like with C++ a well-written C program should be compile-able as Objective-C

bull Unlike with C++ there is no risk of incompatibility between C names and Objective-C keywords

iOS Bootcamp

A strict superset of C

( ) [ ] catchclassdefsdynamicencodeendfinallyimplementationinterfaceoptional

privatepropertyprotectedprotocolpublicrequiredselectorsynchronizedsynthesizethrowtry

SELIMPnil Nil

BOOLYESNOid typ

edef

selfsuper

hidde

n par

amete

rsinoutinoutbycopy

byrefonewaygettersetter

readwritereadonlyassignretain

copynonatomicstrongweak av

ailab

le in

parti

cular

cont

exts

iOS Bootcamp

Requirements

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 20: Objective-C

iOS Bootcamp

1993

NeXT + Sun = OpenStep API

ldquoJava Was Strongly Influenced by Objective-CrdquoPatrick Naughton co-creator of Java Programming Language

NSObject

iOS Bootcamp

1996

NeXT sube Apple

iOS Bootcamp

1997

Code Name ldquoRhapsodyrdquo

iOS Bootcamp

2001

Mac OS X v100

iOS Bootcamp

2006

Objective-C 20

prop

erty

fast

enu

mer

atio

n f

or in

optio

nal p

roto

col

garb

age

colle

ctio

n

OS

X

clas

s ex

tens

ions

new

run

time

iOS Bootcamp

2007

The iPhone

iOS Bootcamp

2008

The iPhone SDK

iOS Bootcamp

2005

Chris Lattner

Source httpnondotorgsabreResumehtml

Director and Architect Low-Level ToolsSeptember 2011 - Ongoing

Senior Manager and Architect Low-Level ToolsJune 2010 - September 2011

Senior Manager of Compilers and Low-Level Tools Compiler ArchitectSeptember 2009 - June 2010

Manager of Compilers and Low-Level Tools Compiler ArchitectJuly 2008 - September 2009

LLVM Compiler Group Manager and Compiler ArchitectDecember 2006 - July 2008

Senior Compiler Engineer and Tech LeadJune 2005 - December 2006

iOS Bootcamp

2007

LLVM Compiler Infrastructure

Source The Architecture of Open Source Applications httpwwwaosabookorgenllvmhtml

iOS Bootcamp

2009

Clang (Static Analyzer)

iOS Bootcamp

2009

^ Blocks amp GCD

iOS Bootcamp

2010

Xcode 4

iOS Bootcamp

2011

Automatic Reference Counting

Messaggio Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Modern Objective-CO

bjec

t lite

rals

Enum

s w

ith fi

xed

unde

rlyin

g ty

pe

Subs

crip

ting

met

hods

Uno

rder

ed m

etho

d de

clar

atio

ns

sy

nthe

size

by d

efau

lt

Boxe

d Ex

pres

sions

2012WWDC 2012 Session 405 Modern Objective-C by Patrick C Beard

iOS Bootcamp

TIOBE Top 10 July 2012

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Long Term Trends

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Objective-C

Source httpwwwtiobecomindexphppaperinfotpciObjective-Chtml

Programming Language of the Year

2011

iOS Bootcamp

Ipse dixit Tom Love C++

ldquoObjective-C and C++ both started from C but they went in two very different directions Which approach do you prefer now

Tom Therersquos the successful direction and then therersquos the approach that Bjarne took with C++ In one case it was a small simple mdash dare I say elegant mdash programming language that was very crisp and well defined In the other case it was a pretty ugly complicated difficult language that had some really troublesome features I think those are the distinctions between the twordquo

iOS Bootcamp

Intervallo

iOS Bootcamp

The Language

iOS Bootcamp

Fundamental Laws

iOS Bootcamp

A strict superset of C

bull Objective-C is not inspired by C language like Java or C

bull Objective-C is a strict superset of the C language

bull Objective-C has only added some concepts and their associated keywords

bull Like with C++ a well-written C program should be compile-able as Objective-C

bull Unlike with C++ there is no risk of incompatibility between C names and Objective-C keywords

iOS Bootcamp

A strict superset of C

( ) [ ] catchclassdefsdynamicencodeendfinallyimplementationinterfaceoptional

privatepropertyprotectedprotocolpublicrequiredselectorsynchronizedsynthesizethrowtry

SELIMPnil Nil

BOOLYESNOid typ

edef

selfsuper

hidde

n par

amete

rsinoutinoutbycopy

byrefonewaygettersetter

readwritereadonlyassignretain

copynonatomicstrongweak av

ailab

le in

parti

cular

cont

exts

iOS Bootcamp

Requirements

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 21: Objective-C

iOS Bootcamp

1996

NeXT sube Apple

iOS Bootcamp

1997

Code Name ldquoRhapsodyrdquo

iOS Bootcamp

2001

Mac OS X v100

iOS Bootcamp

2006

Objective-C 20

prop

erty

fast

enu

mer

atio

n f

or in

optio

nal p

roto

col

garb

age

colle

ctio

n

OS

X

clas

s ex

tens

ions

new

run

time

iOS Bootcamp

2007

The iPhone

iOS Bootcamp

2008

The iPhone SDK

iOS Bootcamp

2005

Chris Lattner

Source httpnondotorgsabreResumehtml

Director and Architect Low-Level ToolsSeptember 2011 - Ongoing

Senior Manager and Architect Low-Level ToolsJune 2010 - September 2011

Senior Manager of Compilers and Low-Level Tools Compiler ArchitectSeptember 2009 - June 2010

Manager of Compilers and Low-Level Tools Compiler ArchitectJuly 2008 - September 2009

LLVM Compiler Group Manager and Compiler ArchitectDecember 2006 - July 2008

Senior Compiler Engineer and Tech LeadJune 2005 - December 2006

iOS Bootcamp

2007

LLVM Compiler Infrastructure

Source The Architecture of Open Source Applications httpwwwaosabookorgenllvmhtml

iOS Bootcamp

2009

Clang (Static Analyzer)

iOS Bootcamp

2009

^ Blocks amp GCD

iOS Bootcamp

2010

Xcode 4

iOS Bootcamp

2011

Automatic Reference Counting

Messaggio Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Modern Objective-CO

bjec

t lite

rals

Enum

s w

ith fi

xed

unde

rlyin

g ty

pe

Subs

crip

ting

met

hods

Uno

rder

ed m

etho

d de

clar

atio

ns

sy

nthe

size

by d

efau

lt

Boxe

d Ex

pres

sions

2012WWDC 2012 Session 405 Modern Objective-C by Patrick C Beard

iOS Bootcamp

TIOBE Top 10 July 2012

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Long Term Trends

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Objective-C

Source httpwwwtiobecomindexphppaperinfotpciObjective-Chtml

Programming Language of the Year

2011

iOS Bootcamp

Ipse dixit Tom Love C++

ldquoObjective-C and C++ both started from C but they went in two very different directions Which approach do you prefer now

Tom Therersquos the successful direction and then therersquos the approach that Bjarne took with C++ In one case it was a small simple mdash dare I say elegant mdash programming language that was very crisp and well defined In the other case it was a pretty ugly complicated difficult language that had some really troublesome features I think those are the distinctions between the twordquo

iOS Bootcamp

Intervallo

iOS Bootcamp

The Language

iOS Bootcamp

Fundamental Laws

iOS Bootcamp

A strict superset of C

bull Objective-C is not inspired by C language like Java or C

bull Objective-C is a strict superset of the C language

bull Objective-C has only added some concepts and their associated keywords

bull Like with C++ a well-written C program should be compile-able as Objective-C

bull Unlike with C++ there is no risk of incompatibility between C names and Objective-C keywords

iOS Bootcamp

A strict superset of C

( ) [ ] catchclassdefsdynamicencodeendfinallyimplementationinterfaceoptional

privatepropertyprotectedprotocolpublicrequiredselectorsynchronizedsynthesizethrowtry

SELIMPnil Nil

BOOLYESNOid typ

edef

selfsuper

hidde

n par

amete

rsinoutinoutbycopy

byrefonewaygettersetter

readwritereadonlyassignretain

copynonatomicstrongweak av

ailab

le in

parti

cular

cont

exts

iOS Bootcamp

Requirements

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 22: Objective-C

iOS Bootcamp

1997

Code Name ldquoRhapsodyrdquo

iOS Bootcamp

2001

Mac OS X v100

iOS Bootcamp

2006

Objective-C 20

prop

erty

fast

enu

mer

atio

n f

or in

optio

nal p

roto

col

garb

age

colle

ctio

n

OS

X

clas

s ex

tens

ions

new

run

time

iOS Bootcamp

2007

The iPhone

iOS Bootcamp

2008

The iPhone SDK

iOS Bootcamp

2005

Chris Lattner

Source httpnondotorgsabreResumehtml

Director and Architect Low-Level ToolsSeptember 2011 - Ongoing

Senior Manager and Architect Low-Level ToolsJune 2010 - September 2011

Senior Manager of Compilers and Low-Level Tools Compiler ArchitectSeptember 2009 - June 2010

Manager of Compilers and Low-Level Tools Compiler ArchitectJuly 2008 - September 2009

LLVM Compiler Group Manager and Compiler ArchitectDecember 2006 - July 2008

Senior Compiler Engineer and Tech LeadJune 2005 - December 2006

iOS Bootcamp

2007

LLVM Compiler Infrastructure

Source The Architecture of Open Source Applications httpwwwaosabookorgenllvmhtml

iOS Bootcamp

2009

Clang (Static Analyzer)

iOS Bootcamp

2009

^ Blocks amp GCD

iOS Bootcamp

2010

Xcode 4

iOS Bootcamp

2011

Automatic Reference Counting

Messaggio Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Modern Objective-CO

bjec

t lite

rals

Enum

s w

ith fi

xed

unde

rlyin

g ty

pe

Subs

crip

ting

met

hods

Uno

rder

ed m

etho

d de

clar

atio

ns

sy

nthe

size

by d

efau

lt

Boxe

d Ex

pres

sions

2012WWDC 2012 Session 405 Modern Objective-C by Patrick C Beard

iOS Bootcamp

TIOBE Top 10 July 2012

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Long Term Trends

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Objective-C

Source httpwwwtiobecomindexphppaperinfotpciObjective-Chtml

Programming Language of the Year

2011

iOS Bootcamp

Ipse dixit Tom Love C++

ldquoObjective-C and C++ both started from C but they went in two very different directions Which approach do you prefer now

Tom Therersquos the successful direction and then therersquos the approach that Bjarne took with C++ In one case it was a small simple mdash dare I say elegant mdash programming language that was very crisp and well defined In the other case it was a pretty ugly complicated difficult language that had some really troublesome features I think those are the distinctions between the twordquo

iOS Bootcamp

Intervallo

iOS Bootcamp

The Language

iOS Bootcamp

Fundamental Laws

iOS Bootcamp

A strict superset of C

bull Objective-C is not inspired by C language like Java or C

bull Objective-C is a strict superset of the C language

bull Objective-C has only added some concepts and their associated keywords

bull Like with C++ a well-written C program should be compile-able as Objective-C

bull Unlike with C++ there is no risk of incompatibility between C names and Objective-C keywords

iOS Bootcamp

A strict superset of C

( ) [ ] catchclassdefsdynamicencodeendfinallyimplementationinterfaceoptional

privatepropertyprotectedprotocolpublicrequiredselectorsynchronizedsynthesizethrowtry

SELIMPnil Nil

BOOLYESNOid typ

edef

selfsuper

hidde

n par

amete

rsinoutinoutbycopy

byrefonewaygettersetter

readwritereadonlyassignretain

copynonatomicstrongweak av

ailab

le in

parti

cular

cont

exts

iOS Bootcamp

Requirements

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 23: Objective-C

iOS Bootcamp

2001

Mac OS X v100

iOS Bootcamp

2006

Objective-C 20

prop

erty

fast

enu

mer

atio

n f

or in

optio

nal p

roto

col

garb

age

colle

ctio

n

OS

X

clas

s ex

tens

ions

new

run

time

iOS Bootcamp

2007

The iPhone

iOS Bootcamp

2008

The iPhone SDK

iOS Bootcamp

2005

Chris Lattner

Source httpnondotorgsabreResumehtml

Director and Architect Low-Level ToolsSeptember 2011 - Ongoing

Senior Manager and Architect Low-Level ToolsJune 2010 - September 2011

Senior Manager of Compilers and Low-Level Tools Compiler ArchitectSeptember 2009 - June 2010

Manager of Compilers and Low-Level Tools Compiler ArchitectJuly 2008 - September 2009

LLVM Compiler Group Manager and Compiler ArchitectDecember 2006 - July 2008

Senior Compiler Engineer and Tech LeadJune 2005 - December 2006

iOS Bootcamp

2007

LLVM Compiler Infrastructure

Source The Architecture of Open Source Applications httpwwwaosabookorgenllvmhtml

iOS Bootcamp

2009

Clang (Static Analyzer)

iOS Bootcamp

2009

^ Blocks amp GCD

iOS Bootcamp

2010

Xcode 4

iOS Bootcamp

2011

Automatic Reference Counting

Messaggio Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Modern Objective-CO

bjec

t lite

rals

Enum

s w

ith fi

xed

unde

rlyin

g ty

pe

Subs

crip

ting

met

hods

Uno

rder

ed m

etho

d de

clar

atio

ns

sy

nthe

size

by d

efau

lt

Boxe

d Ex

pres

sions

2012WWDC 2012 Session 405 Modern Objective-C by Patrick C Beard

iOS Bootcamp

TIOBE Top 10 July 2012

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Long Term Trends

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Objective-C

Source httpwwwtiobecomindexphppaperinfotpciObjective-Chtml

Programming Language of the Year

2011

iOS Bootcamp

Ipse dixit Tom Love C++

ldquoObjective-C and C++ both started from C but they went in two very different directions Which approach do you prefer now

Tom Therersquos the successful direction and then therersquos the approach that Bjarne took with C++ In one case it was a small simple mdash dare I say elegant mdash programming language that was very crisp and well defined In the other case it was a pretty ugly complicated difficult language that had some really troublesome features I think those are the distinctions between the twordquo

iOS Bootcamp

Intervallo

iOS Bootcamp

The Language

iOS Bootcamp

Fundamental Laws

iOS Bootcamp

A strict superset of C

bull Objective-C is not inspired by C language like Java or C

bull Objective-C is a strict superset of the C language

bull Objective-C has only added some concepts and their associated keywords

bull Like with C++ a well-written C program should be compile-able as Objective-C

bull Unlike with C++ there is no risk of incompatibility between C names and Objective-C keywords

iOS Bootcamp

A strict superset of C

( ) [ ] catchclassdefsdynamicencodeendfinallyimplementationinterfaceoptional

privatepropertyprotectedprotocolpublicrequiredselectorsynchronizedsynthesizethrowtry

SELIMPnil Nil

BOOLYESNOid typ

edef

selfsuper

hidde

n par

amete

rsinoutinoutbycopy

byrefonewaygettersetter

readwritereadonlyassignretain

copynonatomicstrongweak av

ailab

le in

parti

cular

cont

exts

iOS Bootcamp

Requirements

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 24: Objective-C

iOS Bootcamp

2006

Objective-C 20

prop

erty

fast

enu

mer

atio

n f

or in

optio

nal p

roto

col

garb

age

colle

ctio

n

OS

X

clas

s ex

tens

ions

new

run

time

iOS Bootcamp

2007

The iPhone

iOS Bootcamp

2008

The iPhone SDK

iOS Bootcamp

2005

Chris Lattner

Source httpnondotorgsabreResumehtml

Director and Architect Low-Level ToolsSeptember 2011 - Ongoing

Senior Manager and Architect Low-Level ToolsJune 2010 - September 2011

Senior Manager of Compilers and Low-Level Tools Compiler ArchitectSeptember 2009 - June 2010

Manager of Compilers and Low-Level Tools Compiler ArchitectJuly 2008 - September 2009

LLVM Compiler Group Manager and Compiler ArchitectDecember 2006 - July 2008

Senior Compiler Engineer and Tech LeadJune 2005 - December 2006

iOS Bootcamp

2007

LLVM Compiler Infrastructure

Source The Architecture of Open Source Applications httpwwwaosabookorgenllvmhtml

iOS Bootcamp

2009

Clang (Static Analyzer)

iOS Bootcamp

2009

^ Blocks amp GCD

iOS Bootcamp

2010

Xcode 4

iOS Bootcamp

2011

Automatic Reference Counting

Messaggio Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Modern Objective-CO

bjec

t lite

rals

Enum

s w

ith fi

xed

unde

rlyin

g ty

pe

Subs

crip

ting

met

hods

Uno

rder

ed m

etho

d de

clar

atio

ns

sy

nthe

size

by d

efau

lt

Boxe

d Ex

pres

sions

2012WWDC 2012 Session 405 Modern Objective-C by Patrick C Beard

iOS Bootcamp

TIOBE Top 10 July 2012

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Long Term Trends

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Objective-C

Source httpwwwtiobecomindexphppaperinfotpciObjective-Chtml

Programming Language of the Year

2011

iOS Bootcamp

Ipse dixit Tom Love C++

ldquoObjective-C and C++ both started from C but they went in two very different directions Which approach do you prefer now

Tom Therersquos the successful direction and then therersquos the approach that Bjarne took with C++ In one case it was a small simple mdash dare I say elegant mdash programming language that was very crisp and well defined In the other case it was a pretty ugly complicated difficult language that had some really troublesome features I think those are the distinctions between the twordquo

iOS Bootcamp

Intervallo

iOS Bootcamp

The Language

iOS Bootcamp

Fundamental Laws

iOS Bootcamp

A strict superset of C

bull Objective-C is not inspired by C language like Java or C

bull Objective-C is a strict superset of the C language

bull Objective-C has only added some concepts and their associated keywords

bull Like with C++ a well-written C program should be compile-able as Objective-C

bull Unlike with C++ there is no risk of incompatibility between C names and Objective-C keywords

iOS Bootcamp

A strict superset of C

( ) [ ] catchclassdefsdynamicencodeendfinallyimplementationinterfaceoptional

privatepropertyprotectedprotocolpublicrequiredselectorsynchronizedsynthesizethrowtry

SELIMPnil Nil

BOOLYESNOid typ

edef

selfsuper

hidde

n par

amete

rsinoutinoutbycopy

byrefonewaygettersetter

readwritereadonlyassignretain

copynonatomicstrongweak av

ailab

le in

parti

cular

cont

exts

iOS Bootcamp

Requirements

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 25: Objective-C

iOS Bootcamp

2007

The iPhone

iOS Bootcamp

2008

The iPhone SDK

iOS Bootcamp

2005

Chris Lattner

Source httpnondotorgsabreResumehtml

Director and Architect Low-Level ToolsSeptember 2011 - Ongoing

Senior Manager and Architect Low-Level ToolsJune 2010 - September 2011

Senior Manager of Compilers and Low-Level Tools Compiler ArchitectSeptember 2009 - June 2010

Manager of Compilers and Low-Level Tools Compiler ArchitectJuly 2008 - September 2009

LLVM Compiler Group Manager and Compiler ArchitectDecember 2006 - July 2008

Senior Compiler Engineer and Tech LeadJune 2005 - December 2006

iOS Bootcamp

2007

LLVM Compiler Infrastructure

Source The Architecture of Open Source Applications httpwwwaosabookorgenllvmhtml

iOS Bootcamp

2009

Clang (Static Analyzer)

iOS Bootcamp

2009

^ Blocks amp GCD

iOS Bootcamp

2010

Xcode 4

iOS Bootcamp

2011

Automatic Reference Counting

Messaggio Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Modern Objective-CO

bjec

t lite

rals

Enum

s w

ith fi

xed

unde

rlyin

g ty

pe

Subs

crip

ting

met

hods

Uno

rder

ed m

etho

d de

clar

atio

ns

sy

nthe

size

by d

efau

lt

Boxe

d Ex

pres

sions

2012WWDC 2012 Session 405 Modern Objective-C by Patrick C Beard

iOS Bootcamp

TIOBE Top 10 July 2012

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Long Term Trends

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Objective-C

Source httpwwwtiobecomindexphppaperinfotpciObjective-Chtml

Programming Language of the Year

2011

iOS Bootcamp

Ipse dixit Tom Love C++

ldquoObjective-C and C++ both started from C but they went in two very different directions Which approach do you prefer now

Tom Therersquos the successful direction and then therersquos the approach that Bjarne took with C++ In one case it was a small simple mdash dare I say elegant mdash programming language that was very crisp and well defined In the other case it was a pretty ugly complicated difficult language that had some really troublesome features I think those are the distinctions between the twordquo

iOS Bootcamp

Intervallo

iOS Bootcamp

The Language

iOS Bootcamp

Fundamental Laws

iOS Bootcamp

A strict superset of C

bull Objective-C is not inspired by C language like Java or C

bull Objective-C is a strict superset of the C language

bull Objective-C has only added some concepts and their associated keywords

bull Like with C++ a well-written C program should be compile-able as Objective-C

bull Unlike with C++ there is no risk of incompatibility between C names and Objective-C keywords

iOS Bootcamp

A strict superset of C

( ) [ ] catchclassdefsdynamicencodeendfinallyimplementationinterfaceoptional

privatepropertyprotectedprotocolpublicrequiredselectorsynchronizedsynthesizethrowtry

SELIMPnil Nil

BOOLYESNOid typ

edef

selfsuper

hidde

n par

amete

rsinoutinoutbycopy

byrefonewaygettersetter

readwritereadonlyassignretain

copynonatomicstrongweak av

ailab

le in

parti

cular

cont

exts

iOS Bootcamp

Requirements

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 26: Objective-C

iOS Bootcamp

2008

The iPhone SDK

iOS Bootcamp

2005

Chris Lattner

Source httpnondotorgsabreResumehtml

Director and Architect Low-Level ToolsSeptember 2011 - Ongoing

Senior Manager and Architect Low-Level ToolsJune 2010 - September 2011

Senior Manager of Compilers and Low-Level Tools Compiler ArchitectSeptember 2009 - June 2010

Manager of Compilers and Low-Level Tools Compiler ArchitectJuly 2008 - September 2009

LLVM Compiler Group Manager and Compiler ArchitectDecember 2006 - July 2008

Senior Compiler Engineer and Tech LeadJune 2005 - December 2006

iOS Bootcamp

2007

LLVM Compiler Infrastructure

Source The Architecture of Open Source Applications httpwwwaosabookorgenllvmhtml

iOS Bootcamp

2009

Clang (Static Analyzer)

iOS Bootcamp

2009

^ Blocks amp GCD

iOS Bootcamp

2010

Xcode 4

iOS Bootcamp

2011

Automatic Reference Counting

Messaggio Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Modern Objective-CO

bjec

t lite

rals

Enum

s w

ith fi

xed

unde

rlyin

g ty

pe

Subs

crip

ting

met

hods

Uno

rder

ed m

etho

d de

clar

atio

ns

sy

nthe

size

by d

efau

lt

Boxe

d Ex

pres

sions

2012WWDC 2012 Session 405 Modern Objective-C by Patrick C Beard

iOS Bootcamp

TIOBE Top 10 July 2012

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Long Term Trends

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Objective-C

Source httpwwwtiobecomindexphppaperinfotpciObjective-Chtml

Programming Language of the Year

2011

iOS Bootcamp

Ipse dixit Tom Love C++

ldquoObjective-C and C++ both started from C but they went in two very different directions Which approach do you prefer now

Tom Therersquos the successful direction and then therersquos the approach that Bjarne took with C++ In one case it was a small simple mdash dare I say elegant mdash programming language that was very crisp and well defined In the other case it was a pretty ugly complicated difficult language that had some really troublesome features I think those are the distinctions between the twordquo

iOS Bootcamp

Intervallo

iOS Bootcamp

The Language

iOS Bootcamp

Fundamental Laws

iOS Bootcamp

A strict superset of C

bull Objective-C is not inspired by C language like Java or C

bull Objective-C is a strict superset of the C language

bull Objective-C has only added some concepts and their associated keywords

bull Like with C++ a well-written C program should be compile-able as Objective-C

bull Unlike with C++ there is no risk of incompatibility between C names and Objective-C keywords

iOS Bootcamp

A strict superset of C

( ) [ ] catchclassdefsdynamicencodeendfinallyimplementationinterfaceoptional

privatepropertyprotectedprotocolpublicrequiredselectorsynchronizedsynthesizethrowtry

SELIMPnil Nil

BOOLYESNOid typ

edef

selfsuper

hidde

n par

amete

rsinoutinoutbycopy

byrefonewaygettersetter

readwritereadonlyassignretain

copynonatomicstrongweak av

ailab

le in

parti

cular

cont

exts

iOS Bootcamp

Requirements

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 27: Objective-C

iOS Bootcamp

2005

Chris Lattner

Source httpnondotorgsabreResumehtml

Director and Architect Low-Level ToolsSeptember 2011 - Ongoing

Senior Manager and Architect Low-Level ToolsJune 2010 - September 2011

Senior Manager of Compilers and Low-Level Tools Compiler ArchitectSeptember 2009 - June 2010

Manager of Compilers and Low-Level Tools Compiler ArchitectJuly 2008 - September 2009

LLVM Compiler Group Manager and Compiler ArchitectDecember 2006 - July 2008

Senior Compiler Engineer and Tech LeadJune 2005 - December 2006

iOS Bootcamp

2007

LLVM Compiler Infrastructure

Source The Architecture of Open Source Applications httpwwwaosabookorgenllvmhtml

iOS Bootcamp

2009

Clang (Static Analyzer)

iOS Bootcamp

2009

^ Blocks amp GCD

iOS Bootcamp

2010

Xcode 4

iOS Bootcamp

2011

Automatic Reference Counting

Messaggio Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Modern Objective-CO

bjec

t lite

rals

Enum

s w

ith fi

xed

unde

rlyin

g ty

pe

Subs

crip

ting

met

hods

Uno

rder

ed m

etho

d de

clar

atio

ns

sy

nthe

size

by d

efau

lt

Boxe

d Ex

pres

sions

2012WWDC 2012 Session 405 Modern Objective-C by Patrick C Beard

iOS Bootcamp

TIOBE Top 10 July 2012

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Long Term Trends

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Objective-C

Source httpwwwtiobecomindexphppaperinfotpciObjective-Chtml

Programming Language of the Year

2011

iOS Bootcamp

Ipse dixit Tom Love C++

ldquoObjective-C and C++ both started from C but they went in two very different directions Which approach do you prefer now

Tom Therersquos the successful direction and then therersquos the approach that Bjarne took with C++ In one case it was a small simple mdash dare I say elegant mdash programming language that was very crisp and well defined In the other case it was a pretty ugly complicated difficult language that had some really troublesome features I think those are the distinctions between the twordquo

iOS Bootcamp

Intervallo

iOS Bootcamp

The Language

iOS Bootcamp

Fundamental Laws

iOS Bootcamp

A strict superset of C

bull Objective-C is not inspired by C language like Java or C

bull Objective-C is a strict superset of the C language

bull Objective-C has only added some concepts and their associated keywords

bull Like with C++ a well-written C program should be compile-able as Objective-C

bull Unlike with C++ there is no risk of incompatibility between C names and Objective-C keywords

iOS Bootcamp

A strict superset of C

( ) [ ] catchclassdefsdynamicencodeendfinallyimplementationinterfaceoptional

privatepropertyprotectedprotocolpublicrequiredselectorsynchronizedsynthesizethrowtry

SELIMPnil Nil

BOOLYESNOid typ

edef

selfsuper

hidde

n par

amete

rsinoutinoutbycopy

byrefonewaygettersetter

readwritereadonlyassignretain

copynonatomicstrongweak av

ailab

le in

parti

cular

cont

exts

iOS Bootcamp

Requirements

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 28: Objective-C

iOS Bootcamp

2007

LLVM Compiler Infrastructure

Source The Architecture of Open Source Applications httpwwwaosabookorgenllvmhtml

iOS Bootcamp

2009

Clang (Static Analyzer)

iOS Bootcamp

2009

^ Blocks amp GCD

iOS Bootcamp

2010

Xcode 4

iOS Bootcamp

2011

Automatic Reference Counting

Messaggio Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Modern Objective-CO

bjec

t lite

rals

Enum

s w

ith fi

xed

unde

rlyin

g ty

pe

Subs

crip

ting

met

hods

Uno

rder

ed m

etho

d de

clar

atio

ns

sy

nthe

size

by d

efau

lt

Boxe

d Ex

pres

sions

2012WWDC 2012 Session 405 Modern Objective-C by Patrick C Beard

iOS Bootcamp

TIOBE Top 10 July 2012

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Long Term Trends

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Objective-C

Source httpwwwtiobecomindexphppaperinfotpciObjective-Chtml

Programming Language of the Year

2011

iOS Bootcamp

Ipse dixit Tom Love C++

ldquoObjective-C and C++ both started from C but they went in two very different directions Which approach do you prefer now

Tom Therersquos the successful direction and then therersquos the approach that Bjarne took with C++ In one case it was a small simple mdash dare I say elegant mdash programming language that was very crisp and well defined In the other case it was a pretty ugly complicated difficult language that had some really troublesome features I think those are the distinctions between the twordquo

iOS Bootcamp

Intervallo

iOS Bootcamp

The Language

iOS Bootcamp

Fundamental Laws

iOS Bootcamp

A strict superset of C

bull Objective-C is not inspired by C language like Java or C

bull Objective-C is a strict superset of the C language

bull Objective-C has only added some concepts and their associated keywords

bull Like with C++ a well-written C program should be compile-able as Objective-C

bull Unlike with C++ there is no risk of incompatibility between C names and Objective-C keywords

iOS Bootcamp

A strict superset of C

( ) [ ] catchclassdefsdynamicencodeendfinallyimplementationinterfaceoptional

privatepropertyprotectedprotocolpublicrequiredselectorsynchronizedsynthesizethrowtry

SELIMPnil Nil

BOOLYESNOid typ

edef

selfsuper

hidde

n par

amete

rsinoutinoutbycopy

byrefonewaygettersetter

readwritereadonlyassignretain

copynonatomicstrongweak av

ailab

le in

parti

cular

cont

exts

iOS Bootcamp

Requirements

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 29: Objective-C

iOS Bootcamp

2009

Clang (Static Analyzer)

iOS Bootcamp

2009

^ Blocks amp GCD

iOS Bootcamp

2010

Xcode 4

iOS Bootcamp

2011

Automatic Reference Counting

Messaggio Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Modern Objective-CO

bjec

t lite

rals

Enum

s w

ith fi

xed

unde

rlyin

g ty

pe

Subs

crip

ting

met

hods

Uno

rder

ed m

etho

d de

clar

atio

ns

sy

nthe

size

by d

efau

lt

Boxe

d Ex

pres

sions

2012WWDC 2012 Session 405 Modern Objective-C by Patrick C Beard

iOS Bootcamp

TIOBE Top 10 July 2012

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Long Term Trends

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Objective-C

Source httpwwwtiobecomindexphppaperinfotpciObjective-Chtml

Programming Language of the Year

2011

iOS Bootcamp

Ipse dixit Tom Love C++

ldquoObjective-C and C++ both started from C but they went in two very different directions Which approach do you prefer now

Tom Therersquos the successful direction and then therersquos the approach that Bjarne took with C++ In one case it was a small simple mdash dare I say elegant mdash programming language that was very crisp and well defined In the other case it was a pretty ugly complicated difficult language that had some really troublesome features I think those are the distinctions between the twordquo

iOS Bootcamp

Intervallo

iOS Bootcamp

The Language

iOS Bootcamp

Fundamental Laws

iOS Bootcamp

A strict superset of C

bull Objective-C is not inspired by C language like Java or C

bull Objective-C is a strict superset of the C language

bull Objective-C has only added some concepts and their associated keywords

bull Like with C++ a well-written C program should be compile-able as Objective-C

bull Unlike with C++ there is no risk of incompatibility between C names and Objective-C keywords

iOS Bootcamp

A strict superset of C

( ) [ ] catchclassdefsdynamicencodeendfinallyimplementationinterfaceoptional

privatepropertyprotectedprotocolpublicrequiredselectorsynchronizedsynthesizethrowtry

SELIMPnil Nil

BOOLYESNOid typ

edef

selfsuper

hidde

n par

amete

rsinoutinoutbycopy

byrefonewaygettersetter

readwritereadonlyassignretain

copynonatomicstrongweak av

ailab

le in

parti

cular

cont

exts

iOS Bootcamp

Requirements

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 30: Objective-C

iOS Bootcamp

2009

^ Blocks amp GCD

iOS Bootcamp

2010

Xcode 4

iOS Bootcamp

2011

Automatic Reference Counting

Messaggio Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Modern Objective-CO

bjec

t lite

rals

Enum

s w

ith fi

xed

unde

rlyin

g ty

pe

Subs

crip

ting

met

hods

Uno

rder

ed m

etho

d de

clar

atio

ns

sy

nthe

size

by d

efau

lt

Boxe

d Ex

pres

sions

2012WWDC 2012 Session 405 Modern Objective-C by Patrick C Beard

iOS Bootcamp

TIOBE Top 10 July 2012

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Long Term Trends

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Objective-C

Source httpwwwtiobecomindexphppaperinfotpciObjective-Chtml

Programming Language of the Year

2011

iOS Bootcamp

Ipse dixit Tom Love C++

ldquoObjective-C and C++ both started from C but they went in two very different directions Which approach do you prefer now

Tom Therersquos the successful direction and then therersquos the approach that Bjarne took with C++ In one case it was a small simple mdash dare I say elegant mdash programming language that was very crisp and well defined In the other case it was a pretty ugly complicated difficult language that had some really troublesome features I think those are the distinctions between the twordquo

iOS Bootcamp

Intervallo

iOS Bootcamp

The Language

iOS Bootcamp

Fundamental Laws

iOS Bootcamp

A strict superset of C

bull Objective-C is not inspired by C language like Java or C

bull Objective-C is a strict superset of the C language

bull Objective-C has only added some concepts and their associated keywords

bull Like with C++ a well-written C program should be compile-able as Objective-C

bull Unlike with C++ there is no risk of incompatibility between C names and Objective-C keywords

iOS Bootcamp

A strict superset of C

( ) [ ] catchclassdefsdynamicencodeendfinallyimplementationinterfaceoptional

privatepropertyprotectedprotocolpublicrequiredselectorsynchronizedsynthesizethrowtry

SELIMPnil Nil

BOOLYESNOid typ

edef

selfsuper

hidde

n par

amete

rsinoutinoutbycopy

byrefonewaygettersetter

readwritereadonlyassignretain

copynonatomicstrongweak av

ailab

le in

parti

cular

cont

exts

iOS Bootcamp

Requirements

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 31: Objective-C

iOS Bootcamp

2010

Xcode 4

iOS Bootcamp

2011

Automatic Reference Counting

Messaggio Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Modern Objective-CO

bjec

t lite

rals

Enum

s w

ith fi

xed

unde

rlyin

g ty

pe

Subs

crip

ting

met

hods

Uno

rder

ed m

etho

d de

clar

atio

ns

sy

nthe

size

by d

efau

lt

Boxe

d Ex

pres

sions

2012WWDC 2012 Session 405 Modern Objective-C by Patrick C Beard

iOS Bootcamp

TIOBE Top 10 July 2012

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Long Term Trends

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Objective-C

Source httpwwwtiobecomindexphppaperinfotpciObjective-Chtml

Programming Language of the Year

2011

iOS Bootcamp

Ipse dixit Tom Love C++

ldquoObjective-C and C++ both started from C but they went in two very different directions Which approach do you prefer now

Tom Therersquos the successful direction and then therersquos the approach that Bjarne took with C++ In one case it was a small simple mdash dare I say elegant mdash programming language that was very crisp and well defined In the other case it was a pretty ugly complicated difficult language that had some really troublesome features I think those are the distinctions between the twordquo

iOS Bootcamp

Intervallo

iOS Bootcamp

The Language

iOS Bootcamp

Fundamental Laws

iOS Bootcamp

A strict superset of C

bull Objective-C is not inspired by C language like Java or C

bull Objective-C is a strict superset of the C language

bull Objective-C has only added some concepts and their associated keywords

bull Like with C++ a well-written C program should be compile-able as Objective-C

bull Unlike with C++ there is no risk of incompatibility between C names and Objective-C keywords

iOS Bootcamp

A strict superset of C

( ) [ ] catchclassdefsdynamicencodeendfinallyimplementationinterfaceoptional

privatepropertyprotectedprotocolpublicrequiredselectorsynchronizedsynthesizethrowtry

SELIMPnil Nil

BOOLYESNOid typ

edef

selfsuper

hidde

n par

amete

rsinoutinoutbycopy

byrefonewaygettersetter

readwritereadonlyassignretain

copynonatomicstrongweak av

ailab

le in

parti

cular

cont

exts

iOS Bootcamp

Requirements

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 32: Objective-C

iOS Bootcamp

2011

Automatic Reference Counting

Messaggio Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Modern Objective-CO

bjec

t lite

rals

Enum

s w

ith fi

xed

unde

rlyin

g ty

pe

Subs

crip

ting

met

hods

Uno

rder

ed m

etho

d de

clar

atio

ns

sy

nthe

size

by d

efau

lt

Boxe

d Ex

pres

sions

2012WWDC 2012 Session 405 Modern Objective-C by Patrick C Beard

iOS Bootcamp

TIOBE Top 10 July 2012

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Long Term Trends

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Objective-C

Source httpwwwtiobecomindexphppaperinfotpciObjective-Chtml

Programming Language of the Year

2011

iOS Bootcamp

Ipse dixit Tom Love C++

ldquoObjective-C and C++ both started from C but they went in two very different directions Which approach do you prefer now

Tom Therersquos the successful direction and then therersquos the approach that Bjarne took with C++ In one case it was a small simple mdash dare I say elegant mdash programming language that was very crisp and well defined In the other case it was a pretty ugly complicated difficult language that had some really troublesome features I think those are the distinctions between the twordquo

iOS Bootcamp

Intervallo

iOS Bootcamp

The Language

iOS Bootcamp

Fundamental Laws

iOS Bootcamp

A strict superset of C

bull Objective-C is not inspired by C language like Java or C

bull Objective-C is a strict superset of the C language

bull Objective-C has only added some concepts and their associated keywords

bull Like with C++ a well-written C program should be compile-able as Objective-C

bull Unlike with C++ there is no risk of incompatibility between C names and Objective-C keywords

iOS Bootcamp

A strict superset of C

( ) [ ] catchclassdefsdynamicencodeendfinallyimplementationinterfaceoptional

privatepropertyprotectedprotocolpublicrequiredselectorsynchronizedsynthesizethrowtry

SELIMPnil Nil

BOOLYESNOid typ

edef

selfsuper

hidde

n par

amete

rsinoutinoutbycopy

byrefonewaygettersetter

readwritereadonlyassignretain

copynonatomicstrongweak av

ailab

le in

parti

cular

cont

exts

iOS Bootcamp

Requirements

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 33: Objective-C

iOS Bootcamp

Modern Objective-CO

bjec

t lite

rals

Enum

s w

ith fi

xed

unde

rlyin

g ty

pe

Subs

crip

ting

met

hods

Uno

rder

ed m

etho

d de

clar

atio

ns

sy

nthe

size

by d

efau

lt

Boxe

d Ex

pres

sions

2012WWDC 2012 Session 405 Modern Objective-C by Patrick C Beard

iOS Bootcamp

TIOBE Top 10 July 2012

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Long Term Trends

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Objective-C

Source httpwwwtiobecomindexphppaperinfotpciObjective-Chtml

Programming Language of the Year

2011

iOS Bootcamp

Ipse dixit Tom Love C++

ldquoObjective-C and C++ both started from C but they went in two very different directions Which approach do you prefer now

Tom Therersquos the successful direction and then therersquos the approach that Bjarne took with C++ In one case it was a small simple mdash dare I say elegant mdash programming language that was very crisp and well defined In the other case it was a pretty ugly complicated difficult language that had some really troublesome features I think those are the distinctions between the twordquo

iOS Bootcamp

Intervallo

iOS Bootcamp

The Language

iOS Bootcamp

Fundamental Laws

iOS Bootcamp

A strict superset of C

bull Objective-C is not inspired by C language like Java or C

bull Objective-C is a strict superset of the C language

bull Objective-C has only added some concepts and their associated keywords

bull Like with C++ a well-written C program should be compile-able as Objective-C

bull Unlike with C++ there is no risk of incompatibility between C names and Objective-C keywords

iOS Bootcamp

A strict superset of C

( ) [ ] catchclassdefsdynamicencodeendfinallyimplementationinterfaceoptional

privatepropertyprotectedprotocolpublicrequiredselectorsynchronizedsynthesizethrowtry

SELIMPnil Nil

BOOLYESNOid typ

edef

selfsuper

hidde

n par

amete

rsinoutinoutbycopy

byrefonewaygettersetter

readwritereadonlyassignretain

copynonatomicstrongweak av

ailab

le in

parti

cular

cont

exts

iOS Bootcamp

Requirements

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 34: Objective-C

iOS Bootcamp

TIOBE Top 10 July 2012

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Long Term Trends

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Objective-C

Source httpwwwtiobecomindexphppaperinfotpciObjective-Chtml

Programming Language of the Year

2011

iOS Bootcamp

Ipse dixit Tom Love C++

ldquoObjective-C and C++ both started from C but they went in two very different directions Which approach do you prefer now

Tom Therersquos the successful direction and then therersquos the approach that Bjarne took with C++ In one case it was a small simple mdash dare I say elegant mdash programming language that was very crisp and well defined In the other case it was a pretty ugly complicated difficult language that had some really troublesome features I think those are the distinctions between the twordquo

iOS Bootcamp

Intervallo

iOS Bootcamp

The Language

iOS Bootcamp

Fundamental Laws

iOS Bootcamp

A strict superset of C

bull Objective-C is not inspired by C language like Java or C

bull Objective-C is a strict superset of the C language

bull Objective-C has only added some concepts and their associated keywords

bull Like with C++ a well-written C program should be compile-able as Objective-C

bull Unlike with C++ there is no risk of incompatibility between C names and Objective-C keywords

iOS Bootcamp

A strict superset of C

( ) [ ] catchclassdefsdynamicencodeendfinallyimplementationinterfaceoptional

privatepropertyprotectedprotocolpublicrequiredselectorsynchronizedsynthesizethrowtry

SELIMPnil Nil

BOOLYESNOid typ

edef

selfsuper

hidde

n par

amete

rsinoutinoutbycopy

byrefonewaygettersetter

readwritereadonlyassignretain

copynonatomicstrongweak av

ailab

le in

parti

cular

cont

exts

iOS Bootcamp

Requirements

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 35: Objective-C

iOS Bootcamp

TIOBE Long Term Trends

Source httpwwwtiobecomindexphpcontentpaperinfotpciindexhtml

iOS Bootcamp

TIOBE Objective-C

Source httpwwwtiobecomindexphppaperinfotpciObjective-Chtml

Programming Language of the Year

2011

iOS Bootcamp

Ipse dixit Tom Love C++

ldquoObjective-C and C++ both started from C but they went in two very different directions Which approach do you prefer now

Tom Therersquos the successful direction and then therersquos the approach that Bjarne took with C++ In one case it was a small simple mdash dare I say elegant mdash programming language that was very crisp and well defined In the other case it was a pretty ugly complicated difficult language that had some really troublesome features I think those are the distinctions between the twordquo

iOS Bootcamp

Intervallo

iOS Bootcamp

The Language

iOS Bootcamp

Fundamental Laws

iOS Bootcamp

A strict superset of C

bull Objective-C is not inspired by C language like Java or C

bull Objective-C is a strict superset of the C language

bull Objective-C has only added some concepts and their associated keywords

bull Like with C++ a well-written C program should be compile-able as Objective-C

bull Unlike with C++ there is no risk of incompatibility between C names and Objective-C keywords

iOS Bootcamp

A strict superset of C

( ) [ ] catchclassdefsdynamicencodeendfinallyimplementationinterfaceoptional

privatepropertyprotectedprotocolpublicrequiredselectorsynchronizedsynthesizethrowtry

SELIMPnil Nil

BOOLYESNOid typ

edef

selfsuper

hidde

n par

amete

rsinoutinoutbycopy

byrefonewaygettersetter

readwritereadonlyassignretain

copynonatomicstrongweak av

ailab

le in

parti

cular

cont

exts

iOS Bootcamp

Requirements

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 36: Objective-C

iOS Bootcamp

TIOBE Objective-C

Source httpwwwtiobecomindexphppaperinfotpciObjective-Chtml

Programming Language of the Year

2011

iOS Bootcamp

Ipse dixit Tom Love C++

ldquoObjective-C and C++ both started from C but they went in two very different directions Which approach do you prefer now

Tom Therersquos the successful direction and then therersquos the approach that Bjarne took with C++ In one case it was a small simple mdash dare I say elegant mdash programming language that was very crisp and well defined In the other case it was a pretty ugly complicated difficult language that had some really troublesome features I think those are the distinctions between the twordquo

iOS Bootcamp

Intervallo

iOS Bootcamp

The Language

iOS Bootcamp

Fundamental Laws

iOS Bootcamp

A strict superset of C

bull Objective-C is not inspired by C language like Java or C

bull Objective-C is a strict superset of the C language

bull Objective-C has only added some concepts and their associated keywords

bull Like with C++ a well-written C program should be compile-able as Objective-C

bull Unlike with C++ there is no risk of incompatibility between C names and Objective-C keywords

iOS Bootcamp

A strict superset of C

( ) [ ] catchclassdefsdynamicencodeendfinallyimplementationinterfaceoptional

privatepropertyprotectedprotocolpublicrequiredselectorsynchronizedsynthesizethrowtry

SELIMPnil Nil

BOOLYESNOid typ

edef

selfsuper

hidde

n par

amete

rsinoutinoutbycopy

byrefonewaygettersetter

readwritereadonlyassignretain

copynonatomicstrongweak av

ailab

le in

parti

cular

cont

exts

iOS Bootcamp

Requirements

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 37: Objective-C

iOS Bootcamp

Ipse dixit Tom Love C++

ldquoObjective-C and C++ both started from C but they went in two very different directions Which approach do you prefer now

Tom Therersquos the successful direction and then therersquos the approach that Bjarne took with C++ In one case it was a small simple mdash dare I say elegant mdash programming language that was very crisp and well defined In the other case it was a pretty ugly complicated difficult language that had some really troublesome features I think those are the distinctions between the twordquo

iOS Bootcamp

Intervallo

iOS Bootcamp

The Language

iOS Bootcamp

Fundamental Laws

iOS Bootcamp

A strict superset of C

bull Objective-C is not inspired by C language like Java or C

bull Objective-C is a strict superset of the C language

bull Objective-C has only added some concepts and their associated keywords

bull Like with C++ a well-written C program should be compile-able as Objective-C

bull Unlike with C++ there is no risk of incompatibility between C names and Objective-C keywords

iOS Bootcamp

A strict superset of C

( ) [ ] catchclassdefsdynamicencodeendfinallyimplementationinterfaceoptional

privatepropertyprotectedprotocolpublicrequiredselectorsynchronizedsynthesizethrowtry

SELIMPnil Nil

BOOLYESNOid typ

edef

selfsuper

hidde

n par

amete

rsinoutinoutbycopy

byrefonewaygettersetter

readwritereadonlyassignretain

copynonatomicstrongweak av

ailab

le in

parti

cular

cont

exts

iOS Bootcamp

Requirements

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 38: Objective-C

iOS Bootcamp

Intervallo

iOS Bootcamp

The Language

iOS Bootcamp

Fundamental Laws

iOS Bootcamp

A strict superset of C

bull Objective-C is not inspired by C language like Java or C

bull Objective-C is a strict superset of the C language

bull Objective-C has only added some concepts and their associated keywords

bull Like with C++ a well-written C program should be compile-able as Objective-C

bull Unlike with C++ there is no risk of incompatibility between C names and Objective-C keywords

iOS Bootcamp

A strict superset of C

( ) [ ] catchclassdefsdynamicencodeendfinallyimplementationinterfaceoptional

privatepropertyprotectedprotocolpublicrequiredselectorsynchronizedsynthesizethrowtry

SELIMPnil Nil

BOOLYESNOid typ

edef

selfsuper

hidde

n par

amete

rsinoutinoutbycopy

byrefonewaygettersetter

readwritereadonlyassignretain

copynonatomicstrongweak av

ailab

le in

parti

cular

cont

exts

iOS Bootcamp

Requirements

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 39: Objective-C

iOS Bootcamp

The Language

iOS Bootcamp

Fundamental Laws

iOS Bootcamp

A strict superset of C

bull Objective-C is not inspired by C language like Java or C

bull Objective-C is a strict superset of the C language

bull Objective-C has only added some concepts and their associated keywords

bull Like with C++ a well-written C program should be compile-able as Objective-C

bull Unlike with C++ there is no risk of incompatibility between C names and Objective-C keywords

iOS Bootcamp

A strict superset of C

( ) [ ] catchclassdefsdynamicencodeendfinallyimplementationinterfaceoptional

privatepropertyprotectedprotocolpublicrequiredselectorsynchronizedsynthesizethrowtry

SELIMPnil Nil

BOOLYESNOid typ

edef

selfsuper

hidde

n par

amete

rsinoutinoutbycopy

byrefonewaygettersetter

readwritereadonlyassignretain

copynonatomicstrongweak av

ailab

le in

parti

cular

cont

exts

iOS Bootcamp

Requirements

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 40: Objective-C

iOS Bootcamp

Fundamental Laws

iOS Bootcamp

A strict superset of C

bull Objective-C is not inspired by C language like Java or C

bull Objective-C is a strict superset of the C language

bull Objective-C has only added some concepts and their associated keywords

bull Like with C++ a well-written C program should be compile-able as Objective-C

bull Unlike with C++ there is no risk of incompatibility between C names and Objective-C keywords

iOS Bootcamp

A strict superset of C

( ) [ ] catchclassdefsdynamicencodeendfinallyimplementationinterfaceoptional

privatepropertyprotectedprotocolpublicrequiredselectorsynchronizedsynthesizethrowtry

SELIMPnil Nil

BOOLYESNOid typ

edef

selfsuper

hidde

n par

amete

rsinoutinoutbycopy

byrefonewaygettersetter

readwritereadonlyassignretain

copynonatomicstrongweak av

ailab

le in

parti

cular

cont

exts

iOS Bootcamp

Requirements

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 41: Objective-C

iOS Bootcamp

A strict superset of C

bull Objective-C is not inspired by C language like Java or C

bull Objective-C is a strict superset of the C language

bull Objective-C has only added some concepts and their associated keywords

bull Like with C++ a well-written C program should be compile-able as Objective-C

bull Unlike with C++ there is no risk of incompatibility between C names and Objective-C keywords

iOS Bootcamp

A strict superset of C

( ) [ ] catchclassdefsdynamicencodeendfinallyimplementationinterfaceoptional

privatepropertyprotectedprotocolpublicrequiredselectorsynchronizedsynthesizethrowtry

SELIMPnil Nil

BOOLYESNOid typ

edef

selfsuper

hidde

n par

amete

rsinoutinoutbycopy

byrefonewaygettersetter

readwritereadonlyassignretain

copynonatomicstrongweak av

ailab

le in

parti

cular

cont

exts

iOS Bootcamp

Requirements

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 42: Objective-C

iOS Bootcamp

A strict superset of C

( ) [ ] catchclassdefsdynamicencodeendfinallyimplementationinterfaceoptional

privatepropertyprotectedprotocolpublicrequiredselectorsynchronizedsynthesizethrowtry

SELIMPnil Nil

BOOLYESNOid typ

edef

selfsuper

hidde

n par

amete

rsinoutinoutbycopy

byrefonewaygettersetter

readwritereadonlyassignretain

copynonatomicstrongweak av

ailab

le in

parti

cular

cont

exts

iOS Bootcamp

Requirements

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 43: Objective-C

iOS Bootcamp

Requirements

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 44: Objective-C

iOS Bootcamp

amp [ ]

Objective-C

function

Struct

void char int long float

for do whileif else switch case

typedef enum union

c string

const auto static extern

member selection -gt

preprocessor

c array

C Standard Library

sizeof

(type)casting

break continue goto

signed unsigned

function pointer

malloc free

format specifiers d s stack vs heap

int main(int argc const char argv[])

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 45: Objective-C

iOS Bootcamp

Inheritance

Objective-C

MethodClass

Polymorphism

Abstraction

Encapsulation

Message passing

Instance VariableDelegation

SuperclassMethod overriding

Subclass

Dynamic dispatch binding

Interface Protocol

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 46: Objective-C

iOS Bootcamp

Class

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 47: Objective-C

iOS Bootcamp

Bad News

NO namespaces Use prefix instead

NSObject NSString

UIButton UILabel

ABAddressBook ABRecord

Pragma MarkPMDeveloper PMEvent

Draft Proposal for Namespaces in Objective-C namespace usinghttpwwwoptshiftkcom201204draft-proposal-for-namespaces-in-objective-c

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 48: Objective-C

iOS Bootcamp

Class

interface implementation

Personm

import Personh

implementation Person

end

import

Personh

interface Person NSObject

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 49: Objective-C

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 50: Objective-C

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

base types import

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 51: Objective-C

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition start

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 52: Objective-C

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class name

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 53: Objective-C

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

parent class

extends

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 54: Objective-C

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

instancevariables

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 55: Objective-C

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

endmethods

declarations

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 56: Objective-C

iOS Bootcamp

Class interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSInteger _balance

- (NSInteger) withdraw(NSInteger)amount- (void) deposit(NSInteger)amount

end

class definition end

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 57: Objective-C

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 58: Objective-C

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

interfaceimport

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 59: Objective-C

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation start

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 60: Objective-C

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

methods with bodies

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 61: Objective-C

iOS Bootcamp

Class implementation

import BankAccounth

implementation BankAccount

- (id) init self = [super init] return self

- (NSInteger) withdraw(NSInteger)amount return amount

- (void) deposit(NSInteger)amount _balance += amountend

class implementation end

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 62: Objective-C

iOS Bootcamp

class directive

bull class directive provides minimal information about a class

bull class indicates that the name you are referencing is a class

bull The use of the class is known as a forward declaration

Rectanglemimport Rectangleh

import Pointh

implementation Rectangle

- (Point )center end

Rectanglehimport Shapeh

class Point

interface Rectangle Shape

- (Point )center

end

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 63: Objective-C

iOS Bootcamp

Instance Variable Declaration

interface MyClass NSObject private Can only be accessed by instances of MyClass NSInteger _privateIvar1 NSString _privateIvar2 protected Default Can only be accessed by instances of MyClass or MyClasss subclasses NSInteger _protectedIvar1 NSString _protectedIvar2

package 64-bit only Can be accessed by any object in the framework in which MyClass is defined NSInteger _packageIvar1 NSString _packageIvar2 public Never use it Can be accessed by any object NSInteger _publicVar1 NSString _publicVar2

scopequalifiers

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 64: Objective-C

iOS Bootcamp

Method amp Message

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 65: Objective-C

iOS Bootcamp

In other languages might be

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

bool MyClasswriteToFileAtomically(stdstring path bool flag) C++

public virtual bool WriteToFileAtomically(string path bool flag) C

public boolean writeToFileAtomically(String path boolean flag) Java

public function writeToFileAtomically(path flag) PHP

def writeToFileAtomically(self path flag) Python

def writeToFileAtomically(path flag) Ruby

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 66: Objective-C

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method scope

Can be either

+ for a class method

- for an instance method

Methods are always public

ldquoPrivaterdquo methods defined in implementation

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 67: Objective-C

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

return type

Can be any valid data type including

void returns nothing

id a pointer to an object of any class

NSString a pointer to an NSString

BOOL a boolean (YES or NO)

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 68: Objective-C

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

method name

The method name is composed of all labels

Colons precede arguments but are part of the method name

writeTofileatomically

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 69: Objective-C

iOS Bootcamp

Method Declaration

- (BOOL) writeToFile(NSString )path atomically(BOOL)flag

argument type

Arguments come after or within the method name

Variadic methods can take variable arguments

- (id)stringWithFormat(NSString )format stdarg va_list va_start() va_arg() va_end()

argument name

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 70: Objective-C

iOS Bootcamp

selector

SEL callback = selector(writeToFileatomically)

data type for selector

Conceptually similar to function pointer

Useful for callback type behavior

macro to create selector

if ([helper respondsToSelectorcallback]) [helper performSelectorcallback withObjectarguments]

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 71: Objective-C

iOS Bootcamp

Message Passing

bull Methods are invoked by passing messages

bull Messages arenrsquot bound to method implementations until runtime The compiler converts a message expression

bull into a call on a messaging function objc_msgSend

bull Any arguments passed in the message are also handed to objc_msgSend

objc_msgSend(receiver selector)

objc_msgSend(receiver selector arg1 arg2 )

[receiver message]

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 72: Objective-C

iOS Bootcamp

In other languages might be

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

data-gtwriteToFileAtomically(tmpdatatxt true) C++

dataWriteToFileAtomically(tmpdatatxt true) C

datawriteToFileAtomically(tmpdatatxt true) Java

$data-gtwriteToFileAtomically(tmpdatatxt TRUE) PHP

datawriteToFileAtomically(tmpdatatxt True) Python

datawriteToFileAtomically tmpdatatxt true Ruby

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 73: Objective-C

iOS Bootcamp

Message Passing

[data writeToFiletmpdatatxt atomicallyYES]

square brackets syntax

Nested Message Passing [ [ ] [ ] [ [ ] ] ]

[[store data] writeToFile[tmpdatatxt lowercaseString] atomically[[PMOption sharedOption] writeMode] encodingNSUTF8StringEncoding erroramperror]

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 74: Objective-C

iOS Bootcamp

Message Forwarding

bull In Objective C is very common to do message forwarding (a strategy pattern)

bull When an object receives a message and it does not have a corresponding method it can delegates the task to another object

- (void)forwardInvocation(NSInvocation)invocation SEL sel = [invocation selector] if ([helper respondsToSelectorsel]) [invocation invokeWithTargethelper] else [self doesNotRecognizeSelectorsel]

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 75: Objective-C

iOS Bootcamp

Message Terminology

bull Message expression

bull Message

bull Selector

bull Method

[data writeToFiletmpdatatxt atomicallyYES]

The code selected by a message

[data writeToFiletmpdatatxt atomicallyYES]

[data writeToFiletmpdatatxt atomicallyYES]

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 76: Objective-C

iOS Bootcamp

Self amp Super

bull Methods have implicit reference to owning object called self (similar to Java and C this but self is a l-value)

bull Additionally have access to superclass methods using super

- (void)viewWillAppear(BOOL)animated [super viewWillAppearanimated] [self reloadData]

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 77: Objective-C

iOS Bootcamp

ObjectLife Cycle

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 78: Objective-C

iOS Bootcamp

Object Constructionbull NSObject defines class method called alloc

bull Dynamically allocates memory for object on the heap

bull Returns new instance of receiving class

bull NSObject defines instance method called init

bull Implemented by subclasses to initialize instance after memory has been allocated

bull Subclasses commonly define several initializers (default indicated in documentation)

bull alloc and init calls are always nested into single line

BankAccount account = [BankAccount alloc]

BankAccount account = [[BankAccount alloc] init]

BankAccount account = [[BankAccount alloc] init]

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 79: Objective-C

iOS Bootcamp

Object ConstructioninitWithhellip

bull Needs to call super

bull Setup instance variables

bull Returns self

- (id) init self = [super init] if (self) _myInstanceVariable = Pragma Mark return self

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 80: Objective-C

iOS Bootcamp

Object Destructiondealloc

bull Never call explicitly

bull Release all retained or copied instance variables ( if not ARC)

bull Calls [super dealloc] ( if not ARC)

- (void)saveThis(id)object if (_myInstanceVariable = object ) [_myInstanceVariable release] _myInstanceVariable = [object retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 81: Objective-C

iOS Bootcamp

Memory Management

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 82: Objective-C

iOS Bootcamp

Memory Management

bull Manual Reference Counting

bull Higher level abstraction than malloc free

bull Straightforward approach but must adhere to conventions and rules

bull Automatic Reference Counting (ARC)

bull Makes memory management the job of the compiler (and runtime)

bull Available for partially iOS 4+ or OS X 106+ fully iOS 5+ or OS X 107+

bull Garbage Collection

bull Only available for OS X 105+

bull Not available on iOS due to performance concerns

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 83: Objective-C

iOS Bootcamp

Manual Reference Counting

alloc retain

2

release

1

release

1

dealloc

0

(Only) objective-C objects are reference counted

bull Objects start with retain count of 1

bull Increased with retain

bull Decreased with release autorelease

bull When count equals 0 runtime invokes dealloc

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 84: Objective-C

iOS Bootcamp

Objects you createFor objects you create with [[SomeClass alloc] init] or [myInstance copy] (without autoreleasing)

bull Retain should not need to be called

bull Release when you are done using it in the code block

- (void)someMethod NSArray someArray = [[NSArray alloc] init] _myInstanceVariable = someArray

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 85: Objective-C

iOS Bootcamp

Objects you donrsquot createFor objects you donrsquot create (eg get from methods)

bull Retain only when saving to instance (or static) variable

bull Release only if you retained it by saving it (as in above case)

- (void)someMethod id anObject = [someArray objectAtIndex0] _myInstanceVariable = [anObject retain]

- (void)dealloc [_myInstanceVariable release] [super dealloc]

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 86: Objective-C

iOS Bootcamp

AutoreleaseWhat if you create an object and you are returning it from a method how would you be able to release it

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray autorelease]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return [myArray release]

- (NSArray )objects NSArray myArray = [[NSArray alloc] init] return myArray

Leak

Crash

Right

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 87: Objective-C

iOS Bootcamp

Autorelease

bull Instead of explicitly releasing something you mark it for a later release

bull An object called autorelease pool manages a set of objects to release when the pool is released

bull Add an object to the release pool by calling autorelease

autoreleasepool code goes here

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] code goes here[pool release]

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 88: Objective-C

iOS Bootcamp

Autorelease

bull Autorelease is NOT a Garbage Collector It is deterministic

bull Objects returned from methods are understood to be autoreleased if name is not in implicit retained set (alloc new init or copy)

bull If you spawn your own thread yoursquoll have to create your own NSAutoreleasePool

bull Stack based autorelease pools can be nested

Friday QampA 2011-09-02 Lets Build NSAutoreleasePoolhttpwwwmikeashcompyblogfriday-qa-2011-09-02-lets-build-nsautoreleasepoolhtml

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 89: Objective-C

iOS Bootcamp

Memory Management Rule

Everything that increases the retain count with alloc [mutable]copy[WithZone] or retain is in

charge of the corresponding [auto]release

From C++ to Objective-Chttppierrechachatelierfrprogrammationobjective-cphp

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 90: Objective-C

iOS Bootcamp

Automatic Reference Counting

ldquoAutomatic Reference Counting (ARC) in Objective-C makes memory management the job of the compiler By enabling ARC with the new Apple LLVM compiler you will never need to type retain or release again dramatically simplifying the development process while reducing crashes and memory leaks The compiler has a complete understanding of your objects and releases each object the instant it is no longer used so apps run as fast as ever with predictable smooth performancerdquo

(Apple ldquoiOS 5 for developersrdquo ndash httpdeveloperapplecomtechnologiesios5)

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 91: Objective-C

iOS Bootcamp

Automatic Reference Counting

bull The Rule is still valid but it is managed by the compiler

bull No more retain release autorelease nor dealloc

bull New lifetime qualifiers for objects which includes zeroing weak references (only available on iOS 5+ amp OS X 107+)

bull Apple provides a migration tool which is build into Xcode

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 92: Objective-C

iOS Bootcamp

Automatic Reference Counting

Messaggio Auto-Promozionale httpwwwwhymcaorginterventoautomatic-reference-counting

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 93: Objective-C

iOS Bootcamp

Property

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 94: Objective-C

iOS Bootcamp

Property

bull Objective-C 20 introduced new syntax for defining accessor code

bull Much less verbose less error prone

bull Highly configurable

bull Automatically generates accessor code

bull Complementary to existing conventions and technologies

bull Key-Value Coding (KVC)

bull Key-Value Observing (KVO)

bull Cocoa Bindings

bull Core Data Simplifying Accessors

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 95: Objective-C

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 96: Objective-C

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readonly) NSString accountNumber

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 97: Objective-C

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

setter getter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(getter=isActive) BOOL active

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 98: Objective-C

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(nonatomic retain) NSDate createdAt

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 99: Objective-C

iOS Bootcamp

Property Declarationproperty(attributes) type name

Attribute Impacts

readonly readwrite Mutability

getter setter API

nonatomic Concurrency

assign retain copy weak strong ( in ARC) Storage

property(readwrite copy) NSString accountNumber

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 100: Objective-C

iOS Bootcamp

Retain Cycles

1 1retain

retain

Parent Child

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 101: Objective-C

iOS Bootcamp

Retain Cycles

0 1retain

assign

Parent Child

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 102: Objective-C

iOS Bootcamp

Retain Cycles

X

Xnil release

Controller as View Delegate

View

assign

weak

New with ARC iniOS 5+ amp OS X 107+

unsafe_unretained

nil

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 103: Objective-C

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject NSString _accountNumber NSDecimalNumber _balance NSDecimalNumber _fees BOOL _active

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 104: Objective-C

iOS Bootcamp

Property interface

import ltFoundationFoundationhgt

interface BankAccount NSObject No more instance variable declarations

property(readwrite copy) NSString accountNumberproperty(readwrite retain) NSDecimalNumber balanceproperty(readonly) NSDecimalNumber feesproperty(getter=isActive) BOOL active

end

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 105: Objective-C

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

synthesize accountNumber = _accountNumbersynthesize balance = _balancesynthesize fees = _feessynthesize active = _active

end

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 106: Objective-C

iOS Bootcamp

Property implementation

import BankAccounth

implementation BankAccount

No more synthesize statements

end

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 107: Objective-C

iOS Bootcamp

Property Access

bull Generated properties are standard methods

bull Accessed through normal messaging syntax

bull Objective-C 20 property access via dot syntax

bull Dot notation is just syntactic sugar Still uses accessor methods Doesnt getset values directly

id value = [object property][object setPropertynewValue]

id value = objectpropertyobjectproperty = newValue

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 108: Objective-C

iOS Bootcamp

Protocol

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 109: Objective-C

iOS Bootcamp

Protocol

bull List of method declarations

bull Not associated with a particular class

bull Conformance not class is important

bull Useful in defining

bull Methods that others are expected to implement

bull Declaring an interface while hiding its particular class

bull Capturing similarities among classes that arent hierarchically related

Java C Interface done Objective-C style

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 110: Objective-C

iOS Bootcamp

Protocol

bull Defining a Protocol

bull Adopting a Protocol

protocol NSCoding

- (void)encodeWithCoder(NSCoder )aCoder- (id)initWithCoder(NSCoder )aDecoder

end

interface Person NSObjectltNSCodinggt NSString _name method amp property declarationsend

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 111: Objective-C

iOS Bootcamp

Protocol

bull Conforming to a Protocol

implementation Person

Partial implementation of conforming Person class

- (id)initWithCoder(NSCoder )coder if (self = [super init]) _name = [coder decodeObjectForKeyname] [_name retain] return self

- (void)encodeWithCoder(NSCoder )coder [coder encodeObject_name forKeyname]end

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 112: Objective-C

iOS Bootcamp

required amp optional

bull Protocols methods are required by default

bull Can be relaxed with optional directive

protocol SomeProtocol

- (void)requiredMethod

optional

- (void)anOptionalMethod- (void)anotherOptionalMethod

required

- (void)anotherRequiredMethod

end

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 113: Objective-C

iOS Bootcamp

Category amp Extension

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 114: Objective-C

iOS Bootcamp

Category

bull Add new methods to existing classes

bull Alternative to subclassing

bull Defines new methods and can override existing

bull Does not define new instance variables ( in case use Associative References)

bull Becomes part of the class definition (Inherited by subclasses)

bull Can be used as organizational tool

bull Often used in defining ldquoprivaterdquo methods

Extending Object Features

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 115: Objective-C

iOS Bootcamp

import NSString+PMAdditionh NSString string = A string to be trimmedNSLog(Trimmed string [string trim])

Categorybull Defining and using a Category

File NSString+PMAdditionmimplementation NSString (PMAddition)- (NSString )trim NSCharacterSet cs cs = [NSCharacterSet whitespaceAndNewlineCharacterSet] return [self stringByTrimmingCharactersInSetcharSet]end

File NSString+PMAdditionhinterface NSString (PMAddition)- (NSString )trimend

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 116: Objective-C

iOS Bootcamp

Class Extension

bull Objective-C 20 adds ability to define anonymous categories

bull Class extension is unnamed

bull Treated as class interface continuations

bull Useful for implementing required ldquoprivaterdquo API

bull Compiler enforces methods are implemented

Unnamed Categories

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 117: Objective-C

iOS Bootcamp

Class Extension

interface Person NSObject NSUInteger _age

- (NSUInteger)age

end

bull Interface

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 118: Objective-C

iOS Bootcamp

bull Implementation + ldquoPrivaterdquo Method

Class Extension

interface Person ()

- (void)setAge(NSUInteger)age

end

implementation Person

- (NSUInteger)age return _age

- (void)setAge(NSUInteger)age _age = age

end

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 119: Objective-C

iOS Bootcamp

Exception amp Block

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 120: Objective-C

iOS Bootcamp

bull Very few uses for try catch throw and finally

bull Reserve the use of exceptions for programming or unexpected runtime errors (very different from Java C)

bull NSError and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors

try do somethingcatch (NSException e) handle exceptionfinally close resources

- (BOOL)removeItemAtPath(NSString )path error(NSError )error

Exception

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 121: Objective-C

iOS Bootcamp

bull Similar to standard C functions but in addition to executable code blocks may also contain variable bindings

bull Also called closures (or lambdas) because they close around variables in their scope

bull A nonstandard extension to C

bull Used as anonymous functions

Block

[objects sortUsingComparator^(id firstObject id secondObject) return [firstObject comparesecondObject]

]

int (^myBlock)(int) = ^(int num) return num multipier

New in iOS 4+ amp OS X 106+

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 122: Objective-C

iOS Bootcamp

Base Type

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 123: Objective-C

iOS Bootcamp

Dynamic and Static Typing

bull Dynamically-typed object

bull Just id

bull Not id (unless you really really mean it pointer to pointer)

bull Statically-typed object

bull Objective-C provides compile-time type checking

bull Objective-C always uses dynamic binding

id anObject

BankAccount anObject

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 124: Objective-C

iOS Bootcamp

The nil object pointerbull Test for nil explicitly

bull Or implicitly

bull Can use in assignments and as arguments if expected

bull Sending a message to nil NO Problem

if (nil == person) return Yoda Syntax lt(-_-)gt

if (person) return

person = nil[button setTarget nil]

person = nil[person talk]

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 125: Objective-C

iOS Bootcamp

The BOOL typedefbull When Objective-C was developed C had no boolean type

(C99 introduced one)

bull Objective-C uses a typedef to define BOOL as a type

bull Macro included for initialization and comparison YES and NO

BOOL flag = NO

if (flag) if (flag)

if (YES == flag) use flagif (NO == flag)

flag = YESflag = 1

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 126: Objective-C

iOS Bootcamp

Foundation Framework

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 127: Objective-C

iOS Bootcamp

bull Frameworks are functionally similar to shared libraries

bull A compiled object that can be dynamically loaded into a programs address space at runtime

bull Frameworks add associated resources header files and documentation

Framework

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 128: Objective-C

iOS Bootcamp

bull Values and Strings

bull Collections

bull User defaults

bull Archiving

bull Notifications

bull Tasks timers threads

bull File system IO bundles

bull URL XML Scanner

Foundationframework

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 129: Objective-C

iOS Bootcamp

bull Root Class

bull Implements many basics

bull Memory management

bull Introspection

bull Object equality

bull String representation (description is like toString() in Java or ToString() in C)

NSObjectinterface BankAccount NSObject

if ([anObject isKindOfClass[Person class]])

if ([obj1 isEqualobj2]) NOT obj1 == obj2

NSLog( [anObject description])NSLog( anObject) call description

[anObject retain]

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 130: Objective-C

iOS Bootcamp

bull General-purpose Unicode string support

bull NSString objects are conceptually UTF-16 endianness

bull Consistently used in Cocoa instead of ldquoconst char rdquo

bull Objective-C string literals start with

bull NSString is immutable NSMutableString is mutable

NSString

const char cString = Pragma Mark C stringNSString nsString = バンザイ NSString

cString = [nsString UTF8String]nsString = [NSString stringWithCStringcString

encodingNSUTF8StringEncoding]

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 131: Objective-C

iOS Bootcamp

Format Strings

bull Similar to printf but with added for objects

bull Also used for logging with NSLog macro

NSString title = The PreacherNSString whoami = [NSString stringWithFormat I am title]

whoami would be set to I am The Preacher

NSLog(I am a I have d items [array className] [array count])

would log something like I am a NSArray I have 42 items

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 132: Objective-C

iOS Bootcamp

bull NSArray - ordered collection of objects

bull NSDictionary - collection of key-value pairs

bull NSSet - unordered collection of unique objects

bull Immutable and mutable versions

bull Immutable collections can be shared without side effect

bull Mutable objects typically carry a performance overhead

Collections

NSDictionary dicdic = [[NSDictionary alloc] initWithObjectsAndKeys ga username 42 password nil] nil to signify end of objects and keys

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 133: Objective-C

iOS Bootcamp

bull Collections can contain only objects

bull Wrap primitive types in NSNumber or NSValue

bull New literal syntax for

bull array [ obj ]

bull dictionary key obj

bull boxed expressions ( number or c string ) As a shortcut number literals can be boxed without using the ( )

Collections

NSArray a = [42 42 42 314]

NSDictionary d = 1 black 2 white

New in Xcode 44+

(WWDC 2012)

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 134: Objective-C

iOS Bootcamp

bull Added in Objective-C 20

bull for in similar to Java C foreach

bull Use with NSArray NSDictionary NSSet or with any object of class that adopt the NSFastEnumeration protocol

Fast Enumeration

NSArray people

Old schoolfor (int i = 0 i lt [people count] ++i) Person person = [people objectAtIndexi]

New schoolfor (Person person in people)

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 135: Objective-C

iOS Bootcamp

Summary

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 136: Objective-C

iOS Bootcamp

bull Fully C Fully Object-Oriented Powerful Dynamic Runtime

bull Objective-C 20 added many useful new features

bull Garbage Collection for Mac OS X apps

bull Properties Improved Categories amp Protocols

bull Objective-C LLVM continues evolution

bull Blocks (Closures)

bull Automatic Reference Counting

bull Synthesize by default for properties

bull New literals

Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 137: Objective-C

iOS Bootcamp

Objective-C Reference Books

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 138: Objective-C

iOS Bootcamp

Are you bored

The Objective-C Programming Language

Objective-C Runtime Programming Guide

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 139: Objective-C

iOS Bootcamp

Questions

giuseppearicigmailcom

thepreacherpragmamarkorg

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 140: Objective-C

iOS Bootcamp

Whatrsquos NeXT AR

C M

emor

y

Man

agem

ent R

eloa

ded

All a

bout

^Bl

ock

amp

Gra

nd C

entr

al D

ispat

ch

Code Generation

With LLVM

Metaprogramming in

Objective-C

Objective-CRuntimes Delight

Never Say Never AgainThe Objective-C++

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 141: Objective-C

iOS Bootcamp

One More Thing

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg

Page 142: Objective-C

iOS Bootcamp

Thanks

giuseppearicicom pragmamarkorg