简体   繁体   English

使用Objective-C和Swift造成内存泄漏

[英]Creat a memory leak with Objective-C and Swift

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

You just need to create a reference cycle. 您只需要创建一个参考周期。 Obj-C: 对象:

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

@implementation MyClass
@end

//...

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

The same applies to Swift: 同样适用于Swift:

class MyClass {
    var otherObject: MyClass?
}

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

Reason : a holds a strong reference to b , and b holds a strong reference to a . 原因a强烈引用bb强烈引用a ARC doesn't have any garbage collection in runtime. ARC在运行时没有任何垃圾回收。 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). 在这种情况下,即使我们在代码中没有对ab的引用,它们的引用计数也永远不会达到0 ,因为它们彼此引用(除非我们手动中断此循环)。

UPD (kudos to @Sulthan): you don't actually even need two objects, a strong self reference is enough: UPD (对@Sulthan表示感谢):实际上,您甚至不需要两个对象,一个强大的自我引用就足够了:

a.otherObject = a

The block example: 块示例:

@interface Foo:NSObject
@property(strong, copy) dispatch_block_t block;
- (void)doTheMagic;
@end

...
Foo *f = [Foo new];
f.block = ^{
   [f doTheMagic];
};

The fix: 解决方法:

Foo *f = [Foo new];
__weak typeof(f) __weakF = f;
f.block = ^{
   // you can do the __strong dance here if you use __weakF more than once
   [__weakF doTheMagic];
};

The malloc example: malloc示例:

void leakVampires() {
    void *buffy = malloc(42);
 }

  ...
 leakVampires();

如果CGImageRef对象已创建但未释放,则ARC无法释放这些对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM