I have a class DataEntry that I want to store instances of in a Realm database, but i'm having issue instantiating a Realm. Here is my DataEntry class:
class DataEntry: Object {
#objc dynamic var id = 0
#objc dynamic var exercise = ""
#objc dynamic var weightLBS = 0
#objc dynamic var averageBarSpeed = 0
#objc dynamic var topBarSpeed = 0
}
Some context as to what I'll be using it for:
I'd like to have functions to write and delete instances of a DataEntry, but the documentation on that seems fairly simple.
Adding new dataEntry would be done by a user inputing data into a form
Deleting dataEntrys will simply be a button
Planning on reading the data to create graphs to track performance over time
The issue I'm having is instantiating a new Realm, and using the appropriate error handling. I've found a few simpler examples, but they all throw errors so i'm assuming there's something i'm missing. I know you're not supposed to use try!, so I'm wondering, what is a simple way to instantiate a new Realm, so I can then read/write/delete DataEntry's to the Realm Database.
This one gives me multiple "Expected Declaration" errors in lines 1 and 3.
do {
let realm = try Realm()
} catch let error as NSError {
// handle error
}
This one gives me an "Expected Declaration" error on line 1
try {
let realm = try Realm()
} catch {
print(error.localizedDescription)
}
Any additional pointers on how to best set up this would be amazing, wether or not I should have a RealmManager class that would aid in error handling. I've seen in some cases people create extensions of Realm, but this is a little too advanced for me right now.
Background in CS, but brand new to both Swift and Realm for context.
Edit/Update:
Quick clarification, I'm having issues with instantiating a Realm. Not a Realm object. I've updated above to be more clear.
To clarify my question, I'm getting errors for what appears to be good code above, so I assume I have it in the wrong place. I get errors when its inside the DataEntry class, when its inside of a view, and at the top level of a SwiftUI file. Any advice on where I should include the c ode for the instantiation would be great!
I am not sure if this will help but knowing where to put things within a project can sometimes help understand the flow.
So I created a realm project in XCode that writes a person object with the name of Jay to realm when button 0 is clicked. Then when button 1 is clicked, it retrieves that data and prints to console.
There's no error checking here and I am force unwrapping an optional so don't do that in a real app.
import Cocoa
import RealmSwift
class PersonClass: Object {
#Persisted var name = ""
}
class ViewController: NSViewController {
#IBAction func button0Action(_ sender: Any) {
let realm = try! Realm()
let jay = PersonClass()
jay.name = "Jay"
try! realm.write {
realm.add(jay)
}
}
#IBAction func button1Action(_ sender: Any) {
let realm = try! Realm()
let jay = realm.objects(PersonClass.self).where { $0.name == "Jay" }.first!
print(jay.name) //outputs "Jay" to console
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
The project starts with importing RealmSwift and then the Realm object(s) are defined outside of any other classes, so they are at a high level.
Then we have the ViewController with two button actions - as you can see, within each action function, we access realm with
let realm = try! Realm()
and then interact with realm. When that function exits, the realm object is deallocated so it's a safe way to work with Realm and not leave it 'connected'.
Some developers create a singleton or a RealmService class to interact with Realm but singletons can be tricky. I suggest initially going with the pattern shown above (and in the docs).
there has a better way to update and append a new record to Realm in the latest version.
#ObservedResults(Group.self) var groups
$groups.append(Group())
TextField("New name", text: $item.name)
The documentation is here, please take some time to read it.
If it is hard for you, I suggest at least finishing this video by code along with her. LINK
Related
I have set an observer for a live result object.
let token = realm.objects(RealmObject.self).observe(on: realmQueue) { changeset in
print(changeset)
}
It works as expected for the most part, it triggers when I add/delete or edit RealmObject type objects in/to the realm db.
My issue happens when I try to replace the whole array of objects with a new array. Basically what I do is I get all objects of type RealmObjects delete them and then I add the new array of RealmObjects. Now the issues is if I do the delete and add in one write transaction the notification mechanism seems to break, it doesn't trigger for this operation. On the other hand if I separate the delete and add into different write transactions then everything works with notifications (except I get two notifications as expected in this case, but it's not what I want).
Am I missing something and doing something wrong ?
// triggers notifications
let objectsToDelete = realm.objects(RealmObject.self)
try realm.write {
if !objectsToDelete.isEmpty {
realm.delete(objectsToDelete)
}
}
try realm.write {
realm.add(objects)
}
// doesn't trigger notification
let objectsToDelete = realm.objects(RealmObject.self)
try realm.write {
if !objectsToDelete.isEmpty {
realm.delete(objectsToDelete)
}
realm.add(objects)
}
edit: After further investigation it seems that this only happens in a specific case. When replacing the items with the same number of items and same primary key (even though some other properties ore different).
class RealmObject: Object {
#objc dynamic var primary: String!
#objc dynamic var summary: String!
override class func primaryKey() -> String? {
return "primary"
}
}
extension RealmObject {
convenience init(summary: Int, uuid: String = UUID().uuidString) {
self.init()
self.primary = uuid
self.summary = "Object nr. \(summary)"
}
}
let sharedKeys = [UUID().uuidString, UUID().uuidString, UUID().uuidString]
let initialObjects = [RealmObject(summary: 0, uuid: sharedKeys[0]),RealmObject(summary: 1, uuid: sharedKeys[1]),RealmObject(summary: 2, uuid: sharedKeys[2])]
let replaceObjects = [RealmObject(summary: 3, uuid: sharedKeys[0]),RealmObject(summary: 4, uuid: sharedKeys[1]),RealmObject(summary: 5, uuid: sharedKeys[2])]
This rings bells (I worked on the Realm C# team 2015-2017).
I'm fairly certain it is because of optimisations around primary keys and their use within a transaction, combined with how the notification structure is built. Strictly speaking, it is a bug. You might expect these would be coming out as Delete+Add or as a Change record in the notification.
You are fighting a deep core assumption about how primary keys are used and optimisations that are intended to keep them working incredibly fast. I doubt strongly it will get fixed.
Switching to non-primary keys but indexed fields would probably get around this but complicate the rest of your code, sorry.
It's also possible you don't need these to be indexed at all, depending on your data volumes. Realm does some incredibly fast searching so I always recommend people try a non-indexed search first to see if that's enough.
Say I am creating an object that takes two strings and acts like a dictionary.
class WordInDictionary: Object {
#objc dynamic var word: String = ""
#objc dynamic var meaning: String = ""
What should I do if I wanted to have some initial objects that get added to the database just once upon installation/update of the app?
Also, is there a way to make it so that just those initial objects can't be deleted?
"What should I do if I wanted to have some initial objects that get added to the database just once upon installation/update of the app?"
One option would be to have some code near the realm initialisation that checks if there are any WordInDictionary objects already in the realm - if not then add the required default objects.
E.g.
let realm = try! Realm()
if realm.objects(WordInDictionary.self).isEmpty
{
// Add required words here
}
"Also, is there a way to make it so that just those initial objects can't be deleted?"
I don't know of a way to make realm objects read-only. You'd have to implement this in code in some way, e.g. have a isDeletable boolean member which is true for every user-created object and false for your default members, then only delete those from realm.
E.g. for your deletion code:
func deleteWords(wordsToDelete: Results<WordInDictionary>)
{
try! realm.write
{
realm.delete(wordsToDelete.filter("isDeletable = true")
}
}
I'm learning to be an iOS app developer and I want to make an app which stores core data. I know how to do it using tables but is there a way I can store data without using tables? Like I'm trying to make an app which saves about a 100 different variables but m not using tables in it. Can someone please direct me to a full tutorial of how it's done? I came across one tutorial on Ray weindervich but it was done on swift 1.2 and it didn't work for me. Thanks
Core data depends on entities, now something that might help to share (probably you knew this already) is that Core data entity is not a table it represents a thing that can be identify and quantify for example a fruit regardless what your back end is; with that been said, now I have a question, when you say table do do you mean the entities or an actual database table? If you mean entity, with Core data you can say use SQLite as backend or xml file as back end but regardless how you store the data you will need to create at least one entity.
What was suggested in the comments still using entities. So my suggestion would be just create one entity using one of this options:
1. Entity
variable1 datatype
variable2 datatype
...
...
variable n datatype
or
2. Entity
key String
Value object
With option one you will have to know all the possible variables that your application will use and one good advantage is that you won't have to do down casting neither unwrapping.
With option two you don't need to know all the possible variables and also your data can grow without changing the app, the only downside is you will have to wrap and unwrap the data from each record.
These are my suggestions for you.
Hope this help
UPDATE :
So here are the steps that I think you need to follow to achieve your request (important: this a simple sample):
Make sure your project has enable since creation Core Data.
In the Model add the Entity as the picture shows:
Then add the attributes as the picture shows:
Add the add the subclass; this part is not mandatory but makes it easy to handle each entity and its properties.
Then you should have something similar to the following code for the entity:
import Foundation
import CoreData
class Generic: NSManagedObject {
#NSManaged var key: String?
#NSManaged var value: NSObject?
}
And your view controller should have something like this in order to read and save the data:
import UIKit
import CoreData
class ViewController: UIViewController {
#IBOutlet var txtVariable: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let delegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context = delegate.managedObjectContext
let request = NSFetchRequest(entityName: "Generic")
let filter = NSPredicate(format: "key = %#", "xyz")
request.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [filter])
do {
let records = try context.executeFetchRequest(request) as! [Generic]
if (records.count>0)
{
txtVariable.text = (records[0].value as! String)
}
}
catch let error as NSError{
NSLog(error.localizedDescription)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func btnSave_Click(sender: AnyObject) {
let delegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context = delegate.managedObjectContext
let record = NSEntityDescription.insertNewObjectForEntityForName("Generic", inManagedObjectContext: context) as? Generic
record?.key = "xyz"
record?.value = txtVariable.text
do {
try context.save()
}
catch let error as NSError{
NSLog(error.localizedDescription)
}
}}
I'll make it short as possible.
I have an API request that I fetch data from (i.e. Parse).
When I'm getting the results I'm writing it to Realm and then adding them to a UICollectionView's data source.
There are requests that take a bit more time, which run asynchronous. I'm getting the needed results after the data source and collection view was already reloaded.
I'm writing the needed update from the results to my Realm database.
I have read that it's possible to use Realm's Results. But I honestly didn't understood it. I guess there is a dynamic and safe way working with collection views and Realm. Here is my approach for now.
This is how I populate the collection view's data source at the moment:
Declaration
var dataSource = [Realm_item]()
where Realm_item is a Realm Object type.
Looping and Writing
override func viewDidLoad() {
super.viewDidLoad()
for nowResult in FetchedResultsFromAPI
{
let item = Realm_item()
item.item_Title = nowResult["Title"] as! String
item.item_Price = nowResult["Price"] as! String
// Example - Will write it later after the collectionView Done - Async request
GetFileFromImageAndThanWriteRealm(x.image)
// Example - Will write it later after the collectionView Done - Async request
dataSource.append(item)
}
//After finish running over the results *Before writing the image data*
try! self.realm.write {
self.realm.add(self.dataSource)
}
myCollectionView.reloadData()
}
After I write the image to Realm to an already created "object". Will the same Realm Object (with the same primary key) automatically update over in the data source?
What is the right way to update the object from the data source after I wrote the update to same object from the Realm DB?
Update
Model class
class Realm_item: Object {
dynamic var item_ID : String!
dynamic var item_Title : String!
dynamic var item_Price : String!
dynamic var imgPath : String?
override class func primaryKey() -> String {
return "item_ID"
}
}
First I'm checking whether the "object id" exists in the Realm. If it does, I fetch the object from Realm and append it to the data source. If it doesn't exist, I create a new Realm object, write it and than appending it.
Fetching the data from Parse
This happens in the viewDidLoad method and prepares the data source:
var query = PFQuery(className:"Realm_item")
query.limit = 100
query.findObjectsInBackgroundWithBlock { (respond, error) -> Void in
if error == nil
{
for x in respond!
{
if let FetchedItem = self.realm.objectForPrimaryKey(Realm_item.self, key: x.objectId!)
{
self.dataSource.append(FetchedItem)
}
else
{
let item = Realm_item()
item.item_ID = x.objectId
item.item_Title = x["Title"] as! String
item.item_Price = x["Price"] as! String
let file = x["Images"] as! PFFile
RealmHelper().getAndSaveImageFromPFFile(file, named: x.objectId!)
self.dataSource.append(item)
}
}
try! self.realm.write {
self.realm.add(self.dataSource)
}
self.myCollectionView.reloadData()
print(respond?.count)
}
}
Thank you!
You seem to have a few questions and problems here, so I'll do my best.
I suggest you use the Results type as your data source, something like:
var dataSource: Results<Realm_item>?
Then, in your viewDidLoad():
dataSource = realm.objects(Realm_item).
Be sure to use the relevant error checking before using dataSource. We use an optional Results<Realm_item> because the Realm object you're using it from needs to be initialised first. I.e., you'll get something like "Instance member * cannot be used on type *" if you try declaring the results like let dataSource = realm.objects(Realm_item).
The Realm documentation (a very well-written and useful reference to have when you're using Realm as beginner like myself), has this to say about Results...
Results are live, auto-updating views into the underlying data, which means results never have to be re-fetched. Modifying objects that affect the query will be reflected in the results immediately.
Your mileage may vary depending on how you have everything set up. You could try posting your Realm models and Parse-related code for review and comment.
Your last question:
What is the right way to update the "object" from the Data Source after i wrote the update to same object from the Realm DB?
I gather you're asking the best way to update your UI (CollectionView) when the underlying data has been updated? If so...
You can subscribe to Realm notifications to know when Realm data is updated, indicating when your app’s UI should be refreshed for example, without having to re-fetch your Results.
I've seen many tutorials and they really help me with understand parent-child managed object context and other things related to this. I am ready to start using it in my app but I have a question. Why nobody use singleton for keeping main managed object context. I guess it would be much better to extract Core Data related objects from AppDelegate and set it to own class right? Something like in this Tutorial at raywenderlich.com. But they still instantiate CoreDataStack class (no problem with this, singleton must be instantiate too) and when it's need they set managedObjectContext in prepareForSegue (and set it to first view controller from AppDelegate). Why not to remove this need and just use singleton CoreDataStack and have possible to use managedObjectContext in each controller if needed?
Second and bonus question: I think it's better to have less code in controller and more in other classes. I think it helps with readability. So what if I move this code from controller and set it for example to CoreDataStack class or some other class that helps with Core Data requests and responses:
func surfJournalFetchRequest() -> NSFetchRequest {
let fetchRequest =
NSFetchRequest(entityName: "JournalEntry")
fetchRequest.fetchBatchSize = 20
let sortDescriptor =
NSSortDescriptor(key: "date", ascending: false)
fetchRequest.sortDescriptors = [sortDescriptor]
return fetchRequest
}
I know it's possible but is it better? If you get app codes from me would it be better if in controller it would be one line CoreDataStack.fetchRequest("JournalEntry", sortedKey: "date")?
And what about if I take this code and insert it to singleton and created function with closure? I would created child managed context in singleton and do needed operations in there and in controller I would just changed UI:
func exportCSVFile() {
navigationItem.leftBarButtonItem = activityIndicatorBarButtonItem()
let privateContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
privateContext.persistentStoreCoordinator = coreDataStack.context.persistentStoreCoordinator
privateContext.performBlock { () -> Void in
var fetchRequestError:NSError? = nil
let results = privateContext.executeFetchRequest(self.surfJournalFetchRequest(), error: &fetchRequestError)
if results == nil {
println("ERROR: \(fetchRequestError)")
}
let exportFilePath = NSTemporaryDirectory() + "export.csv"
let exportFileURL = NSURL(fileURLWithPath: exportFilePath)!
NSFileManager.defaultManager().createFileAtPath(exportFilePath, contents: NSData(), attributes: nil)
var fileHandleError: NSError? = nil
let fileHandle = NSFileHandle(forWritingToURL: exportFileURL, error: &fileHandleError)
if let fileHandle = fileHandle {
for object in results! {
let journalEntry = object as! JournalEntry
fileHandle.seekToEndOfFile()
let csvData = journalEntry.csv().dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
fileHandle.writeData(csvData!)
}
fileHandle.closeFile()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.navigationItem.leftBarButtonItem =
self.exportBarButtonItem()
println("Export Path: \(exportFilePath)")
self.showExportFinishedAlertView(exportFilePath)
})
} else {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.navigationItem.leftBarButtonItem = self.exportBarButtonItem()
println("ERROR: \(fileHandleError)")
})
}
}
}
I just want to be sure that my aproach would be okay and would be better than original. Thanks
I built my first core data app with a singleton pattern. It seemed logical for me because there is only one core data stack anyway. I was very wrong, the singleton pattern turned into a big mess quickly. I added more and more code to bend the singleton stack to something that works. In the end I gave up and I invested the time to replace the singleton mess with dependency injection.
Here are some of the problems I encountered before I dumped the singleton:
Since the app kept important data, my users requested a backup functionality. To restore from a backup I switched the sqlite file and then I would just create a new Core Data stack. Doing this in a clean way is next to impossible if you use a pull-pattern to get the managedObjectContext from a singleton. So my way to switch the Core Data stack was to tell the user that they have to restart the app. Followed by an exit(). Not the most elegant way to handle this.
After Apple added childContexts I decided to get rid of undo managers and context rollbacks, because that never worked 100% for me. But changing my editing viewControllers so they use child contexts which are discarded when the user hits cancel, was an incredible painful act because I now had a mix of singleton contexts and viewController local contexts in one viewController.
For editing the targets of relationships I had editViewControllers inside editViewController. Because I created the edit context inside the edit viewControllers I ended up saving data to the main context that shouldn't have been saved. It's a bit complicated to explain, but the second viewController saved stuff like new objects to the main context even if the user in the outer edit viewController hit cancel. Which always lead to orphaned objects. So I added more code to bend the singleton in a way that would make it less of a singleton.
I also had a CSV import function and I wanted to preview the data to the user before they press "Import". I build a totally new infrastructure for that. First I parsed the CSV into a data structure that basically duplicated my core data classes. Then I build a viewController to display these non core data classes, with even more code duplication. I would only start to create core data objects when the user pressed import.
After I got rid of the singleton pattern I could reuse the existing data display viewController. I would just give it a different context, in this case an in-memory context that contained the data that will be imported. Much cleaner, less duplicated code.
I guess some of these problems were not really the singletons fault. I was just very inexperienced.
But I still would strongly recommend against singleton core data.
would be one line CoreDataStack.fetchRequest("JournalEntry", sortedKey: "date")?
You don't need a singleton for this. Stuff like this should be in the NSManagedObject subclass you create for JournalEntry.
And what about if I take this code and insert it to singleton and created function with closure? I would created child managed context in singleton and do needed operations in there and in controller I would just changed UI:
And why don't you create a method that doesn't require internal state at all?
class func export(#context: NSManagedObjectContext, toCSVAtPath path: String,
progress: ((current: Int, totalCount: Int) -> Void)?,
completion: ((success: Bool, error: NSError?) -> Void)?) {
Much more flexible.