使用Objective-C和Swift创建内存泄漏 [英] Creat a memory leak with Objective-C and Swift

查看:124
本文介绍了使用Objective-C和Swift创建内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我接受了采访,并被要求用Objective-C和Swift创建内存泄漏。那么如何使用Objective-C和Swift创建内存泄漏?

I had an interview, and I was asked to create a memory leak with Objective-C and Swift.So how to create a memory leak with Objective-C and Swift?

推荐答案

您只需要创建一个参考周期。
Obj-C:

You just need to create a reference cycle. Obj-C:

@interface MyClass
@property (strong) MyClass *otherObject;
@end

//...

MyClass *a = [MyClass new];
MyClass *b = [MyClass new];
a.otherObject = b;
b.otherObject = a;

同样适用于Swift:

The same applies to Swift:

class MyClass {
    var otherObject: MyClass?
}

let a = MyClass()
let b = MyClass()
a.otherObject = b
b.otherObject = a

原因 a 成立强烈引用 b b 拥有对 a 。 ARC在运行时没有任何垃圾回收。它只跟踪引用计数。在这种情况下,即使我们在代码中没有引用 a b ,它们的引用计数也将永远不会达到 0 ,因为他们互相引用(除非我们手动打破这个循环)。

Reason: a holds a strong reference to b, and b holds a strong reference to a. ARC doesn't have any garbage collection in runtime. It just tracks the reference count. In this situation, even if we don't have any references to a or b in code, their reference count will never reach 0, since they reference each other (unless we'll break this cycle manually).

UPD (感谢@Sulthan):你实际上甚至不需要两个对象,强大的自我参考就足够了:

UPD (kudos to @Sulthan): you don't actually even need two objects, a strong self reference is enough:

a.otherObject = a

这篇关于使用Objective-C和Swift创建内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