简体   繁体   中英

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:

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 . 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 (kudos to @Sulthan): you don't actually even need two objects, a strong self reference is enough:

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:

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

  ...
 leakVampires();

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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