Realm: get notified on new insertion / update of object - ios

I am trying out Realm.io on my Swift project. The insertion and update of objects are pretty straightforward, but here comes a problem: I am not able to catch a new object insertion/update notification.
What I want to achieve is simple, I save a list of objects in Realm. And upon app start/refresh, the app will request a new list of objects from remote server and then perform realm.add(objects, update:true) (I've set id as the object's primary key so that the same objects will not be duplicated), then the UI end of my app should be notified whenever there's a new object, or any existing objects have been updated.
I've tried using realm.addNotificationBlock(_:) but it's called every time with a RLMRealmDidChangeNotification event, even though there is no new object/update.
How do I achieve this?
Edit: code sample
public class DataStorageManager {
var token : NotificationToken?
static let sharedInstance = DataStorageManager ()
public func saveListA(list: [A]?, realm:Realm) {
self.token = realm.addNotificationBlock({ (notification, realm) -> Void in
print("database changed")
})
if list?.count > 0 {
try! realm.write {
realm.add(list!, update:true)
}
}
}
}

You should call addNotificationBlock only once and not everytime you call saveListA. So you could move it to the DataStorageManager's init method.
But you wrote that you want to update your UI whenever the list is updated, so instead of having the token inside your DataStorageManager class you could directly add the NotificationToken as a property to your UIViewController class and call addNotificationBlock in your view controller's viewDidLoad method. Then you can directly update your UI inside the notification block.
EDIT:
If you only want to update your UI when certain data gets updated you cannot use Realm's notification system (which sends a notification everytime any data is changed).
You can do one of the following
Use KVO on your Realm objects. This is described in the Realm Docs
Send your own NSNotification whenever the data is updated that needs a refresh of your UI. So in your case you can send an NSNotification everytime your list gets changed in saveListA. Then you register your view controller as an observer to that notification and update your UI whenever you receive that notification.

As I understand it, you should fetch the desired objects somewhere you want to hold them (like your data manager or view controller), getting Results object and subscribe to this Results change.
Please refer to https://realm.io/docs/swift/latest/#collection-notifications.
It doesn't matter where the object would be changed as long as you hold to that notifications token.
The downside is, currently "modifications" array always include every "touched" element, regardless of if there had been any changes at all. It is considered a bug, but no progress there since August '17.
https://github.com/realm/realm-cocoa/issues/3489
For now, I compare modifications manually after getting the notification.

Related

Firebase doesn't call back when using '.childAdded'

I have the following code, written in Swift which I expect to be called each time a new record has been added to the my Database:
var databaseRef = Firebase()
databaseRef = Firebase.init(url: "<MY_PROJECT_URL>")
databaseRef.child(byAppendingPath: "channels").queryLimited(toFirst: 100).observe(.childAdded , with: { (snapshot) in
print("New Message input by user")
})
And this is my data structure:
So I basically create a listener for the branch 'channels'. The completion handler gets called only at the start of my program, then, never again. The strange thing is that if I use '.value' rather than '.childAdded' it does work! I am not interested in using '.value' since that returns me the whole chunk of data inside the 'channels' branch and I am really interested only in the single record that was added. (actually one of those L1... guys. A new one of course) Any ideas?
If you are observing messages from all users at the same time I'd recommend restructuring your Firebase data a bit. Make messages a top-level object, and then you can just observe that whole section. I don't know what your messages look like, but I assume if you do this you will need to add a reference to the user inside the message so that you can get the new message added and still see which user wrote it.

Firebase observeEventType .childAdded doesn't work as promised

When I call this observe function from in my viewcontroller, the .childadded immediately returns a object that was already stored instead of has just bin added like .childadded would suspect.
func observe(callback: RiderVC){
let ref = DBProvider.Instance.dbRef.child("rideRequests")
ref.observe(DataEventType.childAdded) { (snapshot: DataSnapshot) in
if let data = snapshot.value as? NSDictionary {
let drive = cabRide(ritID: ritID, bestemming: bestemming,
vanafLocatie: vanaf, taxiID: taxiID, status: status)
print(drive)
callback.alertForARide(title: "Wilt u deze rit krijgen?", message: "Van: \(vanaf), Naar: \(bestemming)", ritID: ritID)
}
}
}
When I try this function with .childchanged, I only get a alert when it is changed like it suppose to do, but when doing .chiladded, it just gets all the requests out of the database and those requests were already there.
When I add a new request, it also gives an alert. So it works, but how can I get rid of the not added and already there requests?
Does anybody know this flaw?
This is working exactly as promised. From the documentation:
Retrieve lists of items or listen for additions to a list of items.
This event is triggered once for each existing child and then again
every time a new child is added to the specified path. The listener is
passed a snapshot containing the new child's data.
That might seem weird at first, but this is generally what most developers want, as it's basically a way of asking for all data from a particular branch in the database, even if new items get added to it in the future.
If you want it to work the way you're describing, where you're only getting new items in the database after your app has started up, you'll need to do a little bit of work yourself. First, you'll want to add timestamps to the objects you're adding to the database. Then you'll want to do some kind of call where you're asking to query your database by those timestamps. It'll probably look something like this:
myDatabaseRef.queryOrdered(byChild: "myTimestamp").queryStarting(atValue: <currentTimestamp>)
Good luck!

What happens to local variables storing references to deleted NSManagedObjects

When I delete an NSMangedObject from the database, what happens to local variables who were assigned to it?
For example, I have a simple NSManagedObject:
class MyManagedObject: NSManagedObject {
#NSManaged var name: String
}
And then in my ViewController, I pull it out of the database, and assign it locally:
class ViewController: UIViewController {
var myManagedObject: MyManagedObject!
}
Then I delete it from the database.
If print the object name I get the following in the console
print("myManagedObject.name = \(myManagedObject.name)")
//prints: "myManagedObject.name = "
As if the object isn't there? But if I turn the variable into an optional and check it for nil, I am told it's not nil.
I'm not quite sure how to reconcile this in my mind. There seems to be something pointing to the local variable, but its properties are gone.
If I have many disparate UI objects that rely on that object for its properties, I can't assume that there is some local deep copy of it in memory?
Here is more complete code:
In viewDidLoad I create the new object, save the context, fetch the object, then assign it locally.
class ViewController: UIViewController {
var myManagedObject: MyManagedObject!
override func viewDidLoad() {
super.viewDidLoad()
//1 Create the new object
let newObject = NSEntityDescription.insertNewObject(forEntityName: "MyManagedObject", into: coreDataManager.mainContext) as! MyManagedObject
newObject.name = "My First Managed Object"
//2 Save it into the context
do {
try coreDataManager.mainContext.save()
} catch {
//handle error
}
//3 Fetch it from the database
let request = NSFetchRequest<MyManagedObject>(entityName: "MyManagedObject")
do {
let saved = try coreDataManager.mainContext.fetch(request)
//4 Store it in a local variable
self.myManagedObject = saved.first
} catch {
//handle errors
}
}
}
At this point if I print the local variable's name property, I get the correct response:
print("The object's name is: \(myManagedObject.name)")
//prints: The object's name is: My First Managed Object
So, now I delete it from the database:
if let storedObject = myManagedObject {
coreDataManager.mainContext.delete(storedObject)
do {
try coreDataManager.mainContext.save()
} catch {
//handle error
}
}
But now, when I print I get the strangest output:
print("myManagedObject.name = \(myManagedObject.name)")
//prints: "myManagedObject.name = "
This is totally not the way I'm expecting memory to work. If I create a instance of a class Foo, and then pass that instance around to different objects, it's the same instance. It only goes away once no one is pointing to it.
In this case--- what is the variable, myManagedObject? It's not nil. And what is the string, name? Is it an empty string? Or is it some other weird meta-type?
The main thing what you are probably looking here for is the core data context. The context is a connection between your memory and the actual database.
Whenever you fetch the data you fetch it through context. These are managed objects which can be modified or even deleted. Still none of these really happen on the database until you save the context.
When you delete an object it is marked for deletion but it is not deleted from the memory, it must not be since if nothing else it will still be used by the context to actually delete the object from the database itself.
What happens to the managed object once you call to delete it is pretty much irrelevant, even if documented it may change as it is a part of the framework. So it is your responsibility to check these cases and to refetch the objects once needed. So you must ensure your application has a proper architecture and uses core data responsibly.
There are very many ways on how you use your database and more or less any of them has a unique way of using it optimally. You need to be more specific on what you are doing and where do you see potential issues so we can get you on the right track.
To give you an example consider data synchronization from remote server. Here you expect that data can be synchronized at any time no matter what user is doing or what part of the application he is.
For this I suggest you have a single context which operates on a separate thread. All the managed objects should be wrapped and its properties copied once retrieved from database. On most entities you would have something like:
MyEntity.findAll { items in
...the fetch happens on context thread and returns to main, items are wrappers
}
MyEntity.find(id: idString, { item in
...the fetch happens on context thread and returns to main, items are wrappers
})()
Then since you do not have any access to the managed object directly you need some kind of method to copy the data to the managed object like:
myEntityInstance.commit() // Copies all the data to core data object. The operation is done on a context thread. A callback is usually not needed
And then to save the database
MyEntity.saveDatabse {
... save happens on the context thread and callback is called on main thread
}
Now the smart part is that saveDatabse method will report to a delegate that changes have been made. A delegate is usually the current view controller so it makes sense to have a superclass like DataBaseViewController which on view did appear assigns itself as a delegate MyEntity.delegate = self, on view did load calls some method reloadData and in the databaseDidChange delegate method calls reloadData and same in viewWillAppear.
Now each of your view controllers that are subclass of DataBaseViewController will override the reloadData and in that method you will fetch the data from the database again. Either you are fetching all items or a single one. So for those singe ones you need to save the id of the object and fetch it again by that id. If the returned object is nil then item was deleted so you catch the issue you seem to be mentioning.
All of these things are oversimplified but I hope you get a basic idea about core data and how to use it. It is not easy, it never was and it most likely never will be. It is designed for speed to be able to access the data even from a very large database in shortest time possible. The result is that it might not be very safe.

How to delete object in Realm properly and thread-safe

I've just starting to using Realm and feel it's very good, fast except one thing: delete an object in Realm is easily cause an exception.
Is there any way I can delete an object in Realm safety?
In my project, I usually have to create, update, delete hundred objects on the background thread. The issue is:
If the app currently display/using one object on the main thread
In the background, I delete that object.
=> On the main thread will cause an exception when using that object's properties.
I know Realm has isInvalid method to check, but I cannot add the check in every assign properties code, it's look not good.
So, as of now, what I do is: instead of actually delete, I have a property call "deleted", and in delete, I only update that value. And on the UI, I will filtered out objects which have deleted = true
I wonder is there any way better to do this?
This is intended functionality. If a background thread deletes a Realm Object, the next time you try and access that object from any thread, an exception will be thrown.
In order to handle this, Realm provides a rich notification system that you can use to automatically receive alerts of when the contents of a Realm database have been changed and to update the UI accordingly.
If you've got a view controller that is displaying the contents of a single Realm Object, you could implement a system to be notified of any changes being made to your Realm database, and then check to make sure your object is still valid:
class MyViewController : UIViewController {
var myModel: Object = nil
var notificationToken: NotificationToken? = nil
init(model: Object) {
self.myModel = model
}
override fun viewDidLoad() {
super.viewDidLoad()
notificationToken = myModel.realm.addNotificationBlock { notification, realm in
guard myModel.invalidated == false else {
// The object has been deleted, so dismiss this view controller
}
}
}
deinit() {
notificationToken?.stop()
}
}
That notification block will be triggered each time a write transaction modified something in that particular Realm file (Even on background threads), which gives you a chance to check to see if your particular Realm Object in that UI hasn't been deleted. If it has, then you can simply dismiss the UI.
Depending on your specific needs, there is also a more fine-grained notification system you can use to specifically track changes to Realm Objects that were part of the results of a query. There's sample code for that in the Collection Notifications of the Realm documentation.
Please let me know if you need additional clarification! :)

How to avoid calling a method multiple times when the method takes long time to complete

There are several view controllers in my app where I need to sync the local contents with server using a method running in a background thread. Sometimes I need to insert data to my database on server if user has created any. The approach I am using here is to set a flag(something like isSynced = NO) on objects that I need to sync with server (there objects are in Core Data). When the syncing is complete my method will get rid of the flag(e.g. isSynced = YES) so it won't be sent again next time.
Now the problems is that the syncing method takes very long to complete(1 or 2seconds.). If now user pops out this particular view controller and swiftly comes back the previous call is still in progress and next one will be kicked off. The consequence is that there might be duplication in database.
My approach now is the make the syncing method to be called by a Singleton object:
#property (nonatomic) BOOL isSyncing;
//every time before syncing. check if object is available for syncing
if (!isSyncing) {
isSyncing = YES;
// sync server
// when complete
isSyncing = NO;
// post notification to view controller to reload table
} else {
// cancel because previous call is not finished
}
My concern is that if the call is cancelled my view controller will not be able to receive the notification is waiting for. I can fix this by posting another notification in the event of cancelation. I am wondering if this is the right to do this because I think that this problem should be pretty common in iOS development and there should be a standard way to deal with it
Your singleton approach may not be necessary. I don't see the harm in sending a database insert for each new object. You will still need to ensure each object is synched. That is, update the "isSynched" flag. Keep each object that needs to be synced in a "need to synch" list.
Then, update the "isSynced" flag by performing a background query on the database to check if the object exits. Then, use the result of the query to set the isSynched flag.
If the query result indicates the object is not in the database you then resend the object and leave it's "isSynced" flag set to NO.
If the query result indicates the object is in the database, set the "isSynced" flag to YES and remove it from your "need to synch" list.
An approach for preventing duplicate database entries is to make a unique key. For example, tag each with a hash based on the time and date. Then configure the table to ensure each key is unique.

Resources