Thank you for your reply and the example of autorelease!
I realized that I was mistaken when I said that the problem was the lack of autoreleasepool. The problem was recursion, because those data type objects that I called temporary weren't really temporary. And until the recursion completes, the objects I initialized will not be released.
I have created a similar sample code. When I use the doWorkAsync function, the memory increases to 9.34 GB, and after the recursion is completed, the memory is about 30 MB. But when I use "while loop" (doWorkInLoop function), the objects are released correctly, and the amount of memory is about 30 MB throughout the execution of the entire code.
In my code, I just rewrote the recursion into a loop, and it helped me.
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
Task {
let worker = Worker()
do {
try await worker.doWorkAsync()
print("Done")
} catch {
print("catch")
}
}
}
}
class Worker {
var counter: Int = 0
func doWorkAsync() async throws {
guard counter < 10000 else {
return
}
var randomData = Data(count: 1024 * 1024)
let result = randomData.withUnsafeMutableBytes {
SecRandomCopyBytes(kSecRandomDefault, 1024 * 1024, $0.baseAddress!)
}
guard result == errSecSuccess else {
throw NSError(domain: "error in random", code: 1)
}
try await Task.sleep(nanoseconds: 100_000)
counter += 1
try await doWorkAsync()
}
func doWorkInLoop() async throws {
while true {
guard counter < 10000 else {
return
}
var randomData = Data(count: 1024 * 1024)
let result = randomData.withUnsafeMutableBytes {
SecRandomCopyBytes(kSecRandomDefault, 1024 * 1024, $0.baseAddress!)
}
guard result == errSecSuccess else {
throw NSError(domain: "error in random", code: 1)
}
try await Task.sleep(nanoseconds: 100_000)
counter += 1
}
}
}
Topic:
Programming Languages
SubTopic:
Swift
Tags: