使用ARC时必须遵循的方法命名规则
将内存管理语义在方法名中表示出来早已成为Objective-C的惯例,而ARC则将之确立为硬性规定。这些规则简单地体现在方法名上。若方法名以下词语开头,则将其返回的对象归调用者所有:
alloc
new
copy
mutableCopy
归调用者所有的意思是:调用上述四种方法的那段代码要负责释放方法所返回的对象。
若方法名不以上述4个词语开头,则表示所返回的对象不归调用者所拥有。在这种情况下,返回的对象会自动释放,所以其值在跨越方法调用边界后依然后效。要想使对象多存活一段时间,必须令调用者保留它才行。维系这些所需的全部内存管理均有ARC自动处理。
(EOCPerson )newPerson
{
EOCPerson person = [[EOCPerson alloc] init];
return person;
/
The method name begins with 'new' and since 'person' already has an unbalanced +1 retain count from the alloc, no retains, releases, or autoreleases are required when returning
**/
}(EOCPerson )somePerson
{
EOCPerson person = [[EOCPerson alloc] init];
return person;
/
The method name does not begin with one of the "owning" prefiexes, therefore ARC will add an autorelease when return 'person'
**/
}
- (void)doSomething
{
EOCPerson personOne = [EOCPerson newPerson];
EOCPerson personTwo = [EOCPerson otherPerson];
/
At the point , 'personOne' and 'personTwo' go out of scope , therefore ARC needs to clean them up as required .
----'personOne' was returned as owned by this block of code, so ti needs to be released
----'personTwo' was not returned as owned by this block of code, so does not need to be released
}
ARC通过命名约定将内存管理规定标准化。
变量的内存管理的语义:
ARC也会处理局部变量与实例变量的内存管理。默认的情况下,每个变量都是指向对象的强引用。
我们经常会给局部变量加上__weak修饰符,用以打破由“块”所引入的保留环