Server Side Swift 에서 Memory 해제가 안되어 무한 증가할 때 조치 법

몽고디비에 자료를 가져와서 가공을 한 뒤에 다시 몽고디비에 자료를 저장하는 프로그램을 서버용 스위프트로 작성하였다.
하지만 아래와 같이 작성했을 때는 실행을 하면 메모리 해제가 안되어 무한증식하는 상태가 발생되었다.

import Foundation
import MongoKitten

do {
    let mongo = try Server("mongodb://localhost:27017")
    let db = mongo["db"]
    if mongo.isConnected { print("connected successfully to server") }
    let collection = db["collection"]
    let docu: Document = []
    let query = Query(docu)
    var textLog = TextLog()
    do {
        for entity in try collection.find(query) {
            trainLocations.forEach {
                textLog.write("\($0.date.Format(into: "yyyy-MM-dd HH:mm:ss Z")) \n")
            }
        }  //end_for entity in try collection.find(query)
    } catch { print("error -> \(error.localizedDescription)") }
    try mongo.disconnect()
} catch { print("error -> \(error.localizedDescription)") }

이를 해결하기 위해 함수를 포인터를 사용하는 등 별짓을 다했지만 역시나 무한증식은 막을 수 없었다.
이리하여 찾은 해결방법은 이것이었다.
잊지 말자!!!
autorelease 구문이다.
import Foundation
import MongoKitten

do {
    let mongo = try Server("mongodb://localhost:27017")
    let db = mongo["db"]
    if mongo.isConnected { print("connected successfully to server") }
    let collection = db["collection"]
    let docu: Document = []
    let query = Query(docu)
    var textLog = TextLog()
    do {
        for entity in try collection.find(query) {
            autoreleasepool {
                trainLocations.forEach {
                    textLog.write("\($0.date.Format(into: "yyyy-MM-dd HH:mm:ss Z")) \n")
                }
           }
        }  //end_for entity in try collection.find(query)
    } catch { print("error -> \(error.localizedDescription)") }
    try mongo.disconnect()
} catch { print("error -> \(error.localizedDescription)") }
이 구문안에서 메모리 해제가 된다.

위 구문을 추가한 후 실행해보니 메모리 할당이 10메가를 넘지 않는다.

댓글

이 블로그의 인기 게시물

한글 2010 에서 Ctrl + F10 누르면 특수문자 안뜰 때

아이폰에서 RFID 사용하는 방법

VCC 와 GND 는 무엇일까?