Search code examples
iosobjective-cswiftmemory-leaksobjective-c-runtime

Creat a memory leak with Objective-C and 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?


Solution

  • 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