slimboy
slimboy

Reputation: 1653

Coredata memory leak: Deinit does not get called.. causing memory leak

I am saving messages into coredata, and when I leave the controller it doesn't deinit. It's also causing a memory leak that gets bigger and bigger everytime I present a new controller with the function inside.

func saveMessagetoCoreData(text: String, timestamp: NSNumber, status: String, friend: Friend) {

    let moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
    let doubletimestamp = Double(timestamp)
    let date = NSDate(timeIntervalSinceReferenceDate: (doubletimestamp))

    createMessageWithText(text, friend: friend, context: moc, date: date, status: "...")
    do {
        try moc.save()
        //moc.reset()

    } catch let err {
        print(err)
    }


private func createMessageWithText(text: String, friend: Friend, context: NSManagedObjectContext, date: NSDate, isSender: Bool = false, status: String) -> Mesages {
    let message = NSEntityDescription.insertNewObjectForEntityForName("Mesages", inManagedObjectContext: context) as! Mesages

    message.user = friend
    message.text = text
    message.timestamp = date
    message.isSender = isSender
    message.status = status
    message.fromID = NSUserDefaults.standardUserDefaults().objectForKey("FBid") as! String
    friend.lastMessage = message

    return message

}

when the message is saved into coredata, if i dismiss the viewcontroller, it deinit does not get called anymore.

anyone have any idea to what's happening?

Upvotes: 1

Views: 377

Answers (1)

Michael
Michael

Reputation: 9044

Any memory leak is probably caused by a circular reference in your code. The following two lines look suspicious...

    message.user = friend
    ...
    friend.lastMessage = message

message.user points to friend, and friend.lastMessage points to message. As long as they're getting released you should be ok though. What is holding a reference to your view controller?

Upvotes: 2

Related Questions