1

I am reading a file from disk on Mac. The following code in a function keeps making memory usage go up. I don't have any variable to reference the "content", just test to read it in and think the system will release it after the function exit. but it does not. System actually only releases the memory when the for-loop is done.

My question is, how to let system to release the "content" object after the read function exits? I even delay 10s after the function call in the loop.

import Cocoa

class ViewController: NSViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }

    @IBAction func onRead(_ sender: NSButton) {
        
        for n in 0..<100
        {
            readFile()
            sleep(10)//not enough time for system to recycle the memory??
        }
    }
    
    func readFile()
    {

       print ("test read file")
       let content = FileManager.default.contents(atPath: "/Users/swiftuser/Documents/testfile.txt")
                        
    }
    
}
Asif Mujtaba
  • 447
  • 6
  • 17
whataday
  • 47
  • 3
  • You won't make a case with just three lines of code. – El Tomato Jul 10 '20 at 06:45
  • Ok, this is the function, if I call it 100 times, the memory usage goes up and never come down. Should the system release the record and content after function exit? (the code cannot be formatted, sorry) – whataday Jul 10 '20 at 06:58
  • Show the entire class where you read the function 100 times. Or try reading it 125 times, and your application will probably crash. – El Tomato Jul 10 '20 at 07:02
  • see the code above, the function is called 100 times in a button click handler. the memory is not recycled until the for-loop is done. After each call, I delay 10s to let system recycle the memory, but it does not recycle. Is there a way to force the system to recycle? – whataday Jul 10 '20 at 07:57
  • 1
    Try using `autoreleasepool`. – El Tomato Jul 10 '20 at 08:17
  • Does this answer your question? [Is it necessary to use autoreleasepool in a Swift program?](https://stackoverflow.com/questions/25860942/is-it-necessary-to-use-autoreleasepool-in-a-swift-program) – Willeke Jul 10 '20 at 09:26

0 Answers0