类型的值'(类) - > () - > (类)'没有成员'变量'

时间:2018-05-02 12:09:55

标签: ios swift xcode compiler-errors nsfetchedresultscontroller

let fetchedResultsController: NSFetchedResultsController = { () -> NSFetchedResultsController<NSFetchRequestResult> in
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Message")
    fetchRequest.sortDescriptors = [NSSortDescriptor(key: "date", ascending: true)]
    fetchRequest.predicate = NSPredicate(format: "friend.name = %@", self.friend!.name!)
    let delegate = UIApplication.shared.delegate as! AppDelegate
    let context = delegate.persistentContainer.viewContext
    let frc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
    return frc
}()

在说明的行fetchRequest.predicate = NSPredicate(format: "friend.name = %@", self.friend!.name!)我收到错误:Value of type '(ChatLogController) -> () -> (ChatLogController)' has no member 'friend'显然,由于某种原因,我的班级friend中找不到ChatLogController,或者我是错误?这就是我猜的,因为它不会friend成为self的成员。

以下是friend变量,它位于ChatLogController类:

之内
var friend: Friend?
{
    didSet
    {
        navigationItem.title = friend?.name

        messages = friend?.messages?.allObjects as? [Message]

        messages = messages?.sorted(by: {$0.date!.compare($1.date! as Date) == .orderedAscending})
    }
}

任何人都知道我为什么会收到此错误以及如何解决?

修改:我注意到如果我从第一个代码段的第一行删除() -> NSFetchedResultsController<NSFetchRequestResult> in,则错误消失,但是我收到此错误:Unable to infer complex closure return type; add explicit type to disambiguate < / p>

1 个答案:

答案 0 :(得分:1)

您已声明friend为optional属性,该属性在fetchedResultsController的initialisation时尚未初始化,这是一个常数,因此它会给出错误。要解决此问题,您可以使用lazy initialisation,这意味着

  

延迟创建对象或其他一些昂贵的进程   直到它需要

使fetchedResultsController属性变为惰性,这将延迟对象的创建,直到其所需的

lazy var fetchedResultsController: NSFetchedResultsController = { [unowned self] () -> NSFetchedResultsController<NSFetchRequestResult> in
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Message")
    fetchRequest.sortDescriptors = [NSSortDescriptor(key: "date", ascending: true)]
    fetchRequest.predicate = NSPredicate(format: "friend.name = %@", self.friend!.name!)
    let delegate = UIApplication.shared.delegate as! AppDelegate
    let context = delegate.persistentContainer.viewContext
    let frc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
    return frc
}()