标签:
I Writing ARC code
1. Don’t call Retain, release, autorelease
dealloc, unless you need to release CF objects or remove observers, remove [super dealloc]
2. @autoreleasepool instead NSAutoreleasePool
3. retain->strong assign->weak reference cycle //example, when an object owns another one, use strong, otherwise, use weak, reference cycle example
NSNumber *number = [NSNumber numberWithInteger:2];
[mArray addObject:number];
[number release];
@implementation
{
NSMutableArray *_array;
}
-(id)init
{
self = [super init];
If(self)
{
_array = [[NSMutableArray alloc]init];
}
return self;
}
-(void)dealloc
{
[_array release];
[super dealloc];
}
-(id)pop
{
id x = [[_array lastObject]retain];
[_array removeLastObject];
return [x autorelease];
}
II Migrating to ARC
Fully incoperable with non-ARC code
Opt in/out per file: -fobjc-arc -fno-objc-arc
ARC migration Tool: //example, toll-free-bridge, id/int
1. Remove retain, release, autorelease
2. Change NSAutoreleasepool to @autoreleasepool
3. Change retain to strong, assign to weak
III Tips and Tricks
1. Singliton pattern
@implementation ActivityIndicator
+(ActivityIndicator*)instance
{
static ActivityIndicator *sharedInstance;
If(sharedInstance == nil)
{
sharedInstance = [[ActivityIndicator alloc]init];
}
return sharedInstance;
}
@end
2. Ownership qualifiers
__strong __weak
NSString __weak *s = [[NSString alloc]initWithFormat@"Name", self.name];
NSLog(@"string:%@", s);
__block is retained in ARC
3. Core Foundation and toll-free bridging //example
Bridged
NSString *a = (__bridge NSString*)my_cfref; //noop cast
CFStringRef b = (__bridge CFStringRef)my_id;
Move CF Object to ARC
NSString *c = (NSString*)CFBridgingRelease(my_cfref); // -1 on the CFRef (__bridge_transfer NSString*)my_cfref
Move ARC Object to CF
CFStringRef d = (CFStringRef)CFBridgingRetain(my_id); // return CFRef + 1 (_bridge_retained CFStringRef)my_id
4. Avoid object c pointer in C structures
struct x
{
id x; //won‘t compile
float y;
}
5. Mix and match with Non-ARC code
Methods beginning with "alloc, init, copy, mutableCopy,new " transfer ownership
//when called in MRC
-(NSString*)serial
{
return _serial; //autoreleased
}
-(NSString*)newSerial
{
return _serial; //retained
}
Can‘t use property names beginning with ‘new‘
标签:
原文地址:http://www.cnblogs.com/yibinpan/p/5172445.html