Automatic Reference Counting
-
Upload
pragmamark -
Category
Technology
-
view
1.180 -
download
0
description
Transcript of 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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
__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
__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
__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
__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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
+ (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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
Sorry
116
Automatic Reference Counting Specifications
Questions
117
giuseppearicigmailcom
Thanks
118
giuseppearicicom pragmamarkorg
Questions
117
giuseppearicigmailcom
Thanks
118
giuseppearicicom pragmamarkorg
Thanks
118
giuseppearicicom pragmamarkorg