Automatic Reference Counting

118
MOBILE DEVELOPER CONFERENCE 24 – 25 MAGGIO 2012 Giuseppe Arici - @giuseppearici Superpartes Innovation Campus Automatic Reference Counting 1

description

Slides della sessione su Automatic Reference Counting, tenuta da Giuseppe Arici alla WhyMCA 2012. http://www.whymca.org/intervento/automatic-reference-counting ----- Presentata da Apple nel corso dell'ultima WWDC, l'Automatic Reference Counting, secondo gli ingegneri di Cupertino, è la soluzione definitiva all'annoso problema della gestione della memoria nello sviluppo di applicazioni Mac e iOS. ARC promette di ridurre notevolmente il carico di lavoro del programmatore, limitando al minimo la possibilità di errore ed assicurando al contempo un aumento significativo delle prestazioni. Nella compilazione di codice Objective-C, con ARC, il programmatore è sollevato dalla responsabilità di applicare in modo meccanico e ripetitivo le regole fondamentali della gestione della memoria. Inoltre ARC si propone di migliorare l'attività di sviluppo, senza per questo gravare sulle prestazioni del sistema, sulla durata della batteria e sulla sicurezza del codice prodotto. In un ambiente nativo con accesso libero ai puntatori, ARC rappresenta il migliore compromesso possibile tra la gestione manuale della memoria e la garbage collection completamente automatica. In questa sessione si presenteranno le pratiche che permettono di sfruttare al meglio le potenzialità di ARC, si illustreranno le tecniche di migrazione del codice preesistente al nuovo modello di gestione della memoria e si esamineranno i problemi più ricorrenti che si possono incontrare utilizzando ARC in progetti di media complessità.

Transcript of Automatic Reference Counting

Page 1: Automatic Reference Counting

MOBILE DEVELOPER CONFERENCE 24 ndash 25 MAGGIO 2012

Giuseppe Arici - giuseppeariciSuperpartes Innovation Campus

Automatic Reference Counting

1

2

Giuseppe ARiCi Apple iOS amp Mac OS X Addicted Developer

Superpartes 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

ARC3

Attenzione egrave un medicinale leggere attentamente il foglio illustrativo Consultare il medico se il disturbo si presenta ripetutamente I medicinali

vanno assunti con cautela per un breve periodo di tempo non superando le dosi consigliate e solo per le indicazioni riportate nel foglio illustrativo In caso di dubbio rivolgersi al medico o al farmacista Tenere il medicinale fuori dalla

portata e dalla vista dei bambini Da usare solo in etagrave adulta

4

OS X amp iOS5

6

Session Timeline

bull Da dove nasce

bull Che cosrsquoegrave

bull Come funziona

bull Quando utilizzarlo

ARC

Memory Management 100

UIImage lt0x12345678gt

rdquoHello WhyMCA rdquo

NSData lt0a1b2c3d4egt

UIVIew Backing Store

7

Memory Management 100

UIImage lt0x12345678gt

UIVIew Backing Store

8

malloc free

UIImage lt0x12345678gt

UIVIew Backing Store

9

Manual Reference Counting

UIImage lt0x12345678gt

UIVIew Backing Store

1

3

10

Manual Reference Counting

UIImage lt0x12345678gt

UIVIew Backing Store

1

2

11

Manual Reference Counting

UIVIew Backing Store

0

2

12

Garbage Collection 100

13

Generation 1 Generation 2 Generation 3

Garbage Collection 200

14

Garbage Collection 300

15

Garbage Collection 300

16

Garbage Collection 300

17

Garbage Collection 300

18

Heap Compaction

Garbage Collection 400

High Performance Concurrent Garbage Collector

19

Garbage Collection 400

X

20

read barrier

C GCvs

21

Puntatori che giocano a Nascondino

22

Apple lrsquoha fatto comunque

23

Limiti del GC Objective-C

24

Limiti del GC Objective-C

NSData data = [obj someData]const char bytes = [data bytes]

NSUInteger length = [data length]for (NSUInteger i = 0 i lt length ++i) printf(ldquoxrdquo bytes[i])

25

Limiti del GC Objective-C

26

Limiti del GC Objective-C

27

iPhone GCvs

28

iPhone Androidvs

29

30

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)

31

Static Analyzer

32

Analysis + Auto-Fix + Goodies

33

Requisiti di Sistema

bull iOS 5

bull OS X 107

bull iOS 4 - no runtime

bull OS X 106 (64-bit) - no runtime

34

Requisiti di Runtime

bull Clang (LLVM compiler) 30 or later

bull Obj-C Runtime objc4 4939 or later

bull For iOS4 or OS X 106 libarclite_iphoneosa or libarclite_macosxa is linked to make ARC work

35

Conversione ad ARC

36

Conversione ad ARC

37

Conversione ad ARC

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

autoreleasepool code here NSString s = [(id)CFStringCreateWithX(hellip) autorelease] NSString s = CFBridgingRelease(CFStringCreateWithX(hellip))

38

Conversione Automatica

39

From the command line via the -ccc-arcmt-check and -ccc-arcmt-modify arguments

Conversione Automatica

40

Nessuno egrave perfetto

41

Strani Autorelease Pools

Toll-Free Bridging

Structs

Giochetti con i Puntatori

Singleton

Eccezioni

case

Blocks

Conversione Parziale

42

43

ARC egrave costituito da due componenti principali

bull ARC front end compiler

bull ARC optimizer

Come Funziona ARC

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 2: Automatic Reference Counting

2

Giuseppe ARiCi Apple iOS amp Mac OS X Addicted Developer

Superpartes 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

ARC3

Attenzione egrave un medicinale leggere attentamente il foglio illustrativo Consultare il medico se il disturbo si presenta ripetutamente I medicinali

vanno assunti con cautela per un breve periodo di tempo non superando le dosi consigliate e solo per le indicazioni riportate nel foglio illustrativo In caso di dubbio rivolgersi al medico o al farmacista Tenere il medicinale fuori dalla

portata e dalla vista dei bambini Da usare solo in etagrave adulta

4

OS X amp iOS5

6

Session Timeline

bull Da dove nasce

bull Che cosrsquoegrave

bull Come funziona

bull Quando utilizzarlo

ARC

Memory Management 100

UIImage lt0x12345678gt

rdquoHello WhyMCA rdquo

NSData lt0a1b2c3d4egt

UIVIew Backing Store

7

Memory Management 100

UIImage lt0x12345678gt

UIVIew Backing Store

8

malloc free

UIImage lt0x12345678gt

UIVIew Backing Store

9

Manual Reference Counting

UIImage lt0x12345678gt

UIVIew Backing Store

1

3

10

Manual Reference Counting

UIImage lt0x12345678gt

UIVIew Backing Store

1

2

11

Manual Reference Counting

UIVIew Backing Store

0

2

12

Garbage Collection 100

13

Generation 1 Generation 2 Generation 3

Garbage Collection 200

14

Garbage Collection 300

15

Garbage Collection 300

16

Garbage Collection 300

17

Garbage Collection 300

18

Heap Compaction

Garbage Collection 400

High Performance Concurrent Garbage Collector

19

Garbage Collection 400

X

20

read barrier

C GCvs

21

Puntatori che giocano a Nascondino

22

Apple lrsquoha fatto comunque

23

Limiti del GC Objective-C

24

Limiti del GC Objective-C

NSData data = [obj someData]const char bytes = [data bytes]

NSUInteger length = [data length]for (NSUInteger i = 0 i lt length ++i) printf(ldquoxrdquo bytes[i])

25

Limiti del GC Objective-C

26

Limiti del GC Objective-C

27

iPhone GCvs

28

iPhone Androidvs

29

30

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)

31

Static Analyzer

32

Analysis + Auto-Fix + Goodies

33

Requisiti di Sistema

bull iOS 5

bull OS X 107

bull iOS 4 - no runtime

bull OS X 106 (64-bit) - no runtime

34

Requisiti di Runtime

bull Clang (LLVM compiler) 30 or later

bull Obj-C Runtime objc4 4939 or later

bull For iOS4 or OS X 106 libarclite_iphoneosa or libarclite_macosxa is linked to make ARC work

35

Conversione ad ARC

36

Conversione ad ARC

37

Conversione ad ARC

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

autoreleasepool code here NSString s = [(id)CFStringCreateWithX(hellip) autorelease] NSString s = CFBridgingRelease(CFStringCreateWithX(hellip))

38

Conversione Automatica

39

From the command line via the -ccc-arcmt-check and -ccc-arcmt-modify arguments

Conversione Automatica

40

Nessuno egrave perfetto

41

Strani Autorelease Pools

Toll-Free Bridging

Structs

Giochetti con i Puntatori

Singleton

Eccezioni

case

Blocks

Conversione Parziale

42

43

ARC egrave costituito da due componenti principali

bull ARC front end compiler

bull ARC optimizer

Come Funziona ARC

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 3: Automatic Reference Counting

ARC3

Attenzione egrave un medicinale leggere attentamente il foglio illustrativo Consultare il medico se il disturbo si presenta ripetutamente I medicinali

vanno assunti con cautela per un breve periodo di tempo non superando le dosi consigliate e solo per le indicazioni riportate nel foglio illustrativo In caso di dubbio rivolgersi al medico o al farmacista Tenere il medicinale fuori dalla

portata e dalla vista dei bambini Da usare solo in etagrave adulta

4

OS X amp iOS5

6

Session Timeline

bull Da dove nasce

bull Che cosrsquoegrave

bull Come funziona

bull Quando utilizzarlo

ARC

Memory Management 100

UIImage lt0x12345678gt

rdquoHello WhyMCA rdquo

NSData lt0a1b2c3d4egt

UIVIew Backing Store

7

Memory Management 100

UIImage lt0x12345678gt

UIVIew Backing Store

8

malloc free

UIImage lt0x12345678gt

UIVIew Backing Store

9

Manual Reference Counting

UIImage lt0x12345678gt

UIVIew Backing Store

1

3

10

Manual Reference Counting

UIImage lt0x12345678gt

UIVIew Backing Store

1

2

11

Manual Reference Counting

UIVIew Backing Store

0

2

12

Garbage Collection 100

13

Generation 1 Generation 2 Generation 3

Garbage Collection 200

14

Garbage Collection 300

15

Garbage Collection 300

16

Garbage Collection 300

17

Garbage Collection 300

18

Heap Compaction

Garbage Collection 400

High Performance Concurrent Garbage Collector

19

Garbage Collection 400

X

20

read barrier

C GCvs

21

Puntatori che giocano a Nascondino

22

Apple lrsquoha fatto comunque

23

Limiti del GC Objective-C

24

Limiti del GC Objective-C

NSData data = [obj someData]const char bytes = [data bytes]

NSUInteger length = [data length]for (NSUInteger i = 0 i lt length ++i) printf(ldquoxrdquo bytes[i])

25

Limiti del GC Objective-C

26

Limiti del GC Objective-C

27

iPhone GCvs

28

iPhone Androidvs

29

30

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)

31

Static Analyzer

32

Analysis + Auto-Fix + Goodies

33

Requisiti di Sistema

bull iOS 5

bull OS X 107

bull iOS 4 - no runtime

bull OS X 106 (64-bit) - no runtime

34

Requisiti di Runtime

bull Clang (LLVM compiler) 30 or later

bull Obj-C Runtime objc4 4939 or later

bull For iOS4 or OS X 106 libarclite_iphoneosa or libarclite_macosxa is linked to make ARC work

35

Conversione ad ARC

36

Conversione ad ARC

37

Conversione ad ARC

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

autoreleasepool code here NSString s = [(id)CFStringCreateWithX(hellip) autorelease] NSString s = CFBridgingRelease(CFStringCreateWithX(hellip))

38

Conversione Automatica

39

From the command line via the -ccc-arcmt-check and -ccc-arcmt-modify arguments

Conversione Automatica

40

Nessuno egrave perfetto

41

Strani Autorelease Pools

Toll-Free Bridging

Structs

Giochetti con i Puntatori

Singleton

Eccezioni

case

Blocks

Conversione Parziale

42

43

ARC egrave costituito da due componenti principali

bull ARC front end compiler

bull ARC optimizer

Come Funziona ARC

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 4: Automatic Reference Counting

Attenzione egrave un medicinale leggere attentamente il foglio illustrativo Consultare il medico se il disturbo si presenta ripetutamente I medicinali

vanno assunti con cautela per un breve periodo di tempo non superando le dosi consigliate e solo per le indicazioni riportate nel foglio illustrativo In caso di dubbio rivolgersi al medico o al farmacista Tenere il medicinale fuori dalla

portata e dalla vista dei bambini Da usare solo in etagrave adulta

4

OS X amp iOS5

6

Session Timeline

bull Da dove nasce

bull Che cosrsquoegrave

bull Come funziona

bull Quando utilizzarlo

ARC

Memory Management 100

UIImage lt0x12345678gt

rdquoHello WhyMCA rdquo

NSData lt0a1b2c3d4egt

UIVIew Backing Store

7

Memory Management 100

UIImage lt0x12345678gt

UIVIew Backing Store

8

malloc free

UIImage lt0x12345678gt

UIVIew Backing Store

9

Manual Reference Counting

UIImage lt0x12345678gt

UIVIew Backing Store

1

3

10

Manual Reference Counting

UIImage lt0x12345678gt

UIVIew Backing Store

1

2

11

Manual Reference Counting

UIVIew Backing Store

0

2

12

Garbage Collection 100

13

Generation 1 Generation 2 Generation 3

Garbage Collection 200

14

Garbage Collection 300

15

Garbage Collection 300

16

Garbage Collection 300

17

Garbage Collection 300

18

Heap Compaction

Garbage Collection 400

High Performance Concurrent Garbage Collector

19

Garbage Collection 400

X

20

read barrier

C GCvs

21

Puntatori che giocano a Nascondino

22

Apple lrsquoha fatto comunque

23

Limiti del GC Objective-C

24

Limiti del GC Objective-C

NSData data = [obj someData]const char bytes = [data bytes]

NSUInteger length = [data length]for (NSUInteger i = 0 i lt length ++i) printf(ldquoxrdquo bytes[i])

25

Limiti del GC Objective-C

26

Limiti del GC Objective-C

27

iPhone GCvs

28

iPhone Androidvs

29

30

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)

31

Static Analyzer

32

Analysis + Auto-Fix + Goodies

33

Requisiti di Sistema

bull iOS 5

bull OS X 107

bull iOS 4 - no runtime

bull OS X 106 (64-bit) - no runtime

34

Requisiti di Runtime

bull Clang (LLVM compiler) 30 or later

bull Obj-C Runtime objc4 4939 or later

bull For iOS4 or OS X 106 libarclite_iphoneosa or libarclite_macosxa is linked to make ARC work

35

Conversione ad ARC

36

Conversione ad ARC

37

Conversione ad ARC

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

autoreleasepool code here NSString s = [(id)CFStringCreateWithX(hellip) autorelease] NSString s = CFBridgingRelease(CFStringCreateWithX(hellip))

38

Conversione Automatica

39

From the command line via the -ccc-arcmt-check and -ccc-arcmt-modify arguments

Conversione Automatica

40

Nessuno egrave perfetto

41

Strani Autorelease Pools

Toll-Free Bridging

Structs

Giochetti con i Puntatori

Singleton

Eccezioni

case

Blocks

Conversione Parziale

42

43

ARC egrave costituito da due componenti principali

bull ARC front end compiler

bull ARC optimizer

Come Funziona ARC

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 5: Automatic Reference Counting

OS X amp iOS5

6

Session Timeline

bull Da dove nasce

bull Che cosrsquoegrave

bull Come funziona

bull Quando utilizzarlo

ARC

Memory Management 100

UIImage lt0x12345678gt

rdquoHello WhyMCA rdquo

NSData lt0a1b2c3d4egt

UIVIew Backing Store

7

Memory Management 100

UIImage lt0x12345678gt

UIVIew Backing Store

8

malloc free

UIImage lt0x12345678gt

UIVIew Backing Store

9

Manual Reference Counting

UIImage lt0x12345678gt

UIVIew Backing Store

1

3

10

Manual Reference Counting

UIImage lt0x12345678gt

UIVIew Backing Store

1

2

11

Manual Reference Counting

UIVIew Backing Store

0

2

12

Garbage Collection 100

13

Generation 1 Generation 2 Generation 3

Garbage Collection 200

14

Garbage Collection 300

15

Garbage Collection 300

16

Garbage Collection 300

17

Garbage Collection 300

18

Heap Compaction

Garbage Collection 400

High Performance Concurrent Garbage Collector

19

Garbage Collection 400

X

20

read barrier

C GCvs

21

Puntatori che giocano a Nascondino

22

Apple lrsquoha fatto comunque

23

Limiti del GC Objective-C

24

Limiti del GC Objective-C

NSData data = [obj someData]const char bytes = [data bytes]

NSUInteger length = [data length]for (NSUInteger i = 0 i lt length ++i) printf(ldquoxrdquo bytes[i])

25

Limiti del GC Objective-C

26

Limiti del GC Objective-C

27

iPhone GCvs

28

iPhone Androidvs

29

30

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)

31

Static Analyzer

32

Analysis + Auto-Fix + Goodies

33

Requisiti di Sistema

bull iOS 5

bull OS X 107

bull iOS 4 - no runtime

bull OS X 106 (64-bit) - no runtime

34

Requisiti di Runtime

bull Clang (LLVM compiler) 30 or later

bull Obj-C Runtime objc4 4939 or later

bull For iOS4 or OS X 106 libarclite_iphoneosa or libarclite_macosxa is linked to make ARC work

35

Conversione ad ARC

36

Conversione ad ARC

37

Conversione ad ARC

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

autoreleasepool code here NSString s = [(id)CFStringCreateWithX(hellip) autorelease] NSString s = CFBridgingRelease(CFStringCreateWithX(hellip))

38

Conversione Automatica

39

From the command line via the -ccc-arcmt-check and -ccc-arcmt-modify arguments

Conversione Automatica

40

Nessuno egrave perfetto

41

Strani Autorelease Pools

Toll-Free Bridging

Structs

Giochetti con i Puntatori

Singleton

Eccezioni

case

Blocks

Conversione Parziale

42

43

ARC egrave costituito da due componenti principali

bull ARC front end compiler

bull ARC optimizer

Come Funziona ARC

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 6: Automatic Reference Counting

6

Session Timeline

bull Da dove nasce

bull Che cosrsquoegrave

bull Come funziona

bull Quando utilizzarlo

ARC

Memory Management 100

UIImage lt0x12345678gt

rdquoHello WhyMCA rdquo

NSData lt0a1b2c3d4egt

UIVIew Backing Store

7

Memory Management 100

UIImage lt0x12345678gt

UIVIew Backing Store

8

malloc free

UIImage lt0x12345678gt

UIVIew Backing Store

9

Manual Reference Counting

UIImage lt0x12345678gt

UIVIew Backing Store

1

3

10

Manual Reference Counting

UIImage lt0x12345678gt

UIVIew Backing Store

1

2

11

Manual Reference Counting

UIVIew Backing Store

0

2

12

Garbage Collection 100

13

Generation 1 Generation 2 Generation 3

Garbage Collection 200

14

Garbage Collection 300

15

Garbage Collection 300

16

Garbage Collection 300

17

Garbage Collection 300

18

Heap Compaction

Garbage Collection 400

High Performance Concurrent Garbage Collector

19

Garbage Collection 400

X

20

read barrier

C GCvs

21

Puntatori che giocano a Nascondino

22

Apple lrsquoha fatto comunque

23

Limiti del GC Objective-C

24

Limiti del GC Objective-C

NSData data = [obj someData]const char bytes = [data bytes]

NSUInteger length = [data length]for (NSUInteger i = 0 i lt length ++i) printf(ldquoxrdquo bytes[i])

25

Limiti del GC Objective-C

26

Limiti del GC Objective-C

27

iPhone GCvs

28

iPhone Androidvs

29

30

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)

31

Static Analyzer

32

Analysis + Auto-Fix + Goodies

33

Requisiti di Sistema

bull iOS 5

bull OS X 107

bull iOS 4 - no runtime

bull OS X 106 (64-bit) - no runtime

34

Requisiti di Runtime

bull Clang (LLVM compiler) 30 or later

bull Obj-C Runtime objc4 4939 or later

bull For iOS4 or OS X 106 libarclite_iphoneosa or libarclite_macosxa is linked to make ARC work

35

Conversione ad ARC

36

Conversione ad ARC

37

Conversione ad ARC

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

autoreleasepool code here NSString s = [(id)CFStringCreateWithX(hellip) autorelease] NSString s = CFBridgingRelease(CFStringCreateWithX(hellip))

38

Conversione Automatica

39

From the command line via the -ccc-arcmt-check and -ccc-arcmt-modify arguments

Conversione Automatica

40

Nessuno egrave perfetto

41

Strani Autorelease Pools

Toll-Free Bridging

Structs

Giochetti con i Puntatori

Singleton

Eccezioni

case

Blocks

Conversione Parziale

42

43

ARC egrave costituito da due componenti principali

bull ARC front end compiler

bull ARC optimizer

Come Funziona ARC

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 7: Automatic Reference Counting

Memory Management 100

UIImage lt0x12345678gt

rdquoHello WhyMCA rdquo

NSData lt0a1b2c3d4egt

UIVIew Backing Store

7

Memory Management 100

UIImage lt0x12345678gt

UIVIew Backing Store

8

malloc free

UIImage lt0x12345678gt

UIVIew Backing Store

9

Manual Reference Counting

UIImage lt0x12345678gt

UIVIew Backing Store

1

3

10

Manual Reference Counting

UIImage lt0x12345678gt

UIVIew Backing Store

1

2

11

Manual Reference Counting

UIVIew Backing Store

0

2

12

Garbage Collection 100

13

Generation 1 Generation 2 Generation 3

Garbage Collection 200

14

Garbage Collection 300

15

Garbage Collection 300

16

Garbage Collection 300

17

Garbage Collection 300

18

Heap Compaction

Garbage Collection 400

High Performance Concurrent Garbage Collector

19

Garbage Collection 400

X

20

read barrier

C GCvs

21

Puntatori che giocano a Nascondino

22

Apple lrsquoha fatto comunque

23

Limiti del GC Objective-C

24

Limiti del GC Objective-C

NSData data = [obj someData]const char bytes = [data bytes]

NSUInteger length = [data length]for (NSUInteger i = 0 i lt length ++i) printf(ldquoxrdquo bytes[i])

25

Limiti del GC Objective-C

26

Limiti del GC Objective-C

27

iPhone GCvs

28

iPhone Androidvs

29

30

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)

31

Static Analyzer

32

Analysis + Auto-Fix + Goodies

33

Requisiti di Sistema

bull iOS 5

bull OS X 107

bull iOS 4 - no runtime

bull OS X 106 (64-bit) - no runtime

34

Requisiti di Runtime

bull Clang (LLVM compiler) 30 or later

bull Obj-C Runtime objc4 4939 or later

bull For iOS4 or OS X 106 libarclite_iphoneosa or libarclite_macosxa is linked to make ARC work

35

Conversione ad ARC

36

Conversione ad ARC

37

Conversione ad ARC

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

autoreleasepool code here NSString s = [(id)CFStringCreateWithX(hellip) autorelease] NSString s = CFBridgingRelease(CFStringCreateWithX(hellip))

38

Conversione Automatica

39

From the command line via the -ccc-arcmt-check and -ccc-arcmt-modify arguments

Conversione Automatica

40

Nessuno egrave perfetto

41

Strani Autorelease Pools

Toll-Free Bridging

Structs

Giochetti con i Puntatori

Singleton

Eccezioni

case

Blocks

Conversione Parziale

42

43

ARC egrave costituito da due componenti principali

bull ARC front end compiler

bull ARC optimizer

Come Funziona ARC

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 8: Automatic Reference Counting

Memory Management 100

UIImage lt0x12345678gt

UIVIew Backing Store

8

malloc free

UIImage lt0x12345678gt

UIVIew Backing Store

9

Manual Reference Counting

UIImage lt0x12345678gt

UIVIew Backing Store

1

3

10

Manual Reference Counting

UIImage lt0x12345678gt

UIVIew Backing Store

1

2

11

Manual Reference Counting

UIVIew Backing Store

0

2

12

Garbage Collection 100

13

Generation 1 Generation 2 Generation 3

Garbage Collection 200

14

Garbage Collection 300

15

Garbage Collection 300

16

Garbage Collection 300

17

Garbage Collection 300

18

Heap Compaction

Garbage Collection 400

High Performance Concurrent Garbage Collector

19

Garbage Collection 400

X

20

read barrier

C GCvs

21

Puntatori che giocano a Nascondino

22

Apple lrsquoha fatto comunque

23

Limiti del GC Objective-C

24

Limiti del GC Objective-C

NSData data = [obj someData]const char bytes = [data bytes]

NSUInteger length = [data length]for (NSUInteger i = 0 i lt length ++i) printf(ldquoxrdquo bytes[i])

25

Limiti del GC Objective-C

26

Limiti del GC Objective-C

27

iPhone GCvs

28

iPhone Androidvs

29

30

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)

31

Static Analyzer

32

Analysis + Auto-Fix + Goodies

33

Requisiti di Sistema

bull iOS 5

bull OS X 107

bull iOS 4 - no runtime

bull OS X 106 (64-bit) - no runtime

34

Requisiti di Runtime

bull Clang (LLVM compiler) 30 or later

bull Obj-C Runtime objc4 4939 or later

bull For iOS4 or OS X 106 libarclite_iphoneosa or libarclite_macosxa is linked to make ARC work

35

Conversione ad ARC

36

Conversione ad ARC

37

Conversione ad ARC

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

autoreleasepool code here NSString s = [(id)CFStringCreateWithX(hellip) autorelease] NSString s = CFBridgingRelease(CFStringCreateWithX(hellip))

38

Conversione Automatica

39

From the command line via the -ccc-arcmt-check and -ccc-arcmt-modify arguments

Conversione Automatica

40

Nessuno egrave perfetto

41

Strani Autorelease Pools

Toll-Free Bridging

Structs

Giochetti con i Puntatori

Singleton

Eccezioni

case

Blocks

Conversione Parziale

42

43

ARC egrave costituito da due componenti principali

bull ARC front end compiler

bull ARC optimizer

Come Funziona ARC

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 9: Automatic Reference Counting

malloc free

UIImage lt0x12345678gt

UIVIew Backing Store

9

Manual Reference Counting

UIImage lt0x12345678gt

UIVIew Backing Store

1

3

10

Manual Reference Counting

UIImage lt0x12345678gt

UIVIew Backing Store

1

2

11

Manual Reference Counting

UIVIew Backing Store

0

2

12

Garbage Collection 100

13

Generation 1 Generation 2 Generation 3

Garbage Collection 200

14

Garbage Collection 300

15

Garbage Collection 300

16

Garbage Collection 300

17

Garbage Collection 300

18

Heap Compaction

Garbage Collection 400

High Performance Concurrent Garbage Collector

19

Garbage Collection 400

X

20

read barrier

C GCvs

21

Puntatori che giocano a Nascondino

22

Apple lrsquoha fatto comunque

23

Limiti del GC Objective-C

24

Limiti del GC Objective-C

NSData data = [obj someData]const char bytes = [data bytes]

NSUInteger length = [data length]for (NSUInteger i = 0 i lt length ++i) printf(ldquoxrdquo bytes[i])

25

Limiti del GC Objective-C

26

Limiti del GC Objective-C

27

iPhone GCvs

28

iPhone Androidvs

29

30

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)

31

Static Analyzer

32

Analysis + Auto-Fix + Goodies

33

Requisiti di Sistema

bull iOS 5

bull OS X 107

bull iOS 4 - no runtime

bull OS X 106 (64-bit) - no runtime

34

Requisiti di Runtime

bull Clang (LLVM compiler) 30 or later

bull Obj-C Runtime objc4 4939 or later

bull For iOS4 or OS X 106 libarclite_iphoneosa or libarclite_macosxa is linked to make ARC work

35

Conversione ad ARC

36

Conversione ad ARC

37

Conversione ad ARC

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

autoreleasepool code here NSString s = [(id)CFStringCreateWithX(hellip) autorelease] NSString s = CFBridgingRelease(CFStringCreateWithX(hellip))

38

Conversione Automatica

39

From the command line via the -ccc-arcmt-check and -ccc-arcmt-modify arguments

Conversione Automatica

40

Nessuno egrave perfetto

41

Strani Autorelease Pools

Toll-Free Bridging

Structs

Giochetti con i Puntatori

Singleton

Eccezioni

case

Blocks

Conversione Parziale

42

43

ARC egrave costituito da due componenti principali

bull ARC front end compiler

bull ARC optimizer

Come Funziona ARC

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 10: Automatic Reference Counting

Manual Reference Counting

UIImage lt0x12345678gt

UIVIew Backing Store

1

3

10

Manual Reference Counting

UIImage lt0x12345678gt

UIVIew Backing Store

1

2

11

Manual Reference Counting

UIVIew Backing Store

0

2

12

Garbage Collection 100

13

Generation 1 Generation 2 Generation 3

Garbage Collection 200

14

Garbage Collection 300

15

Garbage Collection 300

16

Garbage Collection 300

17

Garbage Collection 300

18

Heap Compaction

Garbage Collection 400

High Performance Concurrent Garbage Collector

19

Garbage Collection 400

X

20

read barrier

C GCvs

21

Puntatori che giocano a Nascondino

22

Apple lrsquoha fatto comunque

23

Limiti del GC Objective-C

24

Limiti del GC Objective-C

NSData data = [obj someData]const char bytes = [data bytes]

NSUInteger length = [data length]for (NSUInteger i = 0 i lt length ++i) printf(ldquoxrdquo bytes[i])

25

Limiti del GC Objective-C

26

Limiti del GC Objective-C

27

iPhone GCvs

28

iPhone Androidvs

29

30

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)

31

Static Analyzer

32

Analysis + Auto-Fix + Goodies

33

Requisiti di Sistema

bull iOS 5

bull OS X 107

bull iOS 4 - no runtime

bull OS X 106 (64-bit) - no runtime

34

Requisiti di Runtime

bull Clang (LLVM compiler) 30 or later

bull Obj-C Runtime objc4 4939 or later

bull For iOS4 or OS X 106 libarclite_iphoneosa or libarclite_macosxa is linked to make ARC work

35

Conversione ad ARC

36

Conversione ad ARC

37

Conversione ad ARC

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

autoreleasepool code here NSString s = [(id)CFStringCreateWithX(hellip) autorelease] NSString s = CFBridgingRelease(CFStringCreateWithX(hellip))

38

Conversione Automatica

39

From the command line via the -ccc-arcmt-check and -ccc-arcmt-modify arguments

Conversione Automatica

40

Nessuno egrave perfetto

41

Strani Autorelease Pools

Toll-Free Bridging

Structs

Giochetti con i Puntatori

Singleton

Eccezioni

case

Blocks

Conversione Parziale

42

43

ARC egrave costituito da due componenti principali

bull ARC front end compiler

bull ARC optimizer

Come Funziona ARC

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 11: Automatic Reference Counting

Manual Reference Counting

UIImage lt0x12345678gt

UIVIew Backing Store

1

2

11

Manual Reference Counting

UIVIew Backing Store

0

2

12

Garbage Collection 100

13

Generation 1 Generation 2 Generation 3

Garbage Collection 200

14

Garbage Collection 300

15

Garbage Collection 300

16

Garbage Collection 300

17

Garbage Collection 300

18

Heap Compaction

Garbage Collection 400

High Performance Concurrent Garbage Collector

19

Garbage Collection 400

X

20

read barrier

C GCvs

21

Puntatori che giocano a Nascondino

22

Apple lrsquoha fatto comunque

23

Limiti del GC Objective-C

24

Limiti del GC Objective-C

NSData data = [obj someData]const char bytes = [data bytes]

NSUInteger length = [data length]for (NSUInteger i = 0 i lt length ++i) printf(ldquoxrdquo bytes[i])

25

Limiti del GC Objective-C

26

Limiti del GC Objective-C

27

iPhone GCvs

28

iPhone Androidvs

29

30

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)

31

Static Analyzer

32

Analysis + Auto-Fix + Goodies

33

Requisiti di Sistema

bull iOS 5

bull OS X 107

bull iOS 4 - no runtime

bull OS X 106 (64-bit) - no runtime

34

Requisiti di Runtime

bull Clang (LLVM compiler) 30 or later

bull Obj-C Runtime objc4 4939 or later

bull For iOS4 or OS X 106 libarclite_iphoneosa or libarclite_macosxa is linked to make ARC work

35

Conversione ad ARC

36

Conversione ad ARC

37

Conversione ad ARC

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

autoreleasepool code here NSString s = [(id)CFStringCreateWithX(hellip) autorelease] NSString s = CFBridgingRelease(CFStringCreateWithX(hellip))

38

Conversione Automatica

39

From the command line via the -ccc-arcmt-check and -ccc-arcmt-modify arguments

Conversione Automatica

40

Nessuno egrave perfetto

41

Strani Autorelease Pools

Toll-Free Bridging

Structs

Giochetti con i Puntatori

Singleton

Eccezioni

case

Blocks

Conversione Parziale

42

43

ARC egrave costituito da due componenti principali

bull ARC front end compiler

bull ARC optimizer

Come Funziona ARC

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 12: Automatic Reference Counting

Manual Reference Counting

UIVIew Backing Store

0

2

12

Garbage Collection 100

13

Generation 1 Generation 2 Generation 3

Garbage Collection 200

14

Garbage Collection 300

15

Garbage Collection 300

16

Garbage Collection 300

17

Garbage Collection 300

18

Heap Compaction

Garbage Collection 400

High Performance Concurrent Garbage Collector

19

Garbage Collection 400

X

20

read barrier

C GCvs

21

Puntatori che giocano a Nascondino

22

Apple lrsquoha fatto comunque

23

Limiti del GC Objective-C

24

Limiti del GC Objective-C

NSData data = [obj someData]const char bytes = [data bytes]

NSUInteger length = [data length]for (NSUInteger i = 0 i lt length ++i) printf(ldquoxrdquo bytes[i])

25

Limiti del GC Objective-C

26

Limiti del GC Objective-C

27

iPhone GCvs

28

iPhone Androidvs

29

30

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)

31

Static Analyzer

32

Analysis + Auto-Fix + Goodies

33

Requisiti di Sistema

bull iOS 5

bull OS X 107

bull iOS 4 - no runtime

bull OS X 106 (64-bit) - no runtime

34

Requisiti di Runtime

bull Clang (LLVM compiler) 30 or later

bull Obj-C Runtime objc4 4939 or later

bull For iOS4 or OS X 106 libarclite_iphoneosa or libarclite_macosxa is linked to make ARC work

35

Conversione ad ARC

36

Conversione ad ARC

37

Conversione ad ARC

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

autoreleasepool code here NSString s = [(id)CFStringCreateWithX(hellip) autorelease] NSString s = CFBridgingRelease(CFStringCreateWithX(hellip))

38

Conversione Automatica

39

From the command line via the -ccc-arcmt-check and -ccc-arcmt-modify arguments

Conversione Automatica

40

Nessuno egrave perfetto

41

Strani Autorelease Pools

Toll-Free Bridging

Structs

Giochetti con i Puntatori

Singleton

Eccezioni

case

Blocks

Conversione Parziale

42

43

ARC egrave costituito da due componenti principali

bull ARC front end compiler

bull ARC optimizer

Come Funziona ARC

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 13: Automatic Reference Counting

Garbage Collection 100

13

Generation 1 Generation 2 Generation 3

Garbage Collection 200

14

Garbage Collection 300

15

Garbage Collection 300

16

Garbage Collection 300

17

Garbage Collection 300

18

Heap Compaction

Garbage Collection 400

High Performance Concurrent Garbage Collector

19

Garbage Collection 400

X

20

read barrier

C GCvs

21

Puntatori che giocano a Nascondino

22

Apple lrsquoha fatto comunque

23

Limiti del GC Objective-C

24

Limiti del GC Objective-C

NSData data = [obj someData]const char bytes = [data bytes]

NSUInteger length = [data length]for (NSUInteger i = 0 i lt length ++i) printf(ldquoxrdquo bytes[i])

25

Limiti del GC Objective-C

26

Limiti del GC Objective-C

27

iPhone GCvs

28

iPhone Androidvs

29

30

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)

31

Static Analyzer

32

Analysis + Auto-Fix + Goodies

33

Requisiti di Sistema

bull iOS 5

bull OS X 107

bull iOS 4 - no runtime

bull OS X 106 (64-bit) - no runtime

34

Requisiti di Runtime

bull Clang (LLVM compiler) 30 or later

bull Obj-C Runtime objc4 4939 or later

bull For iOS4 or OS X 106 libarclite_iphoneosa or libarclite_macosxa is linked to make ARC work

35

Conversione ad ARC

36

Conversione ad ARC

37

Conversione ad ARC

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

autoreleasepool code here NSString s = [(id)CFStringCreateWithX(hellip) autorelease] NSString s = CFBridgingRelease(CFStringCreateWithX(hellip))

38

Conversione Automatica

39

From the command line via the -ccc-arcmt-check and -ccc-arcmt-modify arguments

Conversione Automatica

40

Nessuno egrave perfetto

41

Strani Autorelease Pools

Toll-Free Bridging

Structs

Giochetti con i Puntatori

Singleton

Eccezioni

case

Blocks

Conversione Parziale

42

43

ARC egrave costituito da due componenti principali

bull ARC front end compiler

bull ARC optimizer

Come Funziona ARC

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 14: Automatic Reference Counting

Generation 1 Generation 2 Generation 3

Garbage Collection 200

14

Garbage Collection 300

15

Garbage Collection 300

16

Garbage Collection 300

17

Garbage Collection 300

18

Heap Compaction

Garbage Collection 400

High Performance Concurrent Garbage Collector

19

Garbage Collection 400

X

20

read barrier

C GCvs

21

Puntatori che giocano a Nascondino

22

Apple lrsquoha fatto comunque

23

Limiti del GC Objective-C

24

Limiti del GC Objective-C

NSData data = [obj someData]const char bytes = [data bytes]

NSUInteger length = [data length]for (NSUInteger i = 0 i lt length ++i) printf(ldquoxrdquo bytes[i])

25

Limiti del GC Objective-C

26

Limiti del GC Objective-C

27

iPhone GCvs

28

iPhone Androidvs

29

30

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)

31

Static Analyzer

32

Analysis + Auto-Fix + Goodies

33

Requisiti di Sistema

bull iOS 5

bull OS X 107

bull iOS 4 - no runtime

bull OS X 106 (64-bit) - no runtime

34

Requisiti di Runtime

bull Clang (LLVM compiler) 30 or later

bull Obj-C Runtime objc4 4939 or later

bull For iOS4 or OS X 106 libarclite_iphoneosa or libarclite_macosxa is linked to make ARC work

35

Conversione ad ARC

36

Conversione ad ARC

37

Conversione ad ARC

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

autoreleasepool code here NSString s = [(id)CFStringCreateWithX(hellip) autorelease] NSString s = CFBridgingRelease(CFStringCreateWithX(hellip))

38

Conversione Automatica

39

From the command line via the -ccc-arcmt-check and -ccc-arcmt-modify arguments

Conversione Automatica

40

Nessuno egrave perfetto

41

Strani Autorelease Pools

Toll-Free Bridging

Structs

Giochetti con i Puntatori

Singleton

Eccezioni

case

Blocks

Conversione Parziale

42

43

ARC egrave costituito da due componenti principali

bull ARC front end compiler

bull ARC optimizer

Come Funziona ARC

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 15: Automatic Reference Counting

Garbage Collection 300

15

Garbage Collection 300

16

Garbage Collection 300

17

Garbage Collection 300

18

Heap Compaction

Garbage Collection 400

High Performance Concurrent Garbage Collector

19

Garbage Collection 400

X

20

read barrier

C GCvs

21

Puntatori che giocano a Nascondino

22

Apple lrsquoha fatto comunque

23

Limiti del GC Objective-C

24

Limiti del GC Objective-C

NSData data = [obj someData]const char bytes = [data bytes]

NSUInteger length = [data length]for (NSUInteger i = 0 i lt length ++i) printf(ldquoxrdquo bytes[i])

25

Limiti del GC Objective-C

26

Limiti del GC Objective-C

27

iPhone GCvs

28

iPhone Androidvs

29

30

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)

31

Static Analyzer

32

Analysis + Auto-Fix + Goodies

33

Requisiti di Sistema

bull iOS 5

bull OS X 107

bull iOS 4 - no runtime

bull OS X 106 (64-bit) - no runtime

34

Requisiti di Runtime

bull Clang (LLVM compiler) 30 or later

bull Obj-C Runtime objc4 4939 or later

bull For iOS4 or OS X 106 libarclite_iphoneosa or libarclite_macosxa is linked to make ARC work

35

Conversione ad ARC

36

Conversione ad ARC

37

Conversione ad ARC

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

autoreleasepool code here NSString s = [(id)CFStringCreateWithX(hellip) autorelease] NSString s = CFBridgingRelease(CFStringCreateWithX(hellip))

38

Conversione Automatica

39

From the command line via the -ccc-arcmt-check and -ccc-arcmt-modify arguments

Conversione Automatica

40

Nessuno egrave perfetto

41

Strani Autorelease Pools

Toll-Free Bridging

Structs

Giochetti con i Puntatori

Singleton

Eccezioni

case

Blocks

Conversione Parziale

42

43

ARC egrave costituito da due componenti principali

bull ARC front end compiler

bull ARC optimizer

Come Funziona ARC

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 16: Automatic Reference Counting

Garbage Collection 300

16

Garbage Collection 300

17

Garbage Collection 300

18

Heap Compaction

Garbage Collection 400

High Performance Concurrent Garbage Collector

19

Garbage Collection 400

X

20

read barrier

C GCvs

21

Puntatori che giocano a Nascondino

22

Apple lrsquoha fatto comunque

23

Limiti del GC Objective-C

24

Limiti del GC Objective-C

NSData data = [obj someData]const char bytes = [data bytes]

NSUInteger length = [data length]for (NSUInteger i = 0 i lt length ++i) printf(ldquoxrdquo bytes[i])

25

Limiti del GC Objective-C

26

Limiti del GC Objective-C

27

iPhone GCvs

28

iPhone Androidvs

29

30

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)

31

Static Analyzer

32

Analysis + Auto-Fix + Goodies

33

Requisiti di Sistema

bull iOS 5

bull OS X 107

bull iOS 4 - no runtime

bull OS X 106 (64-bit) - no runtime

34

Requisiti di Runtime

bull Clang (LLVM compiler) 30 or later

bull Obj-C Runtime objc4 4939 or later

bull For iOS4 or OS X 106 libarclite_iphoneosa or libarclite_macosxa is linked to make ARC work

35

Conversione ad ARC

36

Conversione ad ARC

37

Conversione ad ARC

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

autoreleasepool code here NSString s = [(id)CFStringCreateWithX(hellip) autorelease] NSString s = CFBridgingRelease(CFStringCreateWithX(hellip))

38

Conversione Automatica

39

From the command line via the -ccc-arcmt-check and -ccc-arcmt-modify arguments

Conversione Automatica

40

Nessuno egrave perfetto

41

Strani Autorelease Pools

Toll-Free Bridging

Structs

Giochetti con i Puntatori

Singleton

Eccezioni

case

Blocks

Conversione Parziale

42

43

ARC egrave costituito da due componenti principali

bull ARC front end compiler

bull ARC optimizer

Come Funziona ARC

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 17: Automatic Reference Counting

Garbage Collection 300

17

Garbage Collection 300

18

Heap Compaction

Garbage Collection 400

High Performance Concurrent Garbage Collector

19

Garbage Collection 400

X

20

read barrier

C GCvs

21

Puntatori che giocano a Nascondino

22

Apple lrsquoha fatto comunque

23

Limiti del GC Objective-C

24

Limiti del GC Objective-C

NSData data = [obj someData]const char bytes = [data bytes]

NSUInteger length = [data length]for (NSUInteger i = 0 i lt length ++i) printf(ldquoxrdquo bytes[i])

25

Limiti del GC Objective-C

26

Limiti del GC Objective-C

27

iPhone GCvs

28

iPhone Androidvs

29

30

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)

31

Static Analyzer

32

Analysis + Auto-Fix + Goodies

33

Requisiti di Sistema

bull iOS 5

bull OS X 107

bull iOS 4 - no runtime

bull OS X 106 (64-bit) - no runtime

34

Requisiti di Runtime

bull Clang (LLVM compiler) 30 or later

bull Obj-C Runtime objc4 4939 or later

bull For iOS4 or OS X 106 libarclite_iphoneosa or libarclite_macosxa is linked to make ARC work

35

Conversione ad ARC

36

Conversione ad ARC

37

Conversione ad ARC

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

autoreleasepool code here NSString s = [(id)CFStringCreateWithX(hellip) autorelease] NSString s = CFBridgingRelease(CFStringCreateWithX(hellip))

38

Conversione Automatica

39

From the command line via the -ccc-arcmt-check and -ccc-arcmt-modify arguments

Conversione Automatica

40

Nessuno egrave perfetto

41

Strani Autorelease Pools

Toll-Free Bridging

Structs

Giochetti con i Puntatori

Singleton

Eccezioni

case

Blocks

Conversione Parziale

42

43

ARC egrave costituito da due componenti principali

bull ARC front end compiler

bull ARC optimizer

Come Funziona ARC

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 18: Automatic Reference Counting

Garbage Collection 300

18

Heap Compaction

Garbage Collection 400

High Performance Concurrent Garbage Collector

19

Garbage Collection 400

X

20

read barrier

C GCvs

21

Puntatori che giocano a Nascondino

22

Apple lrsquoha fatto comunque

23

Limiti del GC Objective-C

24

Limiti del GC Objective-C

NSData data = [obj someData]const char bytes = [data bytes]

NSUInteger length = [data length]for (NSUInteger i = 0 i lt length ++i) printf(ldquoxrdquo bytes[i])

25

Limiti del GC Objective-C

26

Limiti del GC Objective-C

27

iPhone GCvs

28

iPhone Androidvs

29

30

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)

31

Static Analyzer

32

Analysis + Auto-Fix + Goodies

33

Requisiti di Sistema

bull iOS 5

bull OS X 107

bull iOS 4 - no runtime

bull OS X 106 (64-bit) - no runtime

34

Requisiti di Runtime

bull Clang (LLVM compiler) 30 or later

bull Obj-C Runtime objc4 4939 or later

bull For iOS4 or OS X 106 libarclite_iphoneosa or libarclite_macosxa is linked to make ARC work

35

Conversione ad ARC

36

Conversione ad ARC

37

Conversione ad ARC

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

autoreleasepool code here NSString s = [(id)CFStringCreateWithX(hellip) autorelease] NSString s = CFBridgingRelease(CFStringCreateWithX(hellip))

38

Conversione Automatica

39

From the command line via the -ccc-arcmt-check and -ccc-arcmt-modify arguments

Conversione Automatica

40

Nessuno egrave perfetto

41

Strani Autorelease Pools

Toll-Free Bridging

Structs

Giochetti con i Puntatori

Singleton

Eccezioni

case

Blocks

Conversione Parziale

42

43

ARC egrave costituito da due componenti principali

bull ARC front end compiler

bull ARC optimizer

Come Funziona ARC

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 19: Automatic Reference Counting

Garbage Collection 400

High Performance Concurrent Garbage Collector

19

Garbage Collection 400

X

20

read barrier

C GCvs

21

Puntatori che giocano a Nascondino

22

Apple lrsquoha fatto comunque

23

Limiti del GC Objective-C

24

Limiti del GC Objective-C

NSData data = [obj someData]const char bytes = [data bytes]

NSUInteger length = [data length]for (NSUInteger i = 0 i lt length ++i) printf(ldquoxrdquo bytes[i])

25

Limiti del GC Objective-C

26

Limiti del GC Objective-C

27

iPhone GCvs

28

iPhone Androidvs

29

30

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)

31

Static Analyzer

32

Analysis + Auto-Fix + Goodies

33

Requisiti di Sistema

bull iOS 5

bull OS X 107

bull iOS 4 - no runtime

bull OS X 106 (64-bit) - no runtime

34

Requisiti di Runtime

bull Clang (LLVM compiler) 30 or later

bull Obj-C Runtime objc4 4939 or later

bull For iOS4 or OS X 106 libarclite_iphoneosa or libarclite_macosxa is linked to make ARC work

35

Conversione ad ARC

36

Conversione ad ARC

37

Conversione ad ARC

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

autoreleasepool code here NSString s = [(id)CFStringCreateWithX(hellip) autorelease] NSString s = CFBridgingRelease(CFStringCreateWithX(hellip))

38

Conversione Automatica

39

From the command line via the -ccc-arcmt-check and -ccc-arcmt-modify arguments

Conversione Automatica

40

Nessuno egrave perfetto

41

Strani Autorelease Pools

Toll-Free Bridging

Structs

Giochetti con i Puntatori

Singleton

Eccezioni

case

Blocks

Conversione Parziale

42

43

ARC egrave costituito da due componenti principali

bull ARC front end compiler

bull ARC optimizer

Come Funziona ARC

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 20: Automatic Reference Counting

Garbage Collection 400

X

20

read barrier

C GCvs

21

Puntatori che giocano a Nascondino

22

Apple lrsquoha fatto comunque

23

Limiti del GC Objective-C

24

Limiti del GC Objective-C

NSData data = [obj someData]const char bytes = [data bytes]

NSUInteger length = [data length]for (NSUInteger i = 0 i lt length ++i) printf(ldquoxrdquo bytes[i])

25

Limiti del GC Objective-C

26

Limiti del GC Objective-C

27

iPhone GCvs

28

iPhone Androidvs

29

30

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)

31

Static Analyzer

32

Analysis + Auto-Fix + Goodies

33

Requisiti di Sistema

bull iOS 5

bull OS X 107

bull iOS 4 - no runtime

bull OS X 106 (64-bit) - no runtime

34

Requisiti di Runtime

bull Clang (LLVM compiler) 30 or later

bull Obj-C Runtime objc4 4939 or later

bull For iOS4 or OS X 106 libarclite_iphoneosa or libarclite_macosxa is linked to make ARC work

35

Conversione ad ARC

36

Conversione ad ARC

37

Conversione ad ARC

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

autoreleasepool code here NSString s = [(id)CFStringCreateWithX(hellip) autorelease] NSString s = CFBridgingRelease(CFStringCreateWithX(hellip))

38

Conversione Automatica

39

From the command line via the -ccc-arcmt-check and -ccc-arcmt-modify arguments

Conversione Automatica

40

Nessuno egrave perfetto

41

Strani Autorelease Pools

Toll-Free Bridging

Structs

Giochetti con i Puntatori

Singleton

Eccezioni

case

Blocks

Conversione Parziale

42

43

ARC egrave costituito da due componenti principali

bull ARC front end compiler

bull ARC optimizer

Come Funziona ARC

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 21: Automatic Reference Counting

C GCvs

21

Puntatori che giocano a Nascondino

22

Apple lrsquoha fatto comunque

23

Limiti del GC Objective-C

24

Limiti del GC Objective-C

NSData data = [obj someData]const char bytes = [data bytes]

NSUInteger length = [data length]for (NSUInteger i = 0 i lt length ++i) printf(ldquoxrdquo bytes[i])

25

Limiti del GC Objective-C

26

Limiti del GC Objective-C

27

iPhone GCvs

28

iPhone Androidvs

29

30

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)

31

Static Analyzer

32

Analysis + Auto-Fix + Goodies

33

Requisiti di Sistema

bull iOS 5

bull OS X 107

bull iOS 4 - no runtime

bull OS X 106 (64-bit) - no runtime

34

Requisiti di Runtime

bull Clang (LLVM compiler) 30 or later

bull Obj-C Runtime objc4 4939 or later

bull For iOS4 or OS X 106 libarclite_iphoneosa or libarclite_macosxa is linked to make ARC work

35

Conversione ad ARC

36

Conversione ad ARC

37

Conversione ad ARC

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

autoreleasepool code here NSString s = [(id)CFStringCreateWithX(hellip) autorelease] NSString s = CFBridgingRelease(CFStringCreateWithX(hellip))

38

Conversione Automatica

39

From the command line via the -ccc-arcmt-check and -ccc-arcmt-modify arguments

Conversione Automatica

40

Nessuno egrave perfetto

41

Strani Autorelease Pools

Toll-Free Bridging

Structs

Giochetti con i Puntatori

Singleton

Eccezioni

case

Blocks

Conversione Parziale

42

43

ARC egrave costituito da due componenti principali

bull ARC front end compiler

bull ARC optimizer

Come Funziona ARC

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 22: Automatic Reference Counting

Puntatori che giocano a Nascondino

22

Apple lrsquoha fatto comunque

23

Limiti del GC Objective-C

24

Limiti del GC Objective-C

NSData data = [obj someData]const char bytes = [data bytes]

NSUInteger length = [data length]for (NSUInteger i = 0 i lt length ++i) printf(ldquoxrdquo bytes[i])

25

Limiti del GC Objective-C

26

Limiti del GC Objective-C

27

iPhone GCvs

28

iPhone Androidvs

29

30

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)

31

Static Analyzer

32

Analysis + Auto-Fix + Goodies

33

Requisiti di Sistema

bull iOS 5

bull OS X 107

bull iOS 4 - no runtime

bull OS X 106 (64-bit) - no runtime

34

Requisiti di Runtime

bull Clang (LLVM compiler) 30 or later

bull Obj-C Runtime objc4 4939 or later

bull For iOS4 or OS X 106 libarclite_iphoneosa or libarclite_macosxa is linked to make ARC work

35

Conversione ad ARC

36

Conversione ad ARC

37

Conversione ad ARC

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

autoreleasepool code here NSString s = [(id)CFStringCreateWithX(hellip) autorelease] NSString s = CFBridgingRelease(CFStringCreateWithX(hellip))

38

Conversione Automatica

39

From the command line via the -ccc-arcmt-check and -ccc-arcmt-modify arguments

Conversione Automatica

40

Nessuno egrave perfetto

41

Strani Autorelease Pools

Toll-Free Bridging

Structs

Giochetti con i Puntatori

Singleton

Eccezioni

case

Blocks

Conversione Parziale

42

43

ARC egrave costituito da due componenti principali

bull ARC front end compiler

bull ARC optimizer

Come Funziona ARC

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 23: Automatic Reference Counting

Apple lrsquoha fatto comunque

23

Limiti del GC Objective-C

24

Limiti del GC Objective-C

NSData data = [obj someData]const char bytes = [data bytes]

NSUInteger length = [data length]for (NSUInteger i = 0 i lt length ++i) printf(ldquoxrdquo bytes[i])

25

Limiti del GC Objective-C

26

Limiti del GC Objective-C

27

iPhone GCvs

28

iPhone Androidvs

29

30

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)

31

Static Analyzer

32

Analysis + Auto-Fix + Goodies

33

Requisiti di Sistema

bull iOS 5

bull OS X 107

bull iOS 4 - no runtime

bull OS X 106 (64-bit) - no runtime

34

Requisiti di Runtime

bull Clang (LLVM compiler) 30 or later

bull Obj-C Runtime objc4 4939 or later

bull For iOS4 or OS X 106 libarclite_iphoneosa or libarclite_macosxa is linked to make ARC work

35

Conversione ad ARC

36

Conversione ad ARC

37

Conversione ad ARC

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

autoreleasepool code here NSString s = [(id)CFStringCreateWithX(hellip) autorelease] NSString s = CFBridgingRelease(CFStringCreateWithX(hellip))

38

Conversione Automatica

39

From the command line via the -ccc-arcmt-check and -ccc-arcmt-modify arguments

Conversione Automatica

40

Nessuno egrave perfetto

41

Strani Autorelease Pools

Toll-Free Bridging

Structs

Giochetti con i Puntatori

Singleton

Eccezioni

case

Blocks

Conversione Parziale

42

43

ARC egrave costituito da due componenti principali

bull ARC front end compiler

bull ARC optimizer

Come Funziona ARC

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 24: Automatic Reference Counting

Limiti del GC Objective-C

24

Limiti del GC Objective-C

NSData data = [obj someData]const char bytes = [data bytes]

NSUInteger length = [data length]for (NSUInteger i = 0 i lt length ++i) printf(ldquoxrdquo bytes[i])

25

Limiti del GC Objective-C

26

Limiti del GC Objective-C

27

iPhone GCvs

28

iPhone Androidvs

29

30

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)

31

Static Analyzer

32

Analysis + Auto-Fix + Goodies

33

Requisiti di Sistema

bull iOS 5

bull OS X 107

bull iOS 4 - no runtime

bull OS X 106 (64-bit) - no runtime

34

Requisiti di Runtime

bull Clang (LLVM compiler) 30 or later

bull Obj-C Runtime objc4 4939 or later

bull For iOS4 or OS X 106 libarclite_iphoneosa or libarclite_macosxa is linked to make ARC work

35

Conversione ad ARC

36

Conversione ad ARC

37

Conversione ad ARC

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

autoreleasepool code here NSString s = [(id)CFStringCreateWithX(hellip) autorelease] NSString s = CFBridgingRelease(CFStringCreateWithX(hellip))

38

Conversione Automatica

39

From the command line via the -ccc-arcmt-check and -ccc-arcmt-modify arguments

Conversione Automatica

40

Nessuno egrave perfetto

41

Strani Autorelease Pools

Toll-Free Bridging

Structs

Giochetti con i Puntatori

Singleton

Eccezioni

case

Blocks

Conversione Parziale

42

43

ARC egrave costituito da due componenti principali

bull ARC front end compiler

bull ARC optimizer

Come Funziona ARC

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 25: Automatic Reference Counting

Limiti del GC Objective-C

NSData data = [obj someData]const char bytes = [data bytes]

NSUInteger length = [data length]for (NSUInteger i = 0 i lt length ++i) printf(ldquoxrdquo bytes[i])

25

Limiti del GC Objective-C

26

Limiti del GC Objective-C

27

iPhone GCvs

28

iPhone Androidvs

29

30

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)

31

Static Analyzer

32

Analysis + Auto-Fix + Goodies

33

Requisiti di Sistema

bull iOS 5

bull OS X 107

bull iOS 4 - no runtime

bull OS X 106 (64-bit) - no runtime

34

Requisiti di Runtime

bull Clang (LLVM compiler) 30 or later

bull Obj-C Runtime objc4 4939 or later

bull For iOS4 or OS X 106 libarclite_iphoneosa or libarclite_macosxa is linked to make ARC work

35

Conversione ad ARC

36

Conversione ad ARC

37

Conversione ad ARC

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

autoreleasepool code here NSString s = [(id)CFStringCreateWithX(hellip) autorelease] NSString s = CFBridgingRelease(CFStringCreateWithX(hellip))

38

Conversione Automatica

39

From the command line via the -ccc-arcmt-check and -ccc-arcmt-modify arguments

Conversione Automatica

40

Nessuno egrave perfetto

41

Strani Autorelease Pools

Toll-Free Bridging

Structs

Giochetti con i Puntatori

Singleton

Eccezioni

case

Blocks

Conversione Parziale

42

43

ARC egrave costituito da due componenti principali

bull ARC front end compiler

bull ARC optimizer

Come Funziona ARC

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 26: Automatic Reference Counting

Limiti del GC Objective-C

26

Limiti del GC Objective-C

27

iPhone GCvs

28

iPhone Androidvs

29

30

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)

31

Static Analyzer

32

Analysis + Auto-Fix + Goodies

33

Requisiti di Sistema

bull iOS 5

bull OS X 107

bull iOS 4 - no runtime

bull OS X 106 (64-bit) - no runtime

34

Requisiti di Runtime

bull Clang (LLVM compiler) 30 or later

bull Obj-C Runtime objc4 4939 or later

bull For iOS4 or OS X 106 libarclite_iphoneosa or libarclite_macosxa is linked to make ARC work

35

Conversione ad ARC

36

Conversione ad ARC

37

Conversione ad ARC

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

autoreleasepool code here NSString s = [(id)CFStringCreateWithX(hellip) autorelease] NSString s = CFBridgingRelease(CFStringCreateWithX(hellip))

38

Conversione Automatica

39

From the command line via the -ccc-arcmt-check and -ccc-arcmt-modify arguments

Conversione Automatica

40

Nessuno egrave perfetto

41

Strani Autorelease Pools

Toll-Free Bridging

Structs

Giochetti con i Puntatori

Singleton

Eccezioni

case

Blocks

Conversione Parziale

42

43

ARC egrave costituito da due componenti principali

bull ARC front end compiler

bull ARC optimizer

Come Funziona ARC

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 27: Automatic Reference Counting

Limiti del GC Objective-C

27

iPhone GCvs

28

iPhone Androidvs

29

30

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)

31

Static Analyzer

32

Analysis + Auto-Fix + Goodies

33

Requisiti di Sistema

bull iOS 5

bull OS X 107

bull iOS 4 - no runtime

bull OS X 106 (64-bit) - no runtime

34

Requisiti di Runtime

bull Clang (LLVM compiler) 30 or later

bull Obj-C Runtime objc4 4939 or later

bull For iOS4 or OS X 106 libarclite_iphoneosa or libarclite_macosxa is linked to make ARC work

35

Conversione ad ARC

36

Conversione ad ARC

37

Conversione ad ARC

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

autoreleasepool code here NSString s = [(id)CFStringCreateWithX(hellip) autorelease] NSString s = CFBridgingRelease(CFStringCreateWithX(hellip))

38

Conversione Automatica

39

From the command line via the -ccc-arcmt-check and -ccc-arcmt-modify arguments

Conversione Automatica

40

Nessuno egrave perfetto

41

Strani Autorelease Pools

Toll-Free Bridging

Structs

Giochetti con i Puntatori

Singleton

Eccezioni

case

Blocks

Conversione Parziale

42

43

ARC egrave costituito da due componenti principali

bull ARC front end compiler

bull ARC optimizer

Come Funziona ARC

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 28: Automatic Reference Counting

iPhone GCvs

28

iPhone Androidvs

29

30

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)

31

Static Analyzer

32

Analysis + Auto-Fix + Goodies

33

Requisiti di Sistema

bull iOS 5

bull OS X 107

bull iOS 4 - no runtime

bull OS X 106 (64-bit) - no runtime

34

Requisiti di Runtime

bull Clang (LLVM compiler) 30 or later

bull Obj-C Runtime objc4 4939 or later

bull For iOS4 or OS X 106 libarclite_iphoneosa or libarclite_macosxa is linked to make ARC work

35

Conversione ad ARC

36

Conversione ad ARC

37

Conversione ad ARC

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

autoreleasepool code here NSString s = [(id)CFStringCreateWithX(hellip) autorelease] NSString s = CFBridgingRelease(CFStringCreateWithX(hellip))

38

Conversione Automatica

39

From the command line via the -ccc-arcmt-check and -ccc-arcmt-modify arguments

Conversione Automatica

40

Nessuno egrave perfetto

41

Strani Autorelease Pools

Toll-Free Bridging

Structs

Giochetti con i Puntatori

Singleton

Eccezioni

case

Blocks

Conversione Parziale

42

43

ARC egrave costituito da due componenti principali

bull ARC front end compiler

bull ARC optimizer

Come Funziona ARC

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 29: Automatic Reference Counting

iPhone Androidvs

29

30

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)

31

Static Analyzer

32

Analysis + Auto-Fix + Goodies

33

Requisiti di Sistema

bull iOS 5

bull OS X 107

bull iOS 4 - no runtime

bull OS X 106 (64-bit) - no runtime

34

Requisiti di Runtime

bull Clang (LLVM compiler) 30 or later

bull Obj-C Runtime objc4 4939 or later

bull For iOS4 or OS X 106 libarclite_iphoneosa or libarclite_macosxa is linked to make ARC work

35

Conversione ad ARC

36

Conversione ad ARC

37

Conversione ad ARC

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

autoreleasepool code here NSString s = [(id)CFStringCreateWithX(hellip) autorelease] NSString s = CFBridgingRelease(CFStringCreateWithX(hellip))

38

Conversione Automatica

39

From the command line via the -ccc-arcmt-check and -ccc-arcmt-modify arguments

Conversione Automatica

40

Nessuno egrave perfetto

41

Strani Autorelease Pools

Toll-Free Bridging

Structs

Giochetti con i Puntatori

Singleton

Eccezioni

case

Blocks

Conversione Parziale

42

43

ARC egrave costituito da due componenti principali

bull ARC front end compiler

bull ARC optimizer

Come Funziona ARC

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 30: Automatic Reference Counting

30

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)

31

Static Analyzer

32

Analysis + Auto-Fix + Goodies

33

Requisiti di Sistema

bull iOS 5

bull OS X 107

bull iOS 4 - no runtime

bull OS X 106 (64-bit) - no runtime

34

Requisiti di Runtime

bull Clang (LLVM compiler) 30 or later

bull Obj-C Runtime objc4 4939 or later

bull For iOS4 or OS X 106 libarclite_iphoneosa or libarclite_macosxa is linked to make ARC work

35

Conversione ad ARC

36

Conversione ad ARC

37

Conversione ad ARC

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

autoreleasepool code here NSString s = [(id)CFStringCreateWithX(hellip) autorelease] NSString s = CFBridgingRelease(CFStringCreateWithX(hellip))

38

Conversione Automatica

39

From the command line via the -ccc-arcmt-check and -ccc-arcmt-modify arguments

Conversione Automatica

40

Nessuno egrave perfetto

41

Strani Autorelease Pools

Toll-Free Bridging

Structs

Giochetti con i Puntatori

Singleton

Eccezioni

case

Blocks

Conversione Parziale

42

43

ARC egrave costituito da due componenti principali

bull ARC front end compiler

bull ARC optimizer

Come Funziona ARC

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 31: Automatic Reference Counting

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)

31

Static Analyzer

32

Analysis + Auto-Fix + Goodies

33

Requisiti di Sistema

bull iOS 5

bull OS X 107

bull iOS 4 - no runtime

bull OS X 106 (64-bit) - no runtime

34

Requisiti di Runtime

bull Clang (LLVM compiler) 30 or later

bull Obj-C Runtime objc4 4939 or later

bull For iOS4 or OS X 106 libarclite_iphoneosa or libarclite_macosxa is linked to make ARC work

35

Conversione ad ARC

36

Conversione ad ARC

37

Conversione ad ARC

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

autoreleasepool code here NSString s = [(id)CFStringCreateWithX(hellip) autorelease] NSString s = CFBridgingRelease(CFStringCreateWithX(hellip))

38

Conversione Automatica

39

From the command line via the -ccc-arcmt-check and -ccc-arcmt-modify arguments

Conversione Automatica

40

Nessuno egrave perfetto

41

Strani Autorelease Pools

Toll-Free Bridging

Structs

Giochetti con i Puntatori

Singleton

Eccezioni

case

Blocks

Conversione Parziale

42

43

ARC egrave costituito da due componenti principali

bull ARC front end compiler

bull ARC optimizer

Come Funziona ARC

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 32: Automatic Reference Counting

Static Analyzer

32

Analysis + Auto-Fix + Goodies

33

Requisiti di Sistema

bull iOS 5

bull OS X 107

bull iOS 4 - no runtime

bull OS X 106 (64-bit) - no runtime

34

Requisiti di Runtime

bull Clang (LLVM compiler) 30 or later

bull Obj-C Runtime objc4 4939 or later

bull For iOS4 or OS X 106 libarclite_iphoneosa or libarclite_macosxa is linked to make ARC work

35

Conversione ad ARC

36

Conversione ad ARC

37

Conversione ad ARC

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

autoreleasepool code here NSString s = [(id)CFStringCreateWithX(hellip) autorelease] NSString s = CFBridgingRelease(CFStringCreateWithX(hellip))

38

Conversione Automatica

39

From the command line via the -ccc-arcmt-check and -ccc-arcmt-modify arguments

Conversione Automatica

40

Nessuno egrave perfetto

41

Strani Autorelease Pools

Toll-Free Bridging

Structs

Giochetti con i Puntatori

Singleton

Eccezioni

case

Blocks

Conversione Parziale

42

43

ARC egrave costituito da due componenti principali

bull ARC front end compiler

bull ARC optimizer

Come Funziona ARC

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 33: Automatic Reference Counting

Analysis + Auto-Fix + Goodies

33

Requisiti di Sistema

bull iOS 5

bull OS X 107

bull iOS 4 - no runtime

bull OS X 106 (64-bit) - no runtime

34

Requisiti di Runtime

bull Clang (LLVM compiler) 30 or later

bull Obj-C Runtime objc4 4939 or later

bull For iOS4 or OS X 106 libarclite_iphoneosa or libarclite_macosxa is linked to make ARC work

35

Conversione ad ARC

36

Conversione ad ARC

37

Conversione ad ARC

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

autoreleasepool code here NSString s = [(id)CFStringCreateWithX(hellip) autorelease] NSString s = CFBridgingRelease(CFStringCreateWithX(hellip))

38

Conversione Automatica

39

