Observing changes to Realm result set









up vote
4
down vote

favorite












I'm working on an iOS app that uses a Realm database. In my AppDelegate, I define a Realm result set like this:



var results: Results<RealmWidget>!
var notificationToken: NotificationToken? = nil

do
let realm = try Realm()
if results == nil
results = realm.objects(RealmWidget.self)

catch
print(error.localizedDescription)



I observe this result set for changes like this:



if notificationToken == nil 
notificationToken = results.observe (changes: RealmCollectionChange) in
switch changes
case .update(_, _, let insertions, _):
if insertions.count > 0
// show badge on tab bar
// play sound to get the user's attention

default:
break





Anytime a new RealmWidget object is inserted in the database (which happens as a result of receiving data from a server), I want to show a badge on the UITabBar in my UI. This code appears to be working properly.



In another part of my app, I have a view controller with a UITableView that is used to display all of the RealmWidget objects (sorted by a timestamp). Inside of that view controller, I also have a result set that I observe for changes so I know when to reload the tableview. That code looks like this:



var results: Results<RealmWidget>!
var notificationToken: NotificationToken? = nil

class MyViewController: UIViewController, UITableViewDelegate, UITableViewDataSource

override func viewDidLoad()
super.viewDidLoad()

results = RealmHelper.getRealmWidgets() // helper method that queries Realm for all of the Widget objects and sorts them by timestamp
notificationToken = results.observe [weak self] (changes: RealmCollectionChange) in
DispatchQueue.main.async
self!.tableView.reloadData()






This code also appeared to be working properly until I added code to play a sound into the observation block in my AppDelegate. Then I realized that anytime I delete a row from the UITableView in this view controller, I was also hearing the sound play. This was unexpected because I should only be adding the badge to the UITabBar and playing the sound when there is an insertion, not a deletion.



I added some debug code into the observation block that's defined in my AppDelegate so it looks like this:



if notificationToken == nil 
notificationToken = results.observe (changes: RealmCollectionChange) in
switch changes
case .update(_, let deletions, let insertions, let modifications):
print("widget deletion count: (deletions.count)")
print("widget insertion count: (insertions.count)")
print("widget modification count: (modifications.count)")
if insertions.count > 0
// show badge on tab bar
// play sound to get the user's attention

default:
break





When I run the app, switch to the view controller with the tableview and then delete one of the rows (which causes the corresponding RealmWidget object to be deleted from the database), I see the following output printed in the debug console:



widget deletion count: 2
widget insertion count: 1
widget modification count: 0


A couple of things about this are unclear to me:



  • why is the deletion count 2 when I only deleted one RealmWidget object?

  • why is the insertion count 1 when I didn't add/insert any RealmWidget objects?

If anyone can explain what's happening here I would certainly appreciate the help!



-- EDIT --



I added the same debug code into my observation block that is defined inside the view controller and noticed something else strange. When this "problem" occurs, I see this output in the debug console:



widget deletion count (AppDelegate): 2
widget insertion count (AppDelegate): 1
widget modification count (AppDelegate): 0

widget deletion count (View controller): 1
widget insertion count (View controller): 0
widget modification count (View controller): 0


So the observation block in my view controller shows 1 deletion but the observation block in my AppDelegate shows 2 deletions and 1 insertion! Oddly enough, this doesn't happen 100% of the time. If my UITableView is showing 10 RealmWidget objects and I delete them one at a time, about 75% of the time, I see the above output in the console. But the other 25% of the time, the output is exactly what I was expecting to see:



widget deletion count (AppDelegate): 1
widget insertion count (AppDelegate): 0
widget modification count (AppDelegate): 0

widget deletion count (View controller): 1
widget insertion count (View controller): 0
widget modification count (View controller): 0


1 deletion in both observation blocks. I'm even more confused now than I was before! ;-)










share|improve this question



























    up vote
    4
    down vote

    favorite












    I'm working on an iOS app that uses a Realm database. In my AppDelegate, I define a Realm result set like this:



    var results: Results<RealmWidget>!
    var notificationToken: NotificationToken? = nil

    do
    let realm = try Realm()
    if results == nil
    results = realm.objects(RealmWidget.self)

    catch
    print(error.localizedDescription)



    I observe this result set for changes like this:



    if notificationToken == nil 
    notificationToken = results.observe (changes: RealmCollectionChange) in
    switch changes
    case .update(_, _, let insertions, _):
    if insertions.count > 0
    // show badge on tab bar
    // play sound to get the user's attention

    default:
    break





    Anytime a new RealmWidget object is inserted in the database (which happens as a result of receiving data from a server), I want to show a badge on the UITabBar in my UI. This code appears to be working properly.



    In another part of my app, I have a view controller with a UITableView that is used to display all of the RealmWidget objects (sorted by a timestamp). Inside of that view controller, I also have a result set that I observe for changes so I know when to reload the tableview. That code looks like this:



    var results: Results<RealmWidget>!
    var notificationToken: NotificationToken? = nil

    class MyViewController: UIViewController, UITableViewDelegate, UITableViewDataSource

    override func viewDidLoad()
    super.viewDidLoad()

    results = RealmHelper.getRealmWidgets() // helper method that queries Realm for all of the Widget objects and sorts them by timestamp
    notificationToken = results.observe [weak self] (changes: RealmCollectionChange) in
    DispatchQueue.main.async
    self!.tableView.reloadData()






    This code also appeared to be working properly until I added code to play a sound into the observation block in my AppDelegate. Then I realized that anytime I delete a row from the UITableView in this view controller, I was also hearing the sound play. This was unexpected because I should only be adding the badge to the UITabBar and playing the sound when there is an insertion, not a deletion.



    I added some debug code into the observation block that's defined in my AppDelegate so it looks like this:



    if notificationToken == nil 
    notificationToken = results.observe (changes: RealmCollectionChange) in
    switch changes
    case .update(_, let deletions, let insertions, let modifications):
    print("widget deletion count: (deletions.count)")
    print("widget insertion count: (insertions.count)")
    print("widget modification count: (modifications.count)")
    if insertions.count > 0
    // show badge on tab bar
    // play sound to get the user's attention

    default:
    break





    When I run the app, switch to the view controller with the tableview and then delete one of the rows (which causes the corresponding RealmWidget object to be deleted from the database), I see the following output printed in the debug console:



    widget deletion count: 2
    widget insertion count: 1
    widget modification count: 0


    A couple of things about this are unclear to me:



    • why is the deletion count 2 when I only deleted one RealmWidget object?

    • why is the insertion count 1 when I didn't add/insert any RealmWidget objects?

    If anyone can explain what's happening here I would certainly appreciate the help!



    -- EDIT --



    I added the same debug code into my observation block that is defined inside the view controller and noticed something else strange. When this "problem" occurs, I see this output in the debug console:



    widget deletion count (AppDelegate): 2
    widget insertion count (AppDelegate): 1
    widget modification count (AppDelegate): 0

    widget deletion count (View controller): 1
    widget insertion count (View controller): 0
    widget modification count (View controller): 0


    So the observation block in my view controller shows 1 deletion but the observation block in my AppDelegate shows 2 deletions and 1 insertion! Oddly enough, this doesn't happen 100% of the time. If my UITableView is showing 10 RealmWidget objects and I delete them one at a time, about 75% of the time, I see the above output in the console. But the other 25% of the time, the output is exactly what I was expecting to see:



    widget deletion count (AppDelegate): 1
    widget insertion count (AppDelegate): 0
    widget modification count (AppDelegate): 0

    widget deletion count (View controller): 1
    widget insertion count (View controller): 0
    widget modification count (View controller): 0


    1 deletion in both observation blocks. I'm even more confused now than I was before! ;-)










    share|improve this question

























      up vote
      4
      down vote

      favorite









      up vote
      4
      down vote

      favorite











      I'm working on an iOS app that uses a Realm database. In my AppDelegate, I define a Realm result set like this:



      var results: Results<RealmWidget>!
      var notificationToken: NotificationToken? = nil

      do
      let realm = try Realm()
      if results == nil
      results = realm.objects(RealmWidget.self)

      catch
      print(error.localizedDescription)



      I observe this result set for changes like this:



      if notificationToken == nil 
      notificationToken = results.observe (changes: RealmCollectionChange) in
      switch changes
      case .update(_, _, let insertions, _):
      if insertions.count > 0
      // show badge on tab bar
      // play sound to get the user's attention

      default:
      break





      Anytime a new RealmWidget object is inserted in the database (which happens as a result of receiving data from a server), I want to show a badge on the UITabBar in my UI. This code appears to be working properly.



      In another part of my app, I have a view controller with a UITableView that is used to display all of the RealmWidget objects (sorted by a timestamp). Inside of that view controller, I also have a result set that I observe for changes so I know when to reload the tableview. That code looks like this:



      var results: Results<RealmWidget>!
      var notificationToken: NotificationToken? = nil

      class MyViewController: UIViewController, UITableViewDelegate, UITableViewDataSource

      override func viewDidLoad()
      super.viewDidLoad()

      results = RealmHelper.getRealmWidgets() // helper method that queries Realm for all of the Widget objects and sorts them by timestamp
      notificationToken = results.observe [weak self] (changes: RealmCollectionChange) in
      DispatchQueue.main.async
      self!.tableView.reloadData()






      This code also appeared to be working properly until I added code to play a sound into the observation block in my AppDelegate. Then I realized that anytime I delete a row from the UITableView in this view controller, I was also hearing the sound play. This was unexpected because I should only be adding the badge to the UITabBar and playing the sound when there is an insertion, not a deletion.



      I added some debug code into the observation block that's defined in my AppDelegate so it looks like this:



      if notificationToken == nil 
      notificationToken = results.observe (changes: RealmCollectionChange) in
      switch changes
      case .update(_, let deletions, let insertions, let modifications):
      print("widget deletion count: (deletions.count)")
      print("widget insertion count: (insertions.count)")
      print("widget modification count: (modifications.count)")
      if insertions.count > 0
      // show badge on tab bar
      // play sound to get the user's attention

      default:
      break





      When I run the app, switch to the view controller with the tableview and then delete one of the rows (which causes the corresponding RealmWidget object to be deleted from the database), I see the following output printed in the debug console:



      widget deletion count: 2
      widget insertion count: 1
      widget modification count: 0


      A couple of things about this are unclear to me:



      • why is the deletion count 2 when I only deleted one RealmWidget object?

      • why is the insertion count 1 when I didn't add/insert any RealmWidget objects?

      If anyone can explain what's happening here I would certainly appreciate the help!



      -- EDIT --



      I added the same debug code into my observation block that is defined inside the view controller and noticed something else strange. When this "problem" occurs, I see this output in the debug console:



      widget deletion count (AppDelegate): 2
      widget insertion count (AppDelegate): 1
      widget modification count (AppDelegate): 0

      widget deletion count (View controller): 1
      widget insertion count (View controller): 0
      widget modification count (View controller): 0


      So the observation block in my view controller shows 1 deletion but the observation block in my AppDelegate shows 2 deletions and 1 insertion! Oddly enough, this doesn't happen 100% of the time. If my UITableView is showing 10 RealmWidget objects and I delete them one at a time, about 75% of the time, I see the above output in the console. But the other 25% of the time, the output is exactly what I was expecting to see:



      widget deletion count (AppDelegate): 1
      widget insertion count (AppDelegate): 0
      widget modification count (AppDelegate): 0

      widget deletion count (View controller): 1
      widget insertion count (View controller): 0
      widget modification count (View controller): 0


      1 deletion in both observation blocks. I'm even more confused now than I was before! ;-)










      share|improve this question















      I'm working on an iOS app that uses a Realm database. In my AppDelegate, I define a Realm result set like this:



      var results: Results<RealmWidget>!
      var notificationToken: NotificationToken? = nil

      do
      let realm = try Realm()
      if results == nil
      results = realm.objects(RealmWidget.self)

      catch
      print(error.localizedDescription)



      I observe this result set for changes like this:



      if notificationToken == nil 
      notificationToken = results.observe (changes: RealmCollectionChange) in
      switch changes
      case .update(_, _, let insertions, _):
      if insertions.count > 0
      // show badge on tab bar
      // play sound to get the user's attention

      default:
      break





      Anytime a new RealmWidget object is inserted in the database (which happens as a result of receiving data from a server), I want to show a badge on the UITabBar in my UI. This code appears to be working properly.



      In another part of my app, I have a view controller with a UITableView that is used to display all of the RealmWidget objects (sorted by a timestamp). Inside of that view controller, I also have a result set that I observe for changes so I know when to reload the tableview. That code looks like this:



      var results: Results<RealmWidget>!
      var notificationToken: NotificationToken? = nil

      class MyViewController: UIViewController, UITableViewDelegate, UITableViewDataSource

      override func viewDidLoad()
      super.viewDidLoad()

      results = RealmHelper.getRealmWidgets() // helper method that queries Realm for all of the Widget objects and sorts them by timestamp
      notificationToken = results.observe [weak self] (changes: RealmCollectionChange) in
      DispatchQueue.main.async
      self!.tableView.reloadData()






      This code also appeared to be working properly until I added code to play a sound into the observation block in my AppDelegate. Then I realized that anytime I delete a row from the UITableView in this view controller, I was also hearing the sound play. This was unexpected because I should only be adding the badge to the UITabBar and playing the sound when there is an insertion, not a deletion.



      I added some debug code into the observation block that's defined in my AppDelegate so it looks like this:



      if notificationToken == nil 
      notificationToken = results.observe (changes: RealmCollectionChange) in
      switch changes
      case .update(_, let deletions, let insertions, let modifications):
      print("widget deletion count: (deletions.count)")
      print("widget insertion count: (insertions.count)")
      print("widget modification count: (modifications.count)")
      if insertions.count > 0
      // show badge on tab bar
      // play sound to get the user's attention

      default:
      break





      When I run the app, switch to the view controller with the tableview and then delete one of the rows (which causes the corresponding RealmWidget object to be deleted from the database), I see the following output printed in the debug console:



      widget deletion count: 2
      widget insertion count: 1
      widget modification count: 0


      A couple of things about this are unclear to me:



      • why is the deletion count 2 when I only deleted one RealmWidget object?

      • why is the insertion count 1 when I didn't add/insert any RealmWidget objects?

      If anyone can explain what's happening here I would certainly appreciate the help!



      -- EDIT --



      I added the same debug code into my observation block that is defined inside the view controller and noticed something else strange. When this "problem" occurs, I see this output in the debug console:



      widget deletion count (AppDelegate): 2
      widget insertion count (AppDelegate): 1
      widget modification count (AppDelegate): 0

      widget deletion count (View controller): 1
      widget insertion count (View controller): 0
      widget modification count (View controller): 0


      So the observation block in my view controller shows 1 deletion but the observation block in my AppDelegate shows 2 deletions and 1 insertion! Oddly enough, this doesn't happen 100% of the time. If my UITableView is showing 10 RealmWidget objects and I delete them one at a time, about 75% of the time, I see the above output in the console. But the other 25% of the time, the output is exactly what I was expecting to see:



      widget deletion count (AppDelegate): 1
      widget insertion count (AppDelegate): 0
      widget modification count (AppDelegate): 0

      widget deletion count (View controller): 1
      widget insertion count (View controller): 0
      widget modification count (View controller): 0


      1 deletion in both observation blocks. I'm even more confused now than I was before! ;-)







      ios swift realm






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 8 at 18:48

























      asked Nov 8 at 15:37









      bmt22033

      2,25344575




      2,25344575



























          active

          oldest

          votes











          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













           

          draft saved


          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53211113%2fobserving-changes-to-realm-result-set%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown






























          active

          oldest

          votes













          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes















           

          draft saved


          draft discarded















































           


          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53211113%2fobserving-changes-to-realm-result-set%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

          Crossroads (UK TV series)

          ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế