简体   繁体   中英

Error: “unable to open database file” & “Too many open files”

I have checked many questions available on SO such as this & this , related to these errors but let me tell you my scenario.

I am loading images on a view & after clicking assets in collection view 18 times my code returns this error. I am not doing anything complex I am just adding the same asset which is been clicked on a view above that asset.

Information: I am creating assets & saving them in documents directory & fetching them from there only.

Below is my code where error is coming:

let data = try Data(contentsOf: URL(fileURLWithPath: (contentsOfFile: (userInfo[kPath] as! String))), options: .uncached)

I am trying to get imageData & then put it as image in image view but after few clicks the Try statement is returning following errors

"Too many open files"

I have also tried another way of loading image ie

UIImage(contentsOfFile: imageFilePath)!

but result is same.

Can anyone help me by guiding how to solve this error?

The code that you've shared with us is unlikely to be the source of the "too many files open" problem, but rather more likely just a symptom of another problem. Your other error, "unable to open database file" suggests a more likely culprit, eg you may be opening databases but not properly closing them, eventually ending up with too many files open.

I'd suggest carefully examining everywhere that you open files and double check that you're closing them properly. Especially if you're doing your own sqlite3 API calls, it's surprisingly easy to do this because files are not closed automatically. I would suggest adding logging statements everywhere you open and close files and make sure that every "open" is paired with a corresponding "close".

If the opening and closing of files is happening in Swift code where you have many if or guard statements, often putting the "close" in a defer statement is a nice way of ensuring the close is called regardless of the path of execution.


As an aside and unrelated to this file opening problem, the reference to contentsOfFile in your code snippet is misleading/unnecessary. You can simplify that to:

let data = try Data(contentsOf: URL(fileURLWithPath: userInfo[kPath] as! String), options: .uncached)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM