在ARC下怎么不执行arc dealloc 不调用

这次探索源自于自己一直以来对ARC的一个疑问,在MRC时代,经常写下面的代码:
- (void)dealloc
&&&&self.array =
&&&&self.string =
&&&&// ... //
&&&&// 非Objc对象内存的释放,如CFRelease(...)
&&&&// ... //
&&&&[super dealloc];
对象析构时将内部其他对象release掉,申请的非Objc对象的内存当然也一并处理掉,最后调用super,继续将父类对象做析构。而现如今到了ARC时代,只剩下了下面的代码:
- (void)dealloc
&&&&// ... //
&&&&// 非Objc对象内存的释放,如CFRelease(...)
&&&&// ... //
问题来了:
这个对象实例变量(Ivars)的释放去哪儿了?
没有显示的调用[super dealloc],上层的析构去哪儿了?
ARC文档中对dealloc过程的解释
中对ARC下的dealloc过程做了简单说明,从中还是能找出些有用的信息:
A class may provide a method definition for an instance method named dealloc. This method will be called after the final release of the object but before it is deallocated or any of its instance variables are destroyed. The superclass&s implementation of dealloc will be called automatically when the method returns.
大概意思是:dealloc方法在最后一次release后被调用,但此时实例变量(Ivars)并未释放,父类的dealloc的方法将在子类dealloc方法返回后自动调用
The instance variables for an ARC-compiled class will be destroyed at some point after control enters the dealloc method for the root class of the class. The ordering of the destruction of instance variables is unspecified, both within a single class and between subclasses and superclasses.
理解:ARC下对象的实例变量在根类[NSObject dealloc]中释放(通常root class都是NSObject),变量释放顺序各种不确定(一个类内的不确定,子类和父类间也不确定,也就是说不用care释放顺序)
所以,不用主调[super dealloc]是因为自动调了,后面再说如何实现的;ARC下实例变量在根类NSObject析构时析构,下面就探究下。
NSObject的析构过程
通过apple的runtime源码,不难发现NSObject执行dealloc时调用_objc_rootDealloc继而调用object_dispose随后调用objc_destructInstance方法,前几步都是条件判断和简单的跳转,最后的这个函数如下:
void *objc_destructInstance(id obj)
&&&&if (obj) {
&&&&&&&&Class isa_gen = _object_getClass(obj);
&&&&&&&&class_t *isa = newcls(isa_gen);
&&&&&&&&// Read all of the flags at once for performance.
&&&&&&&&bool cxx = hasCxxStructors(isa);
&&&&&&&&bool assoc = !UseGC && _class_instancesHaveAssociatedObjects(isa_gen);
&&&&&&&&// This order is important.
&&&&&&&&if (cxx) object_cxxDestruct(obj);
&&&&&&&&if (assoc) _object_remove_assocations(obj);
&&&&&&&&if (!UseGC) objc_clear_deallocating(obj);
简单明确的干了三件事:
执行一个叫object_cxxDestruct的东西干了点什么事
执行_object_remove_assocations去除和这个对象assocate的对象(常用于category中添加带变量的属性,这也是为什么ARC下没必要remove一遍的原因)
执行objc_clear_deallocating,清空引用计数表并清除弱引用表,将所有weak引用指nil(这也就是weak变量能安全置空的所在)
所以,所探寻的ARC自动释放实例变量的地方就在cxxDestruct这个东西里面没跑了。
探寻隐藏的.cxx_destruct
上面找到的名为object_cxxDestruct的方法最终成为下面的调用:
static void object_cxxDestructFromClass(id obj, Class cls)
&&&&void (*dtor)(id);
&&&&// Call cls's dtor first, then superclasses's dtors.
&&&&for ( ; cls != NULL; cls = _class_getSuperclass(cls)) {
&&&&&&&&if (!_class_hasCxxStructors(cls))
&&&&&&&&dtor = (void(*)(id))
&&&&&&&&&&&&lookupMethodInClassAndLoadCache(cls, SEL_cxx_destruct);
&&&&&&&&if (dtor != (void(*)(id))_objc_msgForward_internal) {
&&&&&&&&&&&&if (PrintCxxCtors) {
&&&&&&&&&&&&&&&&_objc_inform("CXX: calling C++ destructors for class %s",
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&_class_getName(cls));
&&&&&&&&&&&&}
&&&&&&&&&&&&(*dtor)(obj);
代码也不难理解,沿着继承链逐层向上搜寻SEL_cxx_destruct这个selector,找到函数实现(void (*)(id)(函数指针)并执行。搜索这个selector的声明,发现是名为.cxx_destruct的方法,以点开头的名字,我想和unix的文件一样,是有隐藏属性的
ARC actually creates a -.cxx_destruct method to handle freeing instance variables. This method was originally created for calling C++ destructors automatically when an object was destroyed.
和《Effective Objective-C 2.0》中提到的:
When the compiler saw that an object contained C++ objects, it would generate a method called .cxx_destruct. ARC piggybacks on this method and emits the required cleanup code within it.
可以了解到,.cxx_destruct方法原本是为了C++对象析构的,ARC借用了这个方法插入代码实现了自动内存释放的工作
通过实验找出.cxx_destruct
最好的办法还是写个测试代码把这个隐藏的方法找出来,其实在runtime中运行已经没什么隐藏可言了,简单的类结构如下:
@interface Father : NSObject
@property (nonatomic, copy) NSString *
@interface Son : Father
@property (nonatomic, copy) NSArray *
只有两个简单的属性,找个地方写简单的测试代码:
&&&&&&&&// before new
&&&&&&&&Son *son = [Son new];
&&&&&&&&son.name = @"sark";
&&&&&&&&son.toys = @[@"sunny", @"xx"];
&&&&&&&&// after new
&&&&// gone
主要目的是为了让这个对象走dealloc方法,新建的son对象过了大括号作用域就会释放了,所以在after new这行son对象初始化完成,在gone这行son对象被dealloc
个人一直喜欢使用这个扩展作为调试工具,可以轻松打出一个类的方法,变量等等。
将这个扩展引入工程内,在after new处设置一个断点,run,trigger后使用lldb命令用这个扩展输出Son类所有的方法名:
发现了这个.cxx_destruct方法,经过几次试验,发现:
只有在ARC下这个方法才会出现(试验代码的情况下)
只有当前类拥有实例变量时(不论是不是用property)这个方法才会出现,且父类的实例变量不会导致子类拥有这个方法
出现这个方法和变量是否被赋值,赋值成什么没有关系
使用watchpoint定位内存释放时刻
依然在after new断点处,输入lldb命令:
watchpoint set variable son-&_name
将name的变量加入watchpoint,当这个变量被修改时会触发trigger:
从中可以看出,在这个时刻,_name从0x00006b98变成了0&0,也就是nil,赶紧看下调用栈:
发现果然跟到了.cxx_destruct方法,而且是在objc_storeStrong的过程中释放
刨根问底.cxx_destruct
知道了ARC下对象实例变量的释放过程在.cxx_destruct内完成,但这个函数内部发生了什么,是如何调用objc_storeStrong释放变量的呢?从上面的探究中知道,.cxx_destruct是编译器生成的代码,那它很可能在clang前端编译时完成,这让我联想到clang的Code Generation,因为之前曾经使用clang -rewrite-objc xxx.m时查看过官方文档留下了些印象,于是google:
.cxx_destruct site:clang.llvm.org
结果发现clang的doxygen文档中CodeGenModule模块正是这部分的实现代码,cxx相关的代码生成部分源码在位于1827行,删减掉离题部分如下:
/// EmitObjCIvarInitializations - Emit information for ivar initialization
/// for an implementation.
void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D)
&&&&DeclContext* DC = const_cast&DeclContext*&(dyn_cast&DeclContext&(D));
&&&&assert(DC && "EmitObjCIvarInitializations - null DeclContext");
&&&&IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
&&&&Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
&&&&ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(getContext(),
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&D-&getLocation(),
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&D-&getLocation(), cxxSelector,
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&getContext().VoidTy, 0,
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&DC, true, false, true,
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&ObjCMethodDecl::Required);
&&&D-&addInstanceMethod(DTORMethod);
&&&CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
这个函数大概作用是:获取.cxx_destruct的selector,创建Method,并加入到这个Class的方法列表中,最后一行的调用才是真的创建这个方法的实现。这个方法位于1354行,包含了构造和析构的cxx方法,继续跟随.cxx_destruct,最终调用emitCXXDestructMethod函数,代码如下:
static void emitCXXDestructMethod(CodeGenFunction &CGF, ObjCImplementationDecl *impl)
&&&CodeGenFunction::RunCleanupsScope scope(CGF);
&&&llvm::Value *self = CGF.LoadObjCSelf();
&&&const ObjCInterfaceDecl *iface = impl-&getClassInterface();
&&&for (const ObjCIvarDecl *ivar = iface-&all_declared_ivar_begin(); ivar = ivar-&getNextIvar())
&&&&&QualType type = ivar-&getType();
&&&&&// Check whether the ivar is a destructible type.
&&&&&QualType::DestructionKind dtorKind = type.isDestructedType();
&&&&&if (!dtorKind)
&&&&&CodeGenFunction::Destroyer *destroyer = 0;
&&&&&// Use a call to objc_storeStrong to destroy strong ivars, for the
&&&&&// general benefit of the tools.
&&&&&if (dtorKind == QualType::DK_objc_strong_lifetime) {
&&&&&&&destroyer = destroyARCStrongWithS
&&&&&// Otherwise use the default for the destruction kind.
&&&&&} else {
&&&&&&&destroyer = CGF.getDestroyer(dtorKind);
&&&&&CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
&&&&&CGF.EHStack.pushCleanup&DestroyIvar&(cleanupKind, self, ivar, destroyer,
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&cleanupKind & EHCleanup);
&&&assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
分析这段代码以及其中调用后发现:它遍历当前对象所有的实例变量(Ivars),调用objc_storeStrong,从clang的ARC文档上可以找到objc_storeStrong的示意代码实现如下:
id objc_storeStrong(id *object, id value) {
&&value = [value retain];
&&id oldValue = *
&&*object =
&&[oldValue release];
在.cxx_destruct进行形如objc_storeStrong(&ivar, null)的调用后,这个实例变量就被release和设置成nil了注:真实的实现可以参考&&2078行
自动调用[super dealloc]的实现
按照上面的思路,自动调用[super dealloc]也一定是CodeGen干的工作了 位于&&492行StartObjCMethod方法中:
if (ident-&isStr("dealloc"))
&&&&EHStack.pushCleanup&FinishARCDealloc&(getARCCleanupKind());
上面代码可以得知在调用dealloc方法时被插入了代码,由FinishARCDealloc结构定义:
struct FinishARCDealloc : EHScopeStack::Cleanup {
&&&void Emit(CodeGenFunction &CGF, Flags flags) override {
&&&&&const ObjCMethodDecl *method = cast&ObjCMethodDecl&(CGF.CurCodeDecl);
&&&&&const ObjCImplDecl *impl = cast&ObjCImplDecl&(method-&getDeclContext());
&&&&&const ObjCInterfaceDecl *iface = impl-&getClassInterface();
&&&&&if (!iface-&getSuperClass())
&&&&&bool isCategory = isa&ObjCCategoryImplDecl&(impl);
&&&&&// Call [super dealloc] if we have a superclass.
&&&&&llvm::Value *self = CGF.LoadObjCSelf();
&&&&&CallArgL
&&&&&CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&CGF.getContext().VoidTy,
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&method-&getSelector(),
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&iface,
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&isCategory,
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&self,
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&/*is class msg*/ false,
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&args,
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&method);
上面代码基本上就是向父类转发dealloc的调用,实现了自动调用[super dealloc]方法。
ARC下对象的成员变量于编译器插入的.cxx_desctruct方法自动释放
ARC下[super dealloc]方法也由编译器自动插入
所谓编译器插入代码过程需要进一步了解,还不清楚其运作方式
clang的CodeGen也值得深入研究一下
原文链接:/65028/
阅读(...) 评论()ARC下如何实现内存释放
[问题点数:40分,结帖人nhfc99]
ARC下如何实现内存释放
[问题点数:40分,结帖人nhfc99]
不显示删除回复
显示所有回复
显示星级回复
显示得分回复
只显示楼主
2015年4月 移动开发大版内专家分月排行榜第二
2015年5月 移动开发大版内专家分月排行榜第三2015年3月 移动开发大版内专家分月排行榜第三2014年10月 移动开发大版内专家分月排行榜第三
匿名用户不能发表回复!|
每天回帖即可获得10分可用分!小技巧:
你还可以输入10000个字符
(Ctrl+Enter)
请遵守CSDN,不得违反国家法律法规。
转载文章请注明出自“CSDN(www.csdn.net)”。如是商业用途请联系原作者。已经开启了ARC dealloc 还可以用?
我的工程已经开启ARC了,但是我看-(void)dealloc还是可以实现的,那这个方法还是会被调用吗?还是就是个摆设?
什么时候会调用它?ARC都开起来了,这个留着还有什么用
2012年 12月1日
(1,162 威望)
请输入验证码:
[captcha placeholder]
或 后不会被要求输入验证码。
请输入验证码:
&&&& 或 后不会被要求输入验证码。
官方文档说得很清楚You may implement a dealloc method if you need to manage resources other than releasing instance variables. You do not have to (indeed you cannot) release instance variables, but you may need to invoke [systemClassInstance setDelegate:nil] on system classes and other code that isn’t compiled using ARC.用来在dealloc的时候手动解除delegate关系。
2012年 12月1日
(761 威望)
2012年 12月1日
请输入验证码:
[captcha placeholder]
或 后不会被要求输入验证码。
提一个问题:
2012年 12月1日
(629 威望)
2015年 9月6日
(761 威望)
2015年 10月19日
(614 威望)
2013年 9月18日
(791 威望)
2015年 1月2日
(809 威望)
欢迎访问随意问技术百科,为了给您提供更好的服务,请及时反馈您的意见。iOS开发&ARC情况下调用对象的dealloc方法
众所周知,iOS开发的时候,使用ARC的话,dealloc函数是不需要实现的,写了反而会出错。
但有些特殊的情况,dealloc函数还是需要的。
比如,在画面关闭的时候,需要把ViewController的某些资源释放,
在viewDidDissppear不一定合适,viewDidUnload一般情况下只在memory
warning的时候才被调用。
不用ARC的情况下,我们自然会想到dealloc函数。
其实ARC环境下,也没有把dealloc函数禁掉,还是可以使用的。只不过不需要调用[supper dealloc]了。
举个例子,画面上有UIWebView,它的delegate是该画面的ViewController,在WebView载入完成后,需要做某些事情,比如,把indicator停掉之类的。
如果在WebView载入完成之前关闭画面的话,画面关闭后,ViewController也释放了。但由于WebView正在载入页面,而不会马上被释放,等到页面载入完毕后,回调delegate(ViewController)中的方法,由于此时ViewController已经被释放,所以会出错。(message
sent to deallocated instance)
解决办法是在dealloc中把WebView的delegate释放。
-(void)dealloc {
& & self.webView.delegate =
已投稿到:
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。主题 : 关于开启arc时dealloc的使用
级别: 侠客
UID: 143278
可可豆: 338 CB
威望: 351 点
在线时间: 171(时)
发自: Web Page
关于开启arc时dealloc的使用&&&
关于dealloc方法,我以前用arc都是直接屏蔽掉整个方法的,后来又朋友和我说里面的 [super dealloc]虽然不用了,但这个方法还是要留着的,在里面写一些 xxx=
&
那问题就来了,哪些对象需要在这里面 =nil
&
求高手解答!
级别: 新手上路
可可豆: 37 CB
威望: 31 点
在线时间: 592(时)
发自: Web Page
不知道啊,我从来没有屏蔽过。
如果要添加的话,应该是私有变量置为nil吧。
级别: 新手上路
可可豆: 179 CB
威望: 18 点
在线时间: 3(时)
发自: Web Page
ARC 是不需要释放资源的,系统会自己管理,[super dealloc]这个方法没有用,既然super都不用你写它干什么!!还有这个手动写为nil,你就不怕系统找不到原来的资源?造成内存泄漏!!所以dealloc 这个方法就没有必要写了!
级别: 侠客
UID: 143278
可可豆: 338 CB
威望: 351 点
在线时间: 171(时)
发自: Web Page
私有变量是指NSString这样的吗?那UItableView这种对象呢?还有自己定义的viewcontroller对象呢?
级别: 新手上路
可可豆: 37 CB
威望: 31 点
在线时间: 592(时)
发自: Web Page
。。不是,私有就是说其他对象不能调用的,没有用@property声明的。楼下说的有道理,我其实也没写过dealloc方法,arc模式写了dealloc方法不会报错吗?
级别: 新手上路
UID: 239886
可可豆: 20 CB
威望: 18 点
在线时间: 418(时)
发自: Web Page
ARC里请不要出现dealloc。20 20 20 20 字
级别: 骑士
UID: 156085
可可豆: 733 CB
威望: 901 点
在线时间: 738(时)
发自: Web Page
ARC 自动会帮你把你的 成员变量 置为 nil, 你不需要管,但是 delegate 你有时候 需要 收到置为 nil,特别是一些请求返回的时候。
级别: 新手上路
可可豆: 63 CB
威望: 71 点
在线时间: 112(时)
发自: Web Page
-(void)dealloc
{
&& &
& & [[NSNotificationCenter defaultCenter]removeObserver:self];
& & NSLog(@&dealloc&);
&& &
}
级别: 新手上路
UID: 226303
可可豆: 70 CB
威望: 55 点
在线时间: 11(时)
发自: Web Page
引用 众所周知,iOS开发的时候,使用ARC的话,dealloc函数是不需要实现的,写了反而会出错。但有些特殊的情况,dealloc函数还是需要的。比如,在画面关闭的时候,需要把ViewController的某些资源释放,在viewDidDissppear不一定合适,viewDidUnload一般情况下只在memory warning的时候才被调用。不用ARC的情况下,我们自然会想到dealloc函数。其实ARC环境下,也没有把dealloc函数禁掉,还是可以使用的。只不过不需要调用[supper dealloc]了。举个例子,画面上有UIWebView,它的delegate是该画面的ViewController,在WebView载入完成后,需要做某些事情,比如,把indicator停掉之类的。如果在WebView载入完成之前关闭画面的话,画面关闭后,ViewController也释放了。但由于WebView正在载入页面,而不会马上被释放,等到页面载入完毕后,回调delegate(ViewController)中的方法,由于此时ViewController已经被释放,所以会出错。(message sent to deallocated instance)解决办法是在dealloc中把WebView的delegate释放。-(void)dealloc {&&&&self.webView.delegate =}
关注本帖(如果有新回复会站内信通知您)
苹果公司现任CEO是谁?2字 正确答案:库克
发帖、回帖都会得到可观的积分奖励。
按"Ctrl+Enter"直接提交
关注CocoaChina
关注微信 每日推荐
扫一扫 浏览移动版

我要回帖

更多关于 ios arc dealloc 的文章

 

随机推荐