Coredata内存泄漏:Deinit没有被调用..导致内存泄漏

时间:2016-09-06 06:05:00

标签: ios swift core-data memory-leaks nsfetchedresultscontroller

我将消息保存到coredata中,当我离开控制器时它不会消失。每当我提出一个内置功能的新控制器时,它也会导致内存泄漏变得越来越大。

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

}

当消息被保存到coredata中时,如果我解除了viewcontroller,它就不再被调用了。

任何人都知道发生了什么事?

1 个答案:

答案 0 :(得分:2)

任何内存泄漏都可能是由代码中的循环引用引起的。以下两行看起来很可疑......

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

message.user指向friendfriend.lastMessage指向message。只要他们被释放你就应该没问题。什么是对视图控制器的引用?