现在的位置: 首页 > 综合 > 正文

关于ARC的一些说法

2013年09月14日 ⁄ 综合 ⁄ 共 2015字 ⁄ 字号 评论关闭

以下全部在xCode 4.5,llvm 4.1的测试环境中

1.IBOUTLET

对于IBOUTLET必须是weak的说法,经过使用Instruments测试,使用strong修饰在arc开启的情况下完全没有任何内存遗留不释放的问题。
而在arc关闭的情况下,如果是assign修饰的,则不用处理,如果是retain的必须在退出viewController的时候release对象。如果是简单的放在变量定义里面没有@property修饰的话,也需要release。

2.Toll-Free Bridging
CFBridgingRelease,__bridge_transfer,用来将CFType的转化成id类型,并且这个id类型的周期由arc来控制,你不用管了
CFBridgingRetain,__bridge_retained,用来将id的转化成CFType类型,并且用完这个CFType后你需要CFRelease这个CFType。
__bridge 只做转化,内存保留什么的统统没有

3.block
block创建的时候内存分配在栈上,如果在作用域外面调用的话会出错导致程序崩溃。解决的办法就是创建完成后调用copy方法,移动到堆上。
block会对内部的对象进行一次retain,但是被__block 存储类型修饰符标记的对象变量不会被retain。所以为了避免retain-loop,如果类A中的了Block B需要调用A,那么要要这么用

__block __weak A* a = self;
B = ^(){a....}

或者

复制代码
__weak id weakSelf = self; 
block = ^() { 
id strongSelf = weakSelf; 
if (strongSelf != nil) 
{ 
// do stuff with strongSelf 
} 
};
复制代码

 

5.readonly
“readonly属性的变量同时必须要定义strong或者weak”
这种说法是错误的,下面定义可以编译通过()

@property (nonatomic, readonly) NSString *name;

 

6.autorelease
这里
@autorelease在ARC开启和关闭的情况下,
interface里面 NSString* myString;
某个函数里面

复制代码
{
[self test];
NSLog(@"myString: %@",myString);// 他的说法这里在开启arc时是nil
}

-(void)test{
@autoreleasepool {
NSString *string= [[NSString alloc] initWithFormat:@"First Name: %@", @"tom"];
NSLog(@"string: %@",string);
myString=string;
}
}
复制代码

对strong类型的对象赋值有所不同。
经测试,是相同的,都能正确的给myString赋值。
__autoreleasing 用来修饰一个声明为 (id *) 的函数的参数

7.对工程是否支持arc的判断

#if __has_feature(objc_arc) 
// do your ARC thing here 
#endif 


或者假如你还想支持老的GCC compiler:

#if defined(__has_feature) && __has_feature(objc_arc) 
// do your ARC thing here 
#endif 


更多相关的宏定义:看这里

8.不确定性
下面的代码跑起来可能没有问题,但是,在setBackgroundColor之前,由于uicolor已经不在被引用了,所以有可能已经被释放了,从而setBackgroundColor可能不是你想要的结果。

复制代码
UIColor *uicolor = [UIColor colorWithRed: 0.2 
green: 0.3 
blue: 0.4 
alpha: 1.0];
CGColorRef color = uicolor.CGColor;
[[self.view layer] setBackgroundColor: color];
复制代码

9.C结构体
Objective-C 对象不能作为C语言结构体(struct/union)的成员。
当我们必须在C语言的结构体中放入 Objective-C 对象的时候,可以使用 void* 转型,或者使用 __unsafe_unretained 关键字。注意id与void*之间需要明示cast。


参考:
1.http://blog.bignerdranch.com/296-arc-gotcha-unexpectedly-short-lifetimes/
2.http://www.mikeash.com/pyblog/friday-qa-2011-09-30-automatic-reference-counting.html
3.http://www.yifeiyang.net/development-of-the-iphone-simply-7/

抱歉!评论已关闭.