簡體   English   中英

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

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

我接受了采訪,並被要求使用Objective-C和Swift創建內存泄漏,那么如何使用Objective-C和Swift創建內存泄漏呢?

您只需要創建一個參考周期。 對象:

@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;

同樣適用於Swift:

class MyClass {
    var otherObject: MyClass?
}

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

原因a強烈引用bb強烈引用a ARC在運行時沒有任何垃圾回收。 它只是跟蹤參考計數。 在這種情況下,即使我們在代碼中沒有對ab的引用,它們的引用計數也永遠不會達到0 ,因為它們彼此引用(除非我們手動中斷此循環)。

UPD (對@Sulthan表示感謝):實際上,您甚至不需要兩個對象,一個強大的自我引用就足夠了:

a.otherObject = a

塊示例:

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

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

解決方法:

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];
};

malloc示例:

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

  ...
 leakVampires();

如果CGImageRef對象已創建但未釋放,則ARC無法釋放這些對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM