NSPredicateEditor with Core Data relationship - swift

I have a core data data model with two entities, Document and Field:
Document:
fields [to many relationship]
Field:
name
fieldText
fieldDate
fieldNumber
document [to one relationship]
I am trying to set up an NSPredicateEditor to allow someone to filter documents based on the content of certain fields. I manually build the predicate editor like so:
func updatePredicateEditor() {
print("updatePredicateEditor")
let sortDescriptor = NSSortDescriptor(key: "orderIndex", ascending: true)
fieldsArrayController.sortDescriptors = [sortDescriptor]
let fields = fieldsArrayController.arrangedObjects as! [Field]
var keyPathsStringArray = [NSExpression]()
var stringFieldNames = [String]()
var keyPathsDateArray = [NSExpression]()
var dateFieldNames = [String]()
var keyPathsNumberArray = [NSExpression]()
var numberFieldNames = [String]()
for i in 0..<fields.count {
let currentField = fields[i]
switch currentField.type! {
case "Text":
keyPathsStringArray.append(NSExpression(forKeyPath: "fieldText"))
stringFieldNames.append(currentField.name!)
case "Date":
keyPathsDateArray.append(NSExpression(forKeyPath: "fieldDate"))
dateFieldNames.append(currentField.name!)
case "Number":
keyPathsNumberArray.append(NSExpression(forKeyPath: "fieldNumber"))
numberFieldNames.append(currentField.name!)
default:
print("error on field type")
}
}
let stringOperators = [NSNumber(unsignedInteger: NSPredicateOperatorType.ContainsPredicateOperatorType.rawValue),
NSNumber(unsignedInteger: NSPredicateOperatorType.EqualToPredicateOperatorType.rawValue),
NSNumber(unsignedInteger: NSPredicateOperatorType.NotEqualToPredicateOperatorType.rawValue),
NSNumber(unsignedInteger: NSPredicateOperatorType.BeginsWithPredicateOperatorType.rawValue),
NSNumber(unsignedInteger: NSPredicateOperatorType.EndsWithPredicateOperatorType.rawValue)]
let numberOperators = [NSNumber(unsignedInteger: NSPredicateOperatorType.EqualToPredicateOperatorType.rawValue),
NSNumber(unsignedInteger: NSPredicateOperatorType.NotEqualToPredicateOperatorType.rawValue),
NSNumber(unsignedInteger: NSPredicateOperatorType.LessThanPredicateOperatorType.rawValue),
NSNumber(unsignedInteger: NSPredicateOperatorType.LessThanOrEqualToPredicateOperatorType.rawValue),
NSNumber(unsignedInteger: NSPredicateOperatorType.GreaterThanPredicateOperatorType.rawValue),
NSNumber(unsignedInteger: NSPredicateOperatorType.GreaterThanOrEqualToPredicateOperatorType.rawValue)]
let dateOperators = [NSNumber(unsignedInteger: NSPredicateOperatorType.EqualToPredicateOperatorType.rawValue),
NSNumber(unsignedInteger: NSPredicateOperatorType.NotEqualToPredicateOperatorType.rawValue),
NSNumber(unsignedInteger: NSPredicateOperatorType.LessThanPredicateOperatorType.rawValue),
NSNumber(unsignedInteger: NSPredicateOperatorType.LessThanOrEqualToPredicateOperatorType.rawValue),
NSNumber(unsignedInteger: NSPredicateOperatorType.GreaterThanPredicateOperatorType.rawValue),
NSNumber(unsignedInteger: NSPredicateOperatorType.GreaterThanOrEqualToPredicateOperatorType.rawValue)]
var rowTemplatesTemp = [NSPredicateEditorRowTemplate]() // this is a temp array to hold the different popupbuttons
// add a template for Strings
let leftExpressionStringButton : NSPopUpButton
if keyPathsStringArray.count == 0 {
print("There aren't any text fields in NSPredicateEditor")
}
else {
let stringTemplate = NSPredicateEditorRowTemplate(leftExpressions: keyPathsStringArray,
rightExpressionAttributeType: NSAttributeType.StringAttributeType,
modifier: NSComparisonPredicateModifier.DirectPredicateModifier,
operators: stringOperators,
options: (Int(NSComparisonPredicateOptions.CaseInsensitivePredicateOption.rawValue) |
Int(NSComparisonPredicateOptions.DiacriticInsensitivePredicateOption.rawValue)))
leftExpressionStringButton = stringTemplate.templateViews[0] as! NSPopUpButton
let stringButtonArray = leftExpressionStringButton.itemTitles
for i in 0..<stringButtonArray.count {
(leftExpressionStringButton.itemAtIndex(i)! as NSMenuItem).title = stringFieldNames[i] // set button menu names
}
rowTemplatesTemp.append(stringTemplate)
}
// add another template for Numbers...
let leftExpressionNumberButton : NSPopUpButton
if keyPathsNumberArray.count == 0 {
print("There aren't any number fields in NSPredicateEditor")
}
else {
let numberTemplate = NSPredicateEditorRowTemplate(leftExpressions: keyPathsNumberArray,
rightExpressionAttributeType: NSAttributeType.Integer32AttributeType,
modifier: NSComparisonPredicateModifier.DirectPredicateModifier,
operators: numberOperators,
options: 0)
leftExpressionNumberButton = numberTemplate.templateViews[0] as! NSPopUpButton
let numberButtonArray = leftExpressionNumberButton.itemTitles
for i in 0..<numberButtonArray.count {
(leftExpressionNumberButton.itemAtIndex(i)! as NSMenuItem).title = numberFieldNames[i] // set button menu names
}
rowTemplatesTemp.append(numberTemplate)
}
// add another template for Dates...
let leftExpressionDateButton : NSPopUpButton
if keyPathsDateArray.count == 0 {
print("There aren't any date fields in NSPredicateEditor")
}
else {
let dateTemplate = NSPredicateEditorRowTemplate(leftExpressions: keyPathsDateArray,
rightExpressionAttributeType: NSAttributeType.DateAttributeType,
modifier: NSComparisonPredicateModifier.DirectPredicateModifier,
operators: dateOperators,
options: 0)
leftExpressionDateButton = dateTemplate.templateViews[0] as! NSPopUpButton
let dateButtonArray = leftExpressionDateButton.itemTitles
for i in 0..<dateButtonArray.count {
(leftExpressionDateButton.itemAtIndex(i)! as NSMenuItem).title = dateFieldNames[i] // set button menu names
}
rowTemplatesTemp.append(dateTemplate)
}
// create the any, all or none thing...
let compoundTypes = [NSNumber.init(unsignedInteger: NSCompoundPredicateType.OrPredicateType.rawValue),
NSNumber.init(unsignedInteger: NSCompoundPredicateType.AndPredicateType.rawValue),
NSNumber.init(unsignedInteger: NSCompoundPredicateType.NotPredicateType.rawValue)]
// add the compoundtypes
let compoundTemplate = NSPredicateEditorRowTemplate(compoundTypes: compoundTypes)
rowTemplatesTemp.append(compoundTemplate)
print("setting row templates \(rowTemplatesTemp)")
predicateEditor.rowTemplates = rowTemplatesTemp
predicateEditor.addRow(self)
}
The problem is that NSPredicateEditor does not allow NSExpressions with NSSubqueryExpressionType, so I can't have a subquery as my left expression. I need the NSPredicateEditorRowTemplate to include both the field name as well as the attribute path (fieldText, fieldDate or fieldNumber), so that the final predicate from one row would look like:
name == FIELDNAME && fieldText CONTAINS "<entered text>"
Any suggestions for how to do this? Should I be subclassing NSPredicateEditorRowTemplate, and if so how? Thanks in advance for any help.

Subclass NSPredicateEditorRowTemplate and override predicateWithSubpredicates to convert predicate "FIELDNAME CONTAINS <entered text>" to predicate "name == FIELDNAME && fieldText CONTAINS <entered text>".

Related

Swift - FetchRequest and filter results to display in list from CoreData

I am trying to create a fetch request that pulls data from CoreData, groups it by a id and then puts it into a list. I also want this to be dynamic, new list items can be added at any time while in this view. I have grinder my gears on this for hours and cannot figure out how to make this work dynamically. With my most recent attempt I am just getting initializing errors which I commented into the code. I am so stuck on this and would really appreciate some help. Also I am a total noob at swift so I am sorry if this is illiterate, Thanks
import CoreData
import SwiftUI
struct FilteredList: View {
#Environment(\.managedObjectContext) var moc
#FetchRequest var fetchRequest: FetchedResults<Workout>
var filter: String
var collectedWorkout: [Int64 : [Workout]] = [:]
var uniqueWorkout: [Int64] = []
init(filterIn: String) {
filter = filterIn
//_fetchRequest = FetchRequest<Workout>(sortDescriptors: [SortDescriptor(\.order, order: .reverse)], predicate: NSPredicate(format: "type = %#", filterIn))
// _outerRequest = FetchRequest<Workout>(sortDescriptors: [SortDescriptor(\.order, order: .reverse)], predicate: NSPredicate(format: "new"))
let FR: NSFetchRequest<Workout> = Workout.fetchRequest()
let predicate = NSPredicate(format: "type = %#", filterIn)
var result: [Workout] = []
FR.sortDescriptors = [NSSortDescriptor(keyPath: \Workout.order, ascending: false)]
FR.predicate = predicate
do {
let wOuts: [Workout]
wOuts = try moc.fetch(FR) // <- Varialbe 'self.fetchRequest' used before being initialized
for wOut in wOuts {
print(wOut.last)
result = wOuts
}
} catch{
print("Unable to fetch")
result = []
}
// Then you can use your properties.
let unsortDict = Dictionary(grouping: result, by: { $0.workoutId })
uniqueWorkout = unsortDict.map({ $0.key }).sorted()
} // <- Return from initializer without initializing all stored properties

How to get an array from Firestore document on Swift 5?

Please help me understand the logic reading data from the Firestore document, if one of the values is an array. I tried other answers here and sources but never came to a simple working way and understand clearly. Firestore document structure — example. And Swift class targets for saving (conditional):
struct MyStruct {
var name: String
var pages: Int
}
let part1 = [MyStruct]()
let name1 = ""
let pages1 = 0
let part2 = [MyStruct]()
let name2 = ""
let pages2 = 0
func readFirestore() { }
What should the document reader function look like to add data to existing targets in the class? Thanks in advance for any help in improving my understanding!
They helped to deal with familiar, thank you for what they are. As expected, everything is simple. But for the beginner there is nothing more difficult than simplicity 😁
func readFirestore() {
self.db.collection("example").document("book").getDocument { (document, error) in
if error == nil {
if document != nil && document!.exists {
//get all document data
guard let documentData = document!.data() else {return}
//get value-array for key "part1"
let element = documentData["part1"] as? [Any] //print -> Optional([name1, 100])
//get first element in array
guard let nameDB = element?[0] as? String else {return} //print -> name1
guard let pagesDB = element?[1] as? String else {return} //print -> 100
//append in class
part1.append(MyStruct(name: nameDB, pages: pagesDB))
name1 = nameDB
pages1 = pagesDB
}
}
}
}

Filter an (Codable) array by another array

I'm trying to filter my json data by IDs (trying mark some favourites and filter using it)
struct workoutList : Codable {
let id : Int
let title : String
let tag : String
}
func selectedWorkoutGroup(libraryFilter: Int, jsonErgWorkouts:[workoutList], workoutGroupBox: UITextField) -> [workoutList] {
var selectedGroup = [workoutList]()
let workoutFav = [1,10,100]
if libraryFilter == 0 {
// This works because I'm filtering based on 1 specific item
selectedGroup = jsonErgWorkouts.filter { $0.tag == workoutGroupBox.text }
} else if libraryFilter == 1 {
// Here I want to filter and show only the favorites
selectedGroup = jsonErgWorkouts.filter { $0.id } //
print("selectedGroup:\(selectedGroup)")
}
return selectedGroup
}
in the above code, the filter works when I have 1(one) something specific item to filter and then I get the entire json array with that tag.
Now I want to implement a favorite list, where the user selects for example ID == [1, 10 ,100] as their favourite.
How can I use the filter command to do it? I tried a few things and searched through SO (but doesn't work). Most of the answers are based on filtering based on specific items eg:
selectedGroup = jsonErgWorkouts.filter { workoutFav?.contains($0.id) }
edit: (omitted that I am using/storing the favourites in userDefaults. This code gives the error of "type of expression is ambiguous without more context"
func selectedWorkoutGroup(libraryFilter: Int, jsonErgWorkouts:[workoutList], workoutGroupBox: UITextField) -> [workoutList] {
var selectedGroup = [workoutList]()
UserDefaults.standard.set([1,10,100], forKey: "workoutFavorite")
/// This one gets stored as [Any] so I cast it to [Int]
let workoutFav = UserDefaults.standard.array(forKey: "workoutFavorite") as? [Int]
if libraryFilter == 0 {
// This works because I'm filtering based on 1 specific item
selectedGroup = jsonErgWorkouts.filter { $0.tag == workoutGroupBox.text }
} else if libraryFilter == 1 {
selectedGroup = workoutFav.flatMap { favouriteId in // for each favourite ID
jsonErgWorkouts.filter { $0.id == favouriteId } // This returns Error "type of expression is ambiguous without more context"
} // flatMap joins all those arrays returns by "filter" together, no need to do anything else
print("selectedGroup:\(selectedGroup)")
}
return selectedGroup
}
Final Solution:
Changing from This
let workoutFav = UserDefaults.standard.array(forKey: "workoutFavorite") as? [Int]
to This (notice the as! instead of as?)
let workoutFav = UserDefaults.standard.array(forKey: "workoutFavorite") as! [Int]
works using #sweeper's answer. Thanks
Update:
Figured out why this error occurred "type of expression is ambiguous without more context" when casting the output of UserDefaults as? [Int] and had to use as! [Int]
But using as! [Int] force unwrapping it causes app to crash if the user did not have any favorites saved into the UserDefault. (Which I then had to code around) like below
var workoutFav = [Int]()
if !(UserDefaults.standard.array(forKey: "workoutFavorite") == nil) {
workoutFav = UserDefaults.standard.array(forKey: "workoutFavorite") as! [Int]
}
Which was then simplified and removed the force unwrapping based on this SO https://stackoverflow.com/a/37357869/14414215 to become this one-line
let workoutFav = UserDefaults.standard.array(forKey: "workoutFavorite") as? [Int] ?? [Int]()
You need to do that filter for each id in the favourites array. You get an array of arrays as a result. To get the final array, you need to join those arrays to a single array. This "map each thing to an array and join the arrays" operation is what a flatMap does:
workoutFav.flatMap { favouriteId in // for each favourite ID
jsonErgWorkouts.filter { $0.id == favouriteId } // find workouts that match the ID
} // flatMap joins all those arrays returns by "filter" together, no need to do anything else
First thing first please give a struct name with a capital so you can distinguish between instance of it. Second you need to have new array where you will store each favorite, and store permanently that array, core data or some base on server, form there you will fetch favorites.
The better way is to add property like isFavorite: Bool that is false by default, and if user change it you can set it to be true, in that way you can avoid using ids for that and you can store whole workout's in one array to core data or base that you use, after that you can fetch from there with
let favorites = workouts.compactMap { $0.isFavorite == true }
Here you go in that way, but just to mention it highly recommended that you store those type of data outside User defaults.
struct Fav {
let name: String
let id: String
}
let df = UserDefaults.standard
let jk = ["aaa", "bbb", "cccc"]
df.setValue(jk, forKey: "favorites")
let fav1 = Fav(name: "zzz", id: "aaa")
let fav2 = Fav(name: "bbb", id: "qqq")
let favs = [fav1, fav2]
let favIDs = df.value(forKey: "favorites") as? [String]
favIDs?.forEach({ (id) in
let f = favs.filter({$0.id == id}) // here it is
})

Sum the Values of Nested Custom Objects in Swift

I am trying to add up the values found within some custom objects in Swift. I have the follow code working in a Playground:
//Custom Object
class EntryPack: NSObject{
var date: String!
var duration: Double!
var customValues:[CustomValuePack] = [] //Nested array of objects declared below
}
//Another object to nest in the above
class CustomValuePack: NSObject{
var name:String!
var value: Double!
}
//Instantiate nested objects
let cv1 = CustomValuePack()
cv1.name = "Day"
cv1.value = 1.2
let cv2 = CustomValuePack()
cv2.name = "Day"
cv2.value = 1.3
let cv3 = CustomValuePack()
cv2.name = "Night"
cv2.value = 2.2
//Instantiate parent objects
let entry1 = EntryPack()
entry1.date = "bingo"
entry1.duration = 1.1
entry1.customValues = [cv1, cv2]
let entry2 = EntryPack()
entry2.date = "bingo"
entry2.duration = 2.2
let entry3 = EntryPack()
entry3.date = "dang"
entry3.duration = 3.0
//Throw it all together into an array
var package = [entry1, entry2, entry3]
//Predicate for some filtering
let predicate = NSPredicate(format:"date = %#", "bingo")
let results = (package as NSArray).filteredArrayUsingPredicate(predicate) as! [EntryPack]
//Sum all the parent object durations
let sum = results.reduce(0.0) { $0 + $1.duration }
print(sum) // = 3.3
But now I want to add up the value for each CustomValuePack where the name is "Day".
I can't figure out how to do a similar reduce on a nested array of objects. I've tried something like this, but it yields a syntax error:
let sum2 = results.reduce(0.0) { $0.customValues + $1.customValues.value } //Error
How do I sum the value in a nested array of objects? I eventually want to apply an NSPredicate to filter by name = Day as well, but I'm not that far yet.
Given entries defined as follow
let entries = [entry1, entry2, entry3]
you can extract the CustomValues with name == "Day" and sum the value field with this code
let sum = entries
.flatMap { $0.customValues }
.filter { $0.name == "Day" }
.map { $0.value }
.reduce(0, combine: +)
Improvements
You are using Swift but for some reason there still is a lot of Objective-C into your code.
This is how i would refactor your code
struct EntryPack {
let date: String
let duration: Double
let customValues:[CustomValuePack]
}
struct CustomValuePack {
let name:String
let value: Double
}
let cv1 = CustomValuePack(name: "Day", value: 1.2)
let cv2 = CustomValuePack(name: "Day", value: 1.3)
let cv3 = CustomValuePack(name: "Night", value: 2.2)
let entry1 = EntryPack(date: "bingo", duration: 1.1, customValues: [cv1, cv2])
let entry2 = EntryPack(date: "bingo", duration: 2.2, customValues: [])
let entry3 = EntryPack(date: "dang", duration: 3.0, customValues: [])
Please note that now EntryPack and CustomValuePack are structs which are value types.

Why Realm "to many" relationship having always the same reference?

Why is the realm-list containing the very same elements instead of different ones ?
As you can see in the picture below, there are two relam-objects (UndoMemoryNameEntry and NameEntry). The first one contains a list of 8 elements. The list's element-type is of type NameEntry !
My last NameEntry object is written with currentScorePlayer=1 and currentScoreMe=15 as you can see in the picture below:
The list in UndoMemoryNameEntry is correctly inserted the last NameEntry object. You find the insertion-code further down...
But now the problem: Why are all the existing list-elements as well changed to the newest inserted element ???? As you can see in the picture below, all the elements are unfortunately identical to the last one added - why ??????
If I change the NameEntry to the following :
And inserting at index=0 to the list, then the List changes to :
Why are all the elments changed ? And not just the inserted one ??? Thanks for any help on this !
My two realm-objects are :
class NameEntry: Object {
dynamic var playerName = ""
dynamic var isMyAdversary: Bool = false
dynamic var currentScorePlayer: Int = 0
dynamic var currentScoreMe: Int = 0
}
and the List :
class UndoMemoryNameEntry: Object {
dynamic var undoPlayerName = ""
let NameEntryList = List<NameEntry>()
}
The following code creates the Realm-List :
// query rlm for existing object (with name adversary
let undoPredicate = NSPredicate(format: "undoPlayerName == %#", adversaryName)
let undoPlayerName = rlm.objects(UndoMemoryNameEntry).sorted("undoPlayerName", ascending: true).filter(undoPredicate)
// if undoPlayerName object does not exist - then create it!
if (undoPlayerName.count < 1) {
rlm.beginWrite()
let undoEntry = UndoMemoryNameEntry()
undoEntry.undoPlayerName = adversaryName
rlm.add(undoEntry)
rlm.commitWrite()
}
The following code adds a "NameEntry"-Element in the List :
let undoPredicate = NSPredicate(format: "undoPlayerName == %#", plaNameLab)
let undoPlayerName = rlm.objects(UndoMemoryNameEntry).sorted("undoPlayerName", ascending: true).filter(undoPredicate)
if (undoPlayerName.count == 1) {
rlm.beginWrite()
println(entry)
var undoEntry = undoPlayerName[0] as UndoMemoryNameEntry
undoEntry.NameEntryList.insert(entry, atIndex: 0)
rlm.commitWrite()
}
The above code-excerts work perfectly - except that the realm-List always changes all its elements to the one just inserted.
I finally found a solution:
First of all rearrange the two realm objects as follows:
class NameEntry: Object {
dynamic var playerName = ""
dynamic var currentScorePlayer: Int = 0
dynamic var currentScoreMe: Int = 0
// the undo-list is better placed in the first object...
let undoEntryList = List<UndoMemoryNameEntry>()
override static func primaryKey() -> String? {
return "playerName"
}
}
class UndoMemoryNameEntry: Object {
dynamic var undoPlayerName = ""
dynamic var currentScorePlayer: Int = 0
dynamic var currentScoreMe: Int = 0
// no primary key here since the undoEntry will have several items with the same undoPlayerName
}
Then when adding a "NameEntry"-Element in the List :
let predicate = NSPredicate(format: "playerName == %#", plaNameLab)
let playerName = rlm.objects(NameEntry).sorted("playerName", ascending: true).filter(predicate)
if (playerName.count == 1) {
rlm.beginWrite()
var entry = playerName[0] as NameEntry
// you need to create a new list object first !!!!!!!!!!!!
// ...in my initial example, this creation was missing !!!!!!
var siblingEntry = UndoMemoryNameEntry()
siblingEntry.undoPlayerName = plaNameLab
siblingEntry.currentScorePlayer = entry.currentScorePlayer
siblingEntry.currentScoreMe = entry.currentScoreMe
// insert new list-element
entry.undoEntryList.insert(siblingEntry, atIndex: 0)
// alternatively choose append if you want to add the element at the end of the list
entry.undoEntryList.append(siblingEntry)
// or choose the "ringbuffer-solution" given in the add-on below if you want to restrict the number of list-elements to ringbuffer-size !
// ...
rlm.commitWrite()
}
Add-on: If you want to create a ringbuffer having only a limited number of list-elements:
// create ringbuffer of 20 elements (20th element will be newest)
let ringBufferSize = 20
let undoPredicate = NSPredicate(format: "undoPlayerName == %#", plaNameLab)
if (entry.undoEntryList.filter(undoPredicate).sorted("undoPlayerName").count < ringBufferSize) {
entry.undoEntryList.append(siblingEntry)
}
else {
// entry.undoEntryList.replace(ringBufferSize-1, object: siblingEntry)
entry.undoEntryList.removeAtIndex(ringBufferSize-1)
entry.undoEntryList.append(siblingEntry)
for index in 0..<ringBufferSize-1 {
let tempEntry1 = rlm.objects(UndoMemoryNameEntry).filter(undoPredicate).sorted("undoPlayerName")[index] as UndoMemoryNameEntry
let tempEntry2 = rlm.objects(UndoMemoryNameEntry).filter(undoPredicate).sorted("undoPlayerName")[index+1] as UndoMemoryNameEntry
tempEntry1.currentScorePlayer = tempEntry2.currentScorePlayer
tempEntry1.currentScoreMe = tempEntry2.currentScoreMe
}
let tempEntry = rlm.objects(UndoMemoryNameEntry).filter(undoPredicate).sorted("undoPlayerName")[ringBufferSize-1] as UndoMemoryNameEntry
rlm.delete(tempEntry)
}