I am developing an iOS app, using swift 4.0 (4.2 has the same issue).
I added an extension to Encodable
extension Encodable{
func toDict() throws -> [String:Any]? {
let jsonEncoder = JSONEncoder()
let jsonData = try jsonEncoder.encode(self)
do{
return try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any]
}
catch{
return nil
}
}
}
I have an instance of and Encodable class that has properties that are also of an Encodable class and noticed that when calling instance.toDict()
often, the memory that my app uses increases a lot.
This is true even if I do not use the result that is returned, it is also true if I return nil and ignore the result of JSONSerialization.jsonObject
.
I am sure it is this line that is causing the issue (ignoring the result and returning nil still causes the issue and commenting that line and returning nil will stop the memory increase.
The memory increases more and more as time passes and toDict()
is called more, I eventually end up using 400MB in under 10 mins.
Has anyone encountered this issue? and is there a solution?