Durai Amuthan.H Durai Amuthan.H - 3 months ago 11
Swift Question

Memory leak in swift while invoking description method of an instance

Memory leak happens when I call description on the instance logg

public func writeLog(logs:AnyObject!...) {
for i:Int in 0 ..< logs.count {
if let logg = logs[i] {
var log:String?=logg.description
log = nil
}
}
}


This is how I call

writeLog("Hi")


Here is the screenshot of the memory leak from instruments

Memory leak in instruments

Leaks by backtrace

Memory leak hierarchy

Any help to resolving the issue is highly appreciated !

Answer

It's a typecasting problem but I am not sure why AnyObject.description causes.

instead of this

if let logg = logs[i] {
                var log:String?=logg.description
                log = nil
            }

try to change your code like this

  if let logg = logs[i] as! String{
                var log:String?=logg.description
                log = nil
            }

This won't throw any memory leak

so include conditional branches to check for type of the instance and do a typecast and call the description !

Voila !!! :)