I write an (Mac)App in Swift2 which should search a Realm database of Teachers with a sepcific subject. The Definition for the Teacher Object in realm looks like this:
class Teacher: Object {
var subjects = List<Subject>()
}
This class is very complex so I deleted some lines...
Here's the function that should filter the Database for Teachers with Specific subjects and give only the Teacher names back (as String Array: [String]):
func getAllTeacherNamesForSubject(subject: String) -> [String] {
// Open Database
let realm = openRealmDatabase()
// Or open it this way:
// RLMRealm.setDefaultRealmPath("/Users/name/Data.realm")
// var realm: Realm!
// realm = try! Realm()
// filter the Database with Predicate
let objects = realm.objects(Teacher).filter("!!! Need Help !!!", subject)
// How can I filter the Database? I want to get all the Teachers for that subject
// Make an Array of Objects
let objectsArray = objects.toArray(Teacher) as [Teacher]
// Return
return ???
}
// This is the toArray extension.
// You may need it to use the snippet above
extension Results {
func toArray<T>(ofType: T.Type) -> [T] {
var array = [T]()
for var i = 0; i < count; i++ {
if let result = self[i] as? T {
array.append(result)
}
}
return array
}
}
So the problem is that I don't know how to filter the Database.
Can someone help me please?
To filter objects that have relations with specific values, or in your case, teachers that have subjects with a specific name, you could use this predicate for a case-insensitive search:
NSPredicate(format: "ANY subjects.name ==[c] %#", subjectName)
and just plug that into the filter function. Since you want to return only the teacher names, you won't need to create any extensions as suggested, but rather use the native swift map method:
func getAllTeacherNamesForSubject(subjectName: String) -> [String] {
let realm = openRealmDatabase
let predicate = NSPredicate(format: "ANY subjects.name ==[c] %#", subjectName)
return realm.objects(Teacher).filter(predicate).map { $0.name }
}
For reference, you can find a great cheatsheet on Realm's website describing the complete list of supported predicate syntax.
Related
Im very new with CoreData fetching/display and so far able to save into CoreData from a JSON fetch.
The fetched data is an array of Airport info with only three items; airport_code, access_point and image_url.
I need to add two more values to each fetched item - a lat and lon coordinate which is stored in another CoreData entity with a matching airport_code item/attribute.
Can anyone provide some guidance as to how to create a separate function to query this other CoreData during the loop sequence by using the predicate value of the airport_code? I have attached the code I have so far:
func saveData(context: NSManagedObjectContext){
xArray.forEach { (data) in
let entity = Airports(context: context)
entity.airport_code = data.airport_code
entity.access_points = data.access_points
entity.image_url = data.image_url
entity.lat = getLat()
entity.lon = getLon()
}
do{
try context.save()
print("Success Saving to CoreData: \(xArray.count)")
}
catch{
print("Error Saving to CoreData \(error.localizedDescription)")
}
}
func getLat() -> String {
#FetchRequest(entity: AllAirports.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \AllAirports.airport_code, ascending: true)])
var results: FetchedResults<AllAirports>
//this is where Im lost as to how to query this CoreData to fetch the LON value when there is a match to the data.airport_code in the loop above.
return latResults
}
func getLon() -> String {
#FetchRequest(entity: AllAirports.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \AllAirports.airport_code, ascending: true)])
var results: FetchedResults<AllAirports>
//this is where Im lost as to how to query this CoreData to fetch the LON value when there is a match to the data.airport_code in the loop above.
return lonResults
}
func fetchData(context: NSManagedObjectContext) {
// this function performs a JSON parse and returns the xArray above
….
First you want to take a look at the response here What is the best way to do a fetch request in CoreData? to get an idea how a programmatic fetch request may look like.
As I understand your problem now, you want to write two methods getLat() and getLon() which are going to fetch the coordinates for an airport.
I would recommend to write a single function as shown below which looks up your airport in AllAirports using the given code and returns the tuple with the coordinates found.
func getCoord(airport_code: String) -> (lon: Double, lat: Double)? {
let request: NSFetchRequest<AllAirports> = AllAirports.fetchRequest()
request.predicate = NSPredicate(format: "airport_code == %#", airport_code)
if let result = try? viewContext.fetch(request) {
print("Found \(result.count) airports matching \(airport_code)")
// Just return the first matched airport
if let first = result.first {
return (first.longitude, first.latitude)
}
}
return nil
}
A better solution would be to add an extension to you AllAirports which returns an entry for a given (hopefully unique!) airport_code:
extension AllAirports {
static func airport(byCode airportCode: String, in context: NSManagedObjectContext) -> AllAirports? {
let request: NSFetchRequest<AllAirports> = fetchRequest()
request.predicate = NSPredicate(format: "airport_code == %#", airportCode)
if let result = try? context.fetch(request) {
return result.first
}
return nil
}
}
This could then be used in your code as follows:
func saveData(context: NSManagedObjectContext){
xArray.forEach { (data) in
let entity = Airports(context: context)
entity.airport_code = data.airport_code
entity.access_points = data.access_points
entity.image_url = data.image_url
if let airport = AllAirports.airport(byCode: data.airport_code, in: context) {
entity.lat = airport.latitude
entity.lon = airport.longitude
}
}
I'm trying to delete an entire record out of coreData. I've retrieved the data and placed it in an array for manipulation (I have another function that lets the user edit the data using this method and it works fine) But I can't figure out how to just delete the record. [.remove(at: index)] doesn't work and neither does the code below. I can set all the fields to empty but that's not what I want, I want the record gone completely.
I went through the solutions given for similar problems but to no avail
#IBAction func Delete(_ sender: UIButton) { // The delete function
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "DestinationsOne")
let context = appDelagate.persistentContainer.viewContext
var destArray = [DestinationsOne]() // The data array
do {
try destArray = context.fetch(request) as! [DestinationsOne]} //Fetching the data and placing it in the array
catch{
//error message
}
for index in (0..<destArray.count - 1){ //Go through the records
if destArray[index].destID == IDTitle!{ //Picks the record to edit
let object = destArray[index]
context.delete(object
}
appDelagate.saveContext()
}
I figured this one out. I'm posting the solution in case anyone else has the same question
func deleteRecords() -> Void { //The function to delete the record
let moc = getContext()
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "DestinationsOne")
let result = try? moc.fetch(fetchRequest)
let resultdata = result as! [DestinationsOne] // result as entity
for object in resultdata { // Go through the fetched result
if object.destID == self.IDTitle{ // If there is a match
moc.delete(object) // delete the object
}
}
do {
try moc.save() // Save the delete action
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
} catch {
}
}
func getContext () -> NSManagedObjectContext {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
return appDelegate.persistentContainer.viewContext
}
deleteRecords() // Call the function
Why not applying a predicate to search this particular record. It's much more efficient than looping through a huge list.
func deleteRecords() { //The function to delete the record
let moc = getContext()
let fetchRequest = NSFetchRequest<DestinationsOne>(entityName: "DestinationsOne")
let predicate = NSPredicate(format: "destID == %#", self.IDTitle)
fetchRequest.predicate = predicate
do {
let resultdata = try moc.fetch(fetchRequest) // no type cast needed
if let objectToDelete = resultdata.first {
moc.delete(objectToDelete) // delete the object
try moc.save() // Save the delete action
}
} catch {
print("Could not save error: ", error)
}
}
Here are some issues with your code:
viewContext should be treated as readonly - you should use performBackgroundTask for all changes to core-data
You are fetching ALL of the entities and then then going through each one to find the one you want to delete. It is a lot faster to have core-data only fetch the one you want. You can do this by setting a predicate to the fetch request.
Instead of displaying your records by doing a fetch and using the array as a model, it is better to use a NSFetchedResultsController to do the fetch and manage the results. The fetchedResultsController will keep the data in sync when objects are changed, inserted or deleted. It also has delegate methods that will inform you when there are changes so you can update your view.
remove appDelagate.saveContext from your project. Apple's template code is wrong. You should never be writing to the viewContext so you should never have a reason to save it.
where is IDTitle being set? are you sure it is not nil?
(minor) for index in (0..<destArray.count - 1){ can be replaced with for (index, element) in destArray.enumerated() { which is clearer to read.
In Swift 2 the following code was working:
let request = NSFetchRequest(entityName: String)
but in Swift 3 it gives error:
Generic parameter "ResultType" could not be inferred
because NSFetchRequest is now a generic type. In their documents they wrote this:
let request: NSFetchRequest<Animal> = Animal.fetchRequest
so if my result class is for example Level how should I request correctly?
Because this not working:
let request: NSFetchRequest<Level> = Level.fetchRequest
let request: NSFetchRequest<NSFetchRequestResult> = Level.fetchRequest()
or
let request: NSFetchRequest<Level> = Level.fetchRequest()
depending which version you want.
You have to specify the generic type because otherwise the method call is ambiguous.
The first version is defined for NSManagedObject, the second version is generated automatically for every object using an extension, e.g:
extension Level {
#nonobjc class func fetchRequest() -> NSFetchRequest<Level> {
return NSFetchRequest<Level>(entityName: "Level");
}
#NSManaged var timeStamp: NSDate?
}
The whole point is to remove the usage of String constants.
I think i got it working by doing this:
let request:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "Level")
at least it saves and loads data from DataBase.
But it feels like it is not a proper solution, but it works for now.
The simplest structure I found that works in 3.0 is as follows:
let request = NSFetchRequest<Country>(entityName: "Country")
where the data entity Type is Country.
When trying to create a Core Data BatchDeleteRequest, however, I found that this definition does not work and it seems that you'll need to go with the form:
let request: NSFetchRequest<NSFetchRequestResult> = Country.fetchRequest()
even though the ManagedObject and FetchRequestResult formats are supposed to be equivalent.
Here are some generic CoreData methods that might answer your question:
import Foundation
import Cocoa
func addRecord<T: NSManagedObject>(_ type : T.Type) -> T
{
let entityName = T.description()
let context = app.managedObjectContext
let entity = NSEntityDescription.entity(forEntityName: entityName, in: context)
let record = T(entity: entity!, insertInto: context)
return record
}
func recordsInTable<T: NSManagedObject>(_ type : T.Type) -> Int
{
let recs = allRecords(T.self)
return recs.count
}
func allRecords<T: NSManagedObject>(_ type : T.Type, sort: NSSortDescriptor? = nil) -> [T]
{
let context = app.managedObjectContext
let request = T.fetchRequest()
do
{
let results = try context.fetch(request)
return results as! [T]
}
catch
{
print("Error with request: \(error)")
return []
}
}
func query<T: NSManagedObject>(_ type : T.Type, search: NSPredicate?, sort: NSSortDescriptor? = nil, multiSort: [NSSortDescriptor]? = nil) -> [T]
{
let context = app.managedObjectContext
let request = T.fetchRequest()
if let predicate = search
{
request.predicate = predicate
}
if let sortDescriptors = multiSort
{
request.sortDescriptors = sortDescriptors
}
else if let sortDescriptor = sort
{
request.sortDescriptors = [sortDescriptor]
}
do
{
let results = try context.fetch(request)
return results as! [T]
}
catch
{
print("Error with request: \(error)")
return []
}
}
func deleteRecord(_ object: NSManagedObject)
{
let context = app.managedObjectContext
context.delete(object)
}
func deleteRecords<T: NSManagedObject>(_ type : T.Type, search: NSPredicate? = nil)
{
let context = app.managedObjectContext
let results = query(T.self, search: search)
for record in results
{
context.delete(record)
}
}
func saveDatabase()
{
let context = app.managedObjectContext
do
{
try context.save()
}
catch
{
print("Error saving database: \(error)")
}
}
Assuming that there is a NSManagedObject setup for Contact like this:
class Contact: NSManagedObject
{
#NSManaged var contactNo: Int
#NSManaged var contactName: String
}
These methods can be used in the following way:
let name = "John Appleseed"
let newContact = addRecord(Contact.self)
newContact.contactNo = 1
newContact.contactName = name
let contacts = query(Contact.self, search: NSPredicate(format: "contactName == %#", name))
for contact in contacts
{
print ("Contact name = \(contact.contactName), no = \(contact.contactNo)")
}
deleteRecords(Contact.self, search: NSPredicate(format: "contactName == %#", name))
recs = recordsInTable(Contact.self)
print ("Contacts table has \(recs) records")
saveDatabase()
This is the simplest way to migrate to Swift 3.0, just add <Country>
(tested and worked)
let request = NSFetchRequest<Country>(entityName: "Country")
Swift 3.0 This should work.
let request: NSFetchRequest<NSFetchRequestResult> = NSManagedObject.fetchRequest()
request.entity = entityDescription(context)
request.predicate = predicate
I also had "ResultType" could not be inferred errors. They cleared once I rebuilt the data model setting each entity's Codegen to "Class Definition". I did a brief writeup with step by step instructions here:
Looking for a clear tutorial on the revised NSPersistentContainer in Xcode 8 with Swift 3
By "rebuilt" I mean that I created a new model file with new entries and attributes. A little tedious, but it worked!
What worked best for me so far was:
let request = Level.fetchRequest() as! NSFetchRequest<Level>
I had the same issue and I solved it with the following steps:
Select your xcdatamodeld file and go to the Data Model Inspector
Select your first Entity and go to Section class
Make sure that Codegen "Class Definition" is selected.
Remove all your generated Entity files. You don't need them anymore.
After doing that I had to remove/rewrite all occurences of fetchRequest as XCode seem to somehow mix up with the codegenerated version.
HTH
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
func loadItemsCategory() {
let request: NSFetchRequest<Category> = Category.fetchRequest()
do {
categoryArray = try context.fetch(request)
} catch {
print(error)
}
tableView.reloadData()
}
I am trying to get a Results<News> of news objects from realm of all objects that have 'mytag'
The News object looks something like
dynamic var id = 0
dynamic var title = ""
dynamic var date = NSDate()
dynamic var modified = NSDate()
dynamic var protected = true
dynamic var category : Category?
dynamic var image : Image?
let content = List<Content>()
let tags = List<Tag>()
I have a Results<Tag> with all my tags. Tag has a boolean my to see if it belongs to my tags.
This way I could get personal news.
However, I don't understand how to query this. I have some knowledge of SQL, but i cant seem to figure it out using contains or in
I tried a workaround but it seems Results does not have an append function.
Here's my current workaround:
func retrieveMyNewsSortedByDate() -> Results<News> {
let myTags = TagDataService().myTagsList() // retunrs a List<Tag>
print("My news items");
let items = database().objects(News).filter("tags IN %#", myTags).sorted("date") // how to query or query with news and tag table
let myTagItems = List<News>()
for tag in myTags {
for news in items{
for newsTag in news.tags {
if newsTag == tag {
myTagItems.append(news) // Results does not have .append or .addobject
}
}
}
}
mytagItems = Results(myTagItems)
return myTagItems
}
However, now I would have a very inefficient way that also outputs list that I can't seem to cast to Results. How do I do this?
well, it was quite easy in the end :D
func retrieveMyNewsSortedByDate() -> Results<News> {
let myTags = TagDataService().myTagsList()
let items = database().objects(News).filter("ANY tags IN %#", myTags).sorted("date")
return items
}
I have a UITableViewController which is basically a news feed. I have also implemented a pull to refresh feature. However sometimes when I pull to refresh it gives me the error
'Array index out of range'.
I know this means an item it is trying to get does not exist but can you tell me why? Here is my code:
override func viewDidLoad() {
super.viewDidLoad()
refresher = UIRefreshControl()
refresher.attributedTitle = NSAttributedString(string: "Pull to refresh")
refresher.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged)
self.tableView.addSubview(refresher)
refresh()
tableView.delegate = self
tableView.dataSource = self
}
and the refresh() function:
func refresh() {
//get username and match with userId
let getUser = PFUser.query()
getUser?.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if let users = objects {
//clean arrays and dictionaries so we don't get indexing error
self.messages.removeAll(keepCapacity: true)
self.usernames.removeAll(keepCapacity: true)
for object in users {
if let user = object as? PFUser {
//make userId = username
self.users[user.objectId!] = user.username!
}
}
}
})
let getPost = PFQuery(className: "Posts")
getPost.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if let objects = objects {
self.messages.removeAll(keepCapacity: true)
self.users.removeAll(keepCapacity: true)
self.usernames.removeAll(keepCapacity: true)
for object in objects {
self.messages.append(object["message"] as! String)
self.usernames.append(self.users[object["userId"] as! String]!)
self.tableView.reloadData()
}
}
}
self.refresher.endRefreshing()
}
It appears you are removing everything from users and then trying to access it in getPost.findObjectsInBackgroundWithBlock.
Specifically, self.users.removeAll(keepCapacity: true) is called just before self.usernames.append(self.users[object["userId"] as! String]!).
Also, be aware that the two queries execute asynchronously. You have no guarantee that users has been populated when the second query's completion block is reached. You will most likely want to restructure your two queries into one compound query or nest them (not recommended).
Lastly, from the looks of it, you may want to use removeAll(keepCapacity: false) rather than keeping the capacity with removeAll(keepCapacity: true).