From the command line via the -ccc-arcmt-check and -ccc-arcmt-modify arguments

Conversione Automatica

40

Nessuno egrave perfetto

41

Strani Autorelease Pools

Toll-Free Bridging

Structs

Giochetti con i Puntatori

Singleton

Eccezioni

case

Blocks

Conversione Parziale

42

43

ARC egrave costituito da due componenti principali

bull ARC front end compiler

bull ARC optimizer

Come Funziona ARC

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 34: Automatic Reference Counting

Requisiti di Sistema

bull iOS 5

bull OS X 107

bull iOS 4 - no runtime

bull OS X 106 (64-bit) - no runtime

34

Requisiti di Runtime

bull Clang (LLVM compiler) 30 or later

bull Obj-C Runtime objc4 4939 or later

bull For iOS4 or OS X 106 libarclite_iphoneosa or libarclite_macosxa is linked to make ARC work

35

Conversione ad ARC

36

Conversione ad ARC

37

Conversione ad ARC

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

autoreleasepool code here NSString s = [(id)CFStringCreateWithX(hellip) autorelease] NSString s = CFBridgingRelease(CFStringCreateWithX(hellip))

38

Conversione Automatica

39

From the command line via the -ccc-arcmt-check and -ccc-arcmt-modify arguments

Conversione Automatica

40

Nessuno egrave perfetto

41

Strani Autorelease Pools

Toll-Free Bridging

Structs

Giochetti con i Puntatori

Singleton

Eccezioni

case

Blocks

Conversione Parziale

42

43

ARC egrave costituito da due componenti principali

bull ARC front end compiler

bull ARC optimizer

Come Funziona ARC

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 35: Automatic Reference Counting

Requisiti di Runtime

bull Clang (LLVM compiler) 30 or later

bull Obj-C Runtime objc4 4939 or later

bull For iOS4 or OS X 106 libarclite_iphoneosa or libarclite_macosxa is linked to make ARC work

35

Conversione ad ARC

36

Conversione ad ARC

37

Conversione ad ARC

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

autoreleasepool code here NSString s = [(id)CFStringCreateWithX(hellip) autorelease] NSString s = CFBridgingRelease(CFStringCreateWithX(hellip))

38

Conversione Automatica

39

From the command line via the -ccc-arcmt-check and -ccc-arcmt-modify arguments

Conversione Automatica

40

Nessuno egrave perfetto

41

Strani Autorelease Pools

Toll-Free Bridging

Structs

Giochetti con i Puntatori

Singleton

Eccezioni

case

Blocks

Conversione Parziale

42

43

ARC egrave costituito da due componenti principali

bull ARC front end compiler

bull ARC optimizer

Come Funziona ARC

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 36: Automatic Reference Counting

Conversione ad ARC

36

Conversione ad ARC

37

Conversione ad ARC

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

autoreleasepool code here NSString s = [(id)CFStringCreateWithX(hellip) autorelease] NSString s = CFBridgingRelease(CFStringCreateWithX(hellip))

38

Conversione Automatica

39

From the command line via the -ccc-arcmt-check and -ccc-arcmt-modify arguments

Conversione Automatica

40

Nessuno egrave perfetto

41

Strani Autorelease Pools

Toll-Free Bridging

Structs

Giochetti con i Puntatori

Singleton

Eccezioni

case

Blocks

Conversione Parziale

42

43

ARC egrave costituito da due componenti principali

bull ARC front end compiler

bull ARC optimizer

Come Funziona ARC

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 37: Automatic Reference Counting

Conversione ad ARC

37

Conversione ad ARC

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

autoreleasepool code here NSString s = [(id)CFStringCreateWithX(hellip) autorelease] NSString s = CFBridgingRelease(CFStringCreateWithX(hellip))

38

Conversione Automatica

39

From the command line via the -ccc-arcmt-check and -ccc-arcmt-modify arguments

Conversione Automatica

40

Nessuno egrave perfetto

41

Strani Autorelease Pools

Toll-Free Bridging

Structs

Giochetti con i Puntatori

Singleton

Eccezioni

case

Blocks

Conversione Parziale

42

43

ARC egrave costituito da due componenti principali

bull ARC front end compiler

bull ARC optimizer

Come Funziona ARC

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 38: Automatic Reference Counting

Conversione ad ARC

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

autoreleasepool code here NSString s = [(id)CFStringCreateWithX(hellip) autorelease] NSString s = CFBridgingRelease(CFStringCreateWithX(hellip))

38

Conversione Automatica

39

From the command line via the -ccc-arcmt-check and -ccc-arcmt-modify arguments

Conversione Automatica

40

Nessuno egrave perfetto

41

Strani Autorelease Pools

Toll-Free Bridging

Structs

Giochetti con i Puntatori

Singleton

Eccezioni

case

Blocks

Conversione Parziale

42

43

ARC egrave costituito da due componenti principali

bull ARC front end compiler

bull ARC optimizer

Come Funziona ARC

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 39: Automatic Reference Counting

Conversione Automatica

39

From the command line via the -ccc-arcmt-check and -ccc-arcmt-modify arguments

Conversione Automatica

40

Nessuno egrave perfetto

41

Strani Autorelease Pools

Toll-Free Bridging

Structs

Giochetti con i Puntatori

Singleton

Eccezioni

case

Blocks

Conversione Parziale

42

43

ARC egrave costituito da due componenti principali

bull ARC front end compiler

bull ARC optimizer

Come Funziona ARC

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 40: Automatic Reference Counting

Conversione Automatica

40

Nessuno egrave perfetto

41

Strani Autorelease Pools

Toll-Free Bridging

Structs

Giochetti con i Puntatori

Singleton

Eccezioni

case

Blocks

Conversione Parziale

42

43

ARC egrave costituito da due componenti principali

bull ARC front end compiler

bull ARC optimizer

Come Funziona ARC

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 41: Automatic Reference Counting

Nessuno egrave perfetto

41

Strani Autorelease Pools

Toll-Free Bridging

Structs

Giochetti con i Puntatori

Singleton

Eccezioni

case

Blocks

Conversione Parziale

42

43

ARC egrave costituito da due componenti principali

bull ARC front end compiler

bull ARC optimizer

Come Funziona ARC

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 42: Automatic Reference Counting

Conversione Parziale

42

43

ARC egrave costituito da due componenti principali

bull ARC front end compiler

bull ARC optimizer

Come Funziona ARC

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 43: Automatic Reference Counting

43

ARC egrave costituito da due componenti principali

bull ARC front end compiler

bull ARC optimizer

Come Funziona ARC

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 44: Automatic Reference Counting

44

bull Inserisce le release correttamente

bull ivar (strong) inserisce le release nel dealloc

bull Nel dealloc chiama il [super dealloc]

bull Genera errori sui qualificatori inconsistenti

ARC front end compiler

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 45: Automatic Reference Counting

45

bull Rimuove le retain e le release superflue

bull Ottimizza le prestazioni minimizzando le sequenza multiple di retain e [auto]release

ARC optimizer

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 46: Automatic Reference Counting

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]

46

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 47: Automatic Reference Counting

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar][foo release]

47

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 48: Automatic Reference Counting

Come Funziona ARC

Foo obj = [[Foo alloc] init][foo bar]objc_release(foo)

48

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 49: Automatic Reference Counting

Come Funziona ARC

49

retain

release

retain

release

retainrelease

retain release

retain

releaseretain

release

retain

release

retain

release

releaseretain

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 50: Automatic Reference Counting

Come Funziona ARC

Foo obj = [self foo][foo bar]

[self setFoo newFoo]

[foo baz]

50

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 51: Automatic Reference Counting

Come Funziona ARC

Foo obj = objc_retain([self foo])[foo bar][self setFoo newFoo][foo baz]objc_release(foo)

51

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 52: Automatic Reference Counting

Come Funziona ARC

- (Foo ) foo return _foo

52

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 53: Automatic Reference Counting

Come Funziona ARC

- (Foo ) foo return [[_foo retain] autorelease]

53

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 54: Automatic Reference Counting

Come Funziona ARC

- (Foo ) foo return objc_retainAutoreleaseReturnValue(_foo)

54

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 55: Automatic Reference Counting

Come Funziona ARC

55

retainautoreleaseretainrelease

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 56: Automatic Reference Counting

retainautoreleaseretainrelease

Come Funziona ARC

56

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 57: Automatic Reference Counting

Come Funziona ARC

objc_retainAutoreleaseReturnValue

objc_retainAutoreleasedReturnValue

57

metodo chiamante

metodo chiamato

Autorelease Pool

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 58: Automatic Reference Counting

retain

release

Come Funziona ARC

58

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 59: Automatic Reference Counting

Riferimenti Ciclici

1 159

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 60: Automatic Reference Counting

Riferimenti Ciclici

0 160

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 61: Automatic Reference Counting

zeroing weak references

61

X

X

Riferimento ldquodebolerdquo non sicuro

Riferimento __weak

nil

nil release

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 62: Automatic Reference Counting

Instruments

62

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 63: Automatic Reference Counting

Memory Management Rules

63

bull You have ownership of any objects you create

bull You can take ownership of an object using retain

bull When no longer needed you must relinquish ownership of an object you own

bull You must not relinquish ownership of an object you donrsquot own

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 64: Automatic Reference Counting

Memory Management Rules

64

Azione su oggetto Objective-C Metodo Objective-C

Create and have ownership of it allocnewcopymutableCopy

Take ownership of it retain

Relinquish it release

Dispose of it dealloc

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 65: Automatic Reference Counting

Qualificatori di Ownership

65

In ARC le variabili id o di tipo oggetto devono avere uno di questi 4 qualificatori di ownership

bull __strong (default)

bull __weak

bull __unsafe_unretained

bull __autoreleasing

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 66: Automatic Reference Counting

__strong

66

id obj = [[NSObject alloc] init]id __strong obj = [[NSObject alloc] init]

ARC id __strong obj = [[NSObject alloc] init] id obj = [[NSObject alloc] init]

non-ARC id obj = [[NSObject alloc] init] [obj release]

bull Default for lsquoidrsquo and object types

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 67: Automatic Reference Counting

__weak

67

bull No ownership of the object

bull When discarded the variable is assigned to nil

bull In OS X not all classes support weak

id __strong obj0 = [[NSObject alloc] init] id __weak obj1 = obj0

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 68: Automatic Reference Counting

__unsafe_unretained

68

bull UNSAFE

bull __weak only for iOS5 OSX Lion (or later)

bull You must take care of the variables manually

id __unsafe_unretained obj = [[NSObject alloc] init]

warning assigning retained obj to unsafe_unretained variable

obj will be released after assignment [-Warc-unsafe-retained-assign]

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 69: Automatic Reference Counting

__autoreleasing

69

autoreleasepool id __strong obj = [NSMutableArray array]

- (BOOL) performOperationWithError(NSError )error

- (BOOL) performOperationWithError(NSError __autoreleasing )error

bull Pointer to lsquoidrsquo or object types is qualified with __autoreleasing as default

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 70: Automatic Reference Counting

Initialization

70

Any variables that are qualified with __strong __weak and __autoreleasing are initialized with nil

id __strong obj0id __weak obj1id __autoreleasing obj2

id __strong obj0 = nilid __weak obj1 = nilid __autoreleasing obj2 = nil

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 71: Automatic Reference Counting

Coding With ARC Rules

bull Che cosa egrave vietato fare

bull Che cosa egrave obbligatorio fare

bull Che cosa si puograve fare con attenzione

71

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 72: Automatic Reference Counting

72

[obj release]

error ARC forbids explicit message send of release

[obj release]

Rule 1

1 Forget about using retain release retainCount and autorelease

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 73: Automatic Reference Counting

73

NSAllocateObject (Class c NSUInteger extraBytes NSZone zone)

error NSAllocateObject is unavailable

not available in automatic reference counting mode

Rule 2

2 Forget about using NSAllocateObject and NSDeallocateObject

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 74: Automatic Reference Counting

bull if begins alloc new copy mutableCopy the caller has ownership

bull if begins init

bull instance method

bull return lsquoidrsquo or types of [super|sub]class

bull not registered in autoreleasepool the caller has ownership

bull special case ldquoinitializerdquo

74

Rule 3

3 Follow the naming rule for methods related to object creation

- (id) init

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 75: Automatic Reference Counting

75

bull NS_RETURNS_NON_RETAINED

bull NS_RETURNS_RETAINED

-(NSString) copyRightString

-(NSString) copyRightString NS_RETURNS_NON_RETAINED

Rule 3 (Positive False)

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 76: Automatic Reference Counting

76

- (void) dealloc free(buffer) [super dealloc]

error ARC forbids explicit message send of dealloc

[super dealloc]

not available in automatic reference counting mode

Rule 4

4 Forget about calling super dealloc explicitly

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 77: Automatic Reference Counting

77

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init] [pool drain]

error NSAutoreleasePool is unavailable

not available in automatic reference counting mode

NSAutoreleasePool pool = [[NSAutoreleasePool alloc] init]

^

Rule 5

5 Use autoreleasepool Instead of NSAutoreleasePool

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 78: Automatic Reference Counting

78

Rule 6

6 Forget About Using Zone (NSZone)

bull If __OBJC2__ is defined the runtime just ignores zones

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 79: Automatic Reference Counting

79

struct Data NSMutableArray array

error ARC forbids Objective-C objs in structs or unions

NSMutableArray array

Rule 7

7 Object Type Variables Cannot Be Members of struct or union in C

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 80: Automatic Reference Counting

80

Rule 8

8 id and void Have to Be Cast Explicitly

Special kind of casts

bull (__bridge cast)

bull (__bridge_retained cast)

bull (__bridge_transfer cast)

id obj = [[NSObject alloc] init] void p = obj

error implicit conversion of a non-Objective-C pointer type void to id is disallowed with ARC

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 81: Automatic Reference Counting

81

id obj = [[NSObject alloc] init] void p = (__bridge void )obj id o = (__bridge id)p

Rule 8 (__bridge cast)

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 82: Automatic Reference Counting

82

ARC id obj = [[NSObject alloc] init]void p = (__bridge_retained void )obj

non-ARC id obj = [[NSObject alloc] init]void p = obj [(id)p retain]

Rule 8 (__bridge_retained cast)

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 83: Automatic Reference Counting

83

ARC id obj = (__bridge_transfer id)p

non-ARC id obj = (id)p[obj retain][(id)p release]

Rule 8 (__bridge_transfer cast)

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 84: Automatic Reference Counting

84

bull Convert an object between Obj-C and Core Foundation

CFTypeRef CFBridgingRetain(id X) return (__bridge_retained CFTypeRef)X

id CFBridgingRelease(CFTypeRef X) return (__bridge_transfer id)X

Rule 8 (Toll-Free Bridging)

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 85: Automatic Reference Counting

85

(__bridge cast)

CFBridgingRetain()

CFBridgingRelease()

passaggio diretto del blocco puntato nessun trasferimento di ownership

trasferimento di ownership da ARC a Core Foundation

trasferimento di ownership da Core Foundation ad ARC

Rule 8 (Toll-Free Bridging)

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 86: Automatic Reference Counting

86

Rule 9

9 Switch cases must be wrapped in scope with

switch (someInt) case 0 NSLog(Case 0) break

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 87: Automatic Reference Counting

bull For performance purpose ARC code leaks on exceptions

bull In Obj-C ARC is not exception-safe for normal releases by default

bull -fobjc-arc-exceptions -fno-objc-arc-exceptions enable disable

bull In Obj-C++ -fobjc-arc-exceptions is enabled by default

87

Rule 10

10Exceptions use must be exceptional

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 88: Automatic Reference Counting

bull Outlets should be defined as declared properties

bull Outlets should generally be weak

bull Top-level objects (or in iOS a storyboard scene) should be strong

88

Rule 11

11IBOutlet must be declared as weak

Resource Programming Guide

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 89: Automatic Reference Counting

89

static MyClass sharedManager = nil

+ (MyClass)sharedManager

synchronized(self)

if (sharedManager == nil)

sharedManager =

[[super allocWithZoneNULL] init]

return sharedManager

+ (id)allocWithZone(NSZone )zone

return [[self sharedManager] retain]

- (id)copyWithZone(NSZone )zone

return self

- (id)retain

return self

- (NSUInteger)retainCount

return NSUIntegerMax cannot be released

- (oneway void)release

do nothing

- (id)autorelease

return self

Rule 12

12Singletons should be redefined with dispatch_async

Resource Programming Guide

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 90: Automatic Reference Counting

+ (id)sharedInstance static dispatch_once_t predicate dispatch_once(amppredicate ^ sharedInstance = [[MyClass alloc] init] ) return sharedInstance

90

Single threaded results Multi threaded results----------------------- ----------------------- synchronized 33829 seconds synchronized 335171 seconds dispatch_once 09891 seconds dispatch_once 16648 seconds

httpbjhomerblogspotit201109synchronized-vs-dispatchoncehtml

Rule 12 (new singleton)

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 91: Automatic Reference Counting

91

pragma clang diagnostic pushpragma clang diagnostic ignored -Warc-performSelector-leaks [self performSelectorselfmySel]pragma clang diagnostic pop

Rule 13

13Be careful with performSelector

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 92: Automatic Reference Counting

bull Property

bull Array

bull Block

Constructs With ARC

92

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 93: Automatic Reference Counting

Property

93

Property modifier Ownership qualifier

assign __unsafe_unretained

copy __strong (note new copied object is assigned)

retain __strong

strong __strong

unsafe_unretained __unsafe_unretained

weak __weak

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 94: Automatic Reference Counting

Property

94

bull Same ownership rules as variables

bull copy copies the object by using copyWithZone

bull manually declared ivar has to have the same ownership qualifier as the property

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 95: Automatic Reference Counting

95

bull ARC forbids synthesizing a readonly property without specifying an ownership qualifier

property (nonatomic readonly) MyObj objsynthesize obj

error ARC forbids synthesizing a property of an Objective-C object with unspecified ownership or storage attribute

Property

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 96: Automatic Reference Counting

96

bull C static arrays qualified with __strong __weak __autoreleasing are initialized with nil

bull For dynamic arrays should be used containers in the Foundation Framework

id objs0[10]id __weak objs1[20]

NSMutableArray objs2 = [NSMutableArray alloc] init]

Array

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 97: Automatic Reference Counting

97

void (^block)(void) = ^ [self doSomethingImportant]ivar = block ARC inserts [block copy]

Block

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 98: Automatic Reference Counting

Block

return ^ [self doSomethingGreat]

98

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 99: Automatic Reference Counting

Block

[array addObject ^ hellip ]

- (id)method return ^ hellip

99

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 100: Automatic Reference Counting

Block

[[[[[[[[[[block copy] copy] copy] copy] copy] copy] copy] copy] copy] copy]

100

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 101: Automatic Reference Counting

Block

__block variable

__weak variable

101

in MRC mutable amp ldquodebolerdquo

in ARC mutable amp strong

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 102: Automatic Reference Counting

Block amp Riferimenti Ciclici iMyObj id ivar void (^block)(void)

102

^ [self something] [ivar something]

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 103: Automatic Reference Counting

103

__weak MyClass weakSelf = self^ [weakSelf something]

Block amp Riferimenti Ciclici

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 104: Automatic Reference Counting

104

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 105: Automatic Reference Counting

105

__weak MyClass weakSelf = self^ if (weakSelf) [weakSelf-gtivar something]

Block amp Riferimenti Ciclici

nil

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 106: Automatic Reference Counting

106

__weak MyClass weakSelf = self^ MyClass localSelf = weakSelf if (localSelf) [localSelf-gtivar something]

Block amp Riferimenti Ciclici

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 107: Automatic Reference Counting

ARC MACRO define some LLVM3 macros if the code is compiled with a different compiler (ie LLVMGCC42)ifndef __has_featuredefine __has_feature(x) 0endififndef __has_extensiondefine __has_extension __has_feature Compatibility with pre-30 compilersendif

if __has_feature(objc_arc) ampamp __clang_major__ gt= 3define ARC_ENABLED 1endif __has_feature(objc_arc)

107

Check compile-time if ARC is enabled

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 108: Automatic Reference Counting

Conclusioni

108

bull La Garbage collection eacute una gran bella idea

bull LObjective-C egrave un gran bel linguaggio

bull LObjective-C + La Garbage Collection non sono una gran bella accoppiata

MA

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 109: Automatic Reference Counting

Conclusioni

109

ARC non egrave la Garbage Collection

hellip anche se ci arriva vicino )

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 110: Automatic Reference Counting

Conclusioni

110

bull Le zeroing weak references sono indispensabili

bull Utilizziamo __weak per evitare i riferimenti ciclici

bull Utilizziamo __unsafe_unretained se e solo se non possiamo usare __weak

bull Utilizziamo Instruments Leaks per individuare i riferimenti ciclici

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 111: Automatic Reference Counting

Conclusioni

111

bull ARC sa gestire soltanto gli oggetti Objective-C

bull Utilizziamo sempre __bridge CFBridgingRetain CFBridgingRelease per interagire con Core Foundation

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 112: Automatic Reference Counting

Conclusioni

112

bull ARC egrave una figata

bull Iniziamo subito ad usarlo

bull Convertiamo il nostro codice

bull Risparmiamo tempo

bull Risparmiamo denaro

bull Viviamo meglio

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 113: Automatic Reference Counting

ARC Reference documentation and articlesClang Automatic Reference Counting documentation

bull Apple Transitioning to ARC Release Notesbull Apple Xcode New Features User Guide Automatic Reference Countingbull Mike Ash Friday QampA about Automatic Reference Countingbull StackOverflow How does automatic reference counting workbull StackOverflow What are the advantages and disadvantages of using ARCbull StackOverflow What is the difference between ARC and garbage collectionbull informIT Automatic Reference Counting in Objective-C Part 1bull informIT Automatic Reference Counting in Objective-C Part 2 The Detailsbull Mike Ash Zeroing weak references without ARCbull Github Support for zeroing weak references on iOS 4 OS X 106bull Assembler - A look under ARCrsquos hoodbull MKBlog - Migrating your code to Objective-C ARCbull Ray Wenderlich - Beginning ARC in iOS 5 Tutorial

113

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 114: Automatic Reference Counting

ARC Reference videos

bull WWDC 2011 ndash Session 322 ndash Introduction to Automatic Reference Countingbull WWDC 2011 ndash Session 322 ndash Objective-C Advancements in depthbull WWDC 2011 ndash Session 308 ndash Blocks and Grand Central Dispatch in Practice

bull NSScreenCasts Episode 9 - Automatic Reference Counting

114

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 115: Automatic Reference Counting

ARC Reference books

bull Pro Multithreading and Memory Management for iOS and OS X with ARC Grand Central Dispatch and Blocks ndash By Kazuki Sakamoto Apress

bull Programming iOS 5 Fundamentals of iPhone iPad and iPod touch Development Second Edition ndash By Matt Neuburg OrsquoReilly

115

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 116: Automatic Reference Counting

Sorry

116

Automatic Reference Counting Specifications

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 117: Automatic Reference Counting

Questions

117

giuseppearicigmailcom

Thanks

118

giuseppearicicom pragmamarkorg

Page 118: Automatic Reference Counting

Thanks

118

giuseppearicicom pragmamarkorg