Sandeep Bhandari Sandeep Bhandari - 3 months ago 8
iOS Question

How to access instance variable inside lazy variable declaration swift

I am new to Swift and was trying to understand lazy variable. I have working experience on Objective-C but swift is driving me crazy.

I have core data model. Where

Person
----holds---->
Account
and
Account
----belongsTo-->
Person
.
holds
and
belongsTo
are the relationship.

Person
list will be displayed and on tapping person all the account associated with him should be listed in TableView. I am using
NSFetchedResultsController
because account might get added on the fly and I want to reflect the changes immediately using
NSFetchedResultsController
delegate.

Now I have passed tapped person object to my class.

class DetailViewController : ViewController{
var foundPerson : Person?

lazy var accountFetchedResultsController : NSFetchedResultsController = {

let fetchRequest = NSFetchRequest(entityName: "AccountInfo")
fetchRequest.predicate = NSPredicate(format: "belongsTo = %@", foundPerson!)
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "accountnumber", ascending: true)]
let appdelegate = UIApplication.sharedApplication().delegate as? AppDelegate
var fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: appdelegate!.managedObjectContext, sectionNameKeyPath: nil, cacheName: nil)
return fetchedResultsController
}()

//other view controller methods
}


When I try to compile this it gives error saying that


"Instance member foundPerson can not be used on type
DetailViewController"


I could not understand much from that error. What exactly is it trying to convey ?? Whats the mistake ?? Thanks in advance

Answer

Try adding self before foundPerson

        fetchRequest.predicate = NSPredicate(format: "belongsTo = %@", self.foundPerson!)