Swift Lazy Variables that Load more than Once (Computed Properties?) - ios

I'm trying to translate some Objective-C code that was essentially lazy loading a variable multiple times. The code was similar to the following:
-(NSFetchedResultsController *)fetchedResultsController {
if (_fetchedResultsController != nil) {
return _fetchedResultsController;
}
//...code to build the fetchedResultsController with a new predicate
Whenever they wanted to rebuild the fetchedResultsController to use a new predicate, they would just set it to "nil" and call it, and it would rebuild it with a new predicate.
I'm struggling to do this same task in Swift. As far as I can tell, Swift lazy variables become normal variables after they are called for the first time. This is causing issues for me because if I try to set my swift variable back to nil, and recall it, it doesn't rebuild but remains nil.
The working code to load my fetchedResultsController as a lazy varaible is below. I've tried changing it to a computed property by adding a check if its nil and have it within a get block, but that hasn't worked. Any ideas?
lazy var taskController : NSFetchedResultsController? = {
var subtaskRequest = NSFetchRequest(entityName: "Subtasks")
var segIndex = self.segmentedControl.selectedSegmentIndex
subtaskRequest.predicate = NSPredicate(format: "task.category.name == %#", self.segmentedControl.titleForSegmentAtIndex(segIndex)!)
subtaskRequest.sortDescriptors = [NSSortDescriptor(key: "task.englishTitle", ascending: true), NSSortDescriptor(key: "sortOrder", ascending: true)]
let controller = NSFetchedResultsController(fetchRequest: subtaskRequest, managedObjectContext:
self.managedObjectContext!, sectionNameKeyPath: "task.englishTitle", cacheName: nil)
controller.delegate = self
return controller
}()

You can create something similar to the Objective-C method using a computed property backed by an optional variable.
var _fetchedResultsController: NSFetchedResultsController?
var fetchedResultsController: NSFetchedResultsController {
get {
if _fetchedResultsController != nil {
return _fetchedResultsController!
}
//create the fetched results controller...
return _fetchedResultsController!
}
}

lazy just implements a very specific memoization pattern. It's not as magical as you'd sometimes like it to be. You can implement your own pattern to match your ObjC code pretty easily.
Just make a second private optional property that holds the real value. Make a standard (non-lazy) computed property that checks the private property for nil and updates it if it's nil.
This is pretty much identical to the ObjC system. In ObjC you had two "things," one called _fetchedResultsController and the other called self.fetchedResultsController. In Swift you'll have two things, one called self.fetchedResultsController and the other called self._cachedFetchedResultsController (or whatever).

Related

SwiftUI: Filter Core Data fetch by relationship (NSPredicate)

#Environment(\.managedObjectContext) private var viewContext
#FetchRequest(
entity: ListStruct.entity(),
sortDescriptors: [NSSortDescriptor(keyPath: \ListStruct.name, ascending: true)],
predicate: NSPredicate(format: "parentfolder == %#", parentFolder),
animation: .default)
private var lists: FetchedResults<ListStruct>
var parentFolder: FolderStruct
There are two entities: FolderStruct and ListStruct. I made a tree structure with two entities. The view that I am using this code receives "var parentFolder: FolderStruct" as a parameter.
The relationship between FolderStruct and ListStruct is to-many, which means a folderStruct can hold many ListStructs. FolderStruct has a relationship named "childlists" which is to-many, and ListStruct has a relationship named "parentfolder" which is to-one.
When fetching ListStructs, I want to filter ListStructs whose parentfolder relationship is the parameter parentFolder. However, the code above makes an error that says "Cannot use instance member 'parentFolder' within property initializer; property initializers run before 'self' is available". How can I fix this problem?
You can supply the param you want to use in the fetch to the View's init as follows:
private var fetchRequest : FetchRequest<Item>
private var items: FetchedResults<Item> {
fetchRequest.wrappedValue
}
init(folder: Folder) {
fetchRequest = FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \Item.name, ascending: true)],
predicate: NSPredicate(format: "folder == %#", folder),
animation: .default)
}
Just so you know, due to a bug in FetchRequest, the body func will be called every time this View is init even if nothing has changed, so you may wish to wrap it in another View that takes the folder as a let for a layer of protection.
Another bug is if you "dynamically change the predicate or sort descriptors" like the documentation states, then when the View containing the #FetchRequest is re-init, those changes are lost.

Anonymous-ish classes (closure?) in Swift for NSFetchedResultsController

Some context:
I've been away from iOS programming for 5+ years and boy howdy have things changed. Just to make it more exciting, I'm trying Swift at the same time.
I'm trying to build a relatively simple iOS app using the Master-Detail App template and am at the point where I'm trying to add sections to the data. My (Core Data) data model is pretty simple at this point - some Locations (these are the sections) each of which contain some Containers. These are linked in the obvious way (a Location have a one-to-many reference to Containers, and Containers have a one-to-one reference to its Location).
I suspect that I'm heading to a place where I'm going to want the fetchedResultsController.object(at: indexPath) to return the Container corresponding with the indexPath but I'm also going to want the fetchedResultsController.sections[section] to return a Location.
The code
This is pretty much the code that comes from the app template (with minor modifications to use my Location type as the generic ResultType for NSFetchedResultsController - that might might be a mistake; maybe it should be a Container or even a NSManagedObject - we'll get to that in a minute).
var fetchedResultsController: NSFetchedResultsController<Location> {
if _fetchedResultsController != nil {
return _fetchedResultsController!
}
let fetchRequest: NSFetchRequest<Location> = Location.fetchRequest()
// Set the batch size to a suitable number.
fetchRequest.fetchBatchSize = 20
// Edit the sort key as appropriate.
let sortDescriptor = NSSortDescriptor(key: "name", ascending: false)
fetchRequest.sortDescriptors = [sortDescriptor]
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: nil, cacheName: "Master")
aFetchedResultsController.delegate = self
_fetchedResultsController = aFetchedResultsController
do {
try _fetchedResultsController!.performFetch()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
return _fetchedResultsController!
}
My questions
I'm new to Swift and I'm struggling to understand what the code that the Xcode template created for me. So I have a few questions:
What do we call this pattern? Anonymous classes (apparently not)? Closures? Knowing what it's called will help me do a better job of searching for related answers instead of wasting your time on these noob questions.
What is it actually defining? What I suspect it's doing is defining an implementation for init and returning an instance of NSFetchedResultsController that has all the default implementations. If that's not completely right, help me understand it a little better (pointing at something to read is also helpful).
How should I go about overriding methods of NSFetchedResultsController when using this pattern? Or is that something where I need to create a real subclass.
What type should I be using as the generic ResultType and why? This is a little off topic, but what the heck, maybe you'll take pity on me and bump me along another step of the journey.
It's basically called a computed property.
It checks if an instance of NSFetchedResultsController exists. If not it creates one and configures it.
There is nothing to override. However you should implement the delegate methods.
The generic type is correct. It avoids a lot of type casting.
I doubt this is the code which comes from the app template. The Swift equivalent of the objective-c-ish pattern with the instance variable and the nil-check is a lazy instantiated property. The body is called once the first time the property is accessed.
lazy var fetchedResultsController : NSFetchedResultsController<Location> = {
let fetchRequest: NSFetchRequest<Location> = Location.fetchRequest()
// Set the batch size to a suitable number.
fetchRequest.fetchBatchSize = 20
// Edit the sort key as appropriate.
let sortDescriptor = NSSortDescriptor(key: "name", ascending: false)
fetchRequest.sortDescriptors = [sortDescriptor]
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
let controller = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: nil, cacheName: "Master")
controller.delegate = self
do {
try controller.performFetch()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
return controller
}()
To add sections you have to specify the sectionNameKeyPath parameter and add an appropriate second sort descriptor.
The table view data source methods should look like
func numberOfSections(in tableView: UITableView) -> Int {
return self.fetchedResultsController.sections?.count ?? 0
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.fetchedResultsController.sections?[section].numberOfObjects ?? 0
}

Recursive fetch in CoreData

I have a data structure simplified to this:
So a folder can contain multiple folders or snippets and each snippet is part of a folder.
I want to fetch all Snippets which are in a given folder or which are in a folder which is a children of a specific folder.
The first case works for me, but I have problems getting the second case right.
To make this more clear here is an example:
When I select Folder C I'd like to get Snippet 3 but when I select Folder B or Folder A I'd like to get Snippet 1, Snippet 2 and Snippet 3.
This is what I currently have:
class Store {
...
func snippetsFetchRequest() -> NSFetchRequest<Snippet> {
let fetch: NSFetchRequest<Snippet> = Snippet.fetchRequest()
fetch.returnsObjectsAsFaults = false
fetch.relationshipKeyPathsForPrefetching = ["folder", "tags"]
fetch.sortDescriptors = [NSSortDescriptor(key: "updateDate", ascending: false)]
return fetch
}
...
}
let context = PersistenceManager.shared.mainContext
let store = SnippetStore(context: context)
fetchedResultsController = NSFetchedResultsController(fetchRequest: store.snippetsFetchRequest(),
managedObjectContext: context,
sectionNameKeyPath: nil,
cacheName: nil)
fetchedResultsController.fetchRequest.predicate = NSPredicate(format: "folder == %#", selectedFolder)
do {
try fetchedResultsController.performFetch()
} catch {
...
}
But this does only fetch the snippets which are direct children of the given/selected folder.
Is there any way I can solve my problem by still using NSFetchedResultsController?
You data structor is wrong. People tend to think about data structor as have a "correct" form for the given information; that you want to "model" the reality as close as possible. This is false. Your model only has value to the extent that it give you value for your particular application.
In this case, if you want to fetch all decedents of a folder it would be best to make a relationship to represent that. You can make a many-to-many relationship of decedents and ancestors that you can set whenever you add an object. If you need more properties for filtering or ordering you should add them, even if those properties can in theory be derived from the current tree model. Just make sure to keep them all in sync.

Creating a Key Path from a computed var in Swift 4

I have a fetchedResultsController where I'd like to add a keypath for Date so I don't have a section for every second of the day. Simple enough, I thought...I'll create an extension for MyEntity
extension MyEntity {
var dateForSection: String {
get {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .long
if let time = self.time {
return dateFormatter.string(from: time)
}
return "Unavailable Date"
}
}
}
Then, on MyViewController in the fetchedResultsController lazy var declaration, I declare the frc as follows:
let frc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedObjectContext, sectionNameKeyPath: #keyPath(MyEntity.dateForSection), cacheName: nil)
I get this compiler error:
Argument of '#keyPath' refers to non-'#objc' property 'dateForSection'
In Googling the issue saw some Swift bug reports from 2016, but I haven't seen any solutions to this. How would I get around this?
Addendum
I've tried adding #objc in front of the var declaration. I've also tried adding #objc dynamic, closing Xcode, nuking derived data from the command line, rebooting Xcode, rebooting my machine, etc.
I can't reproduce the problem. I whipped out a Core Data project with a Group class auto-generated from my entity, and added a computed variable:
extension Group {
#objc var yoho : String {
return "yoho"
}
}
Then I modified that same line in my lazy fetched results controller initializer:
let frc = NSFetchedResultsController(
fetchRequest:req,
managedObjectContext:self.managedObjectContext,
sectionNameKeyPath:#keyPath(Group.yoho), cacheName:nil)
It compiles. I don't know why yours doesn't.
On the other hand, a #keyPath is nothing but a string generated for you, and what's expected here is a string, so if you really can't get it to compile, just put "dateForSection" and be done with it. Of course that doesn't mean it will run without crashing, but at least it will compile and you can move on.

Sorting NSFetchedResultsController by Swift Computed Property on NSManagedObjectSubclass

I'm building an app using Swift with Core Data. At one point in my app, I want to have a UITableView show all the objects of a type currently in the Persistent Store. Currently, I'm retrieving them and showing them in the table view using an NSFetchedResultsController. I want the table view to be sorted by a computed property of my NSManagedObject subclass, which looks like this:
class MHClub: NSManagedObject{
#NSManaged var name: String
#NSManaged var shots: NSSet
var averageDistance: Int{
get{
if shots.count > 0{
var total = 0
for shot in shots{
total += (shot as! MHShot).distance.integerValue
}
return total / shots.count
}
else{
return 0
}
}
}
In my table view controller, I am setting up my NSFetchedResultsController's fetchRequest as follows:
let request = NSFetchRequest(entityName: "MHClub")
request.sortDescriptors = [NSSortDescriptor(key: "averageDistance", ascending: true), NSSortDescriptor(key: "name", ascending: true)]
Setting it up like this causes my app to crash with the following message in the log:
'NSInvalidArgumentException', reason: 'keypath averageDistance not found in entity <NSSQLEntity MHClub id=1>'
When I take out the first sort descriptor, my app runs just fine, but my table view isn't sorted exactly how I want it to be. How can I sort my table view based on a computed property of an NSManagedObject subclass in Swift?
As was pointed out by Martin, you cannot sort on a computed property. Just update a new stored property of the club every time a shot is taken.

Resources