Beispiel #1
0
 /// <summary>
 /// Adds the prefernce specifier observer.
 /// </summary>
 /// <param name="defaults">Defaults.</param>
 /// <param name="action">Action.</param>
 public static void AddPrefernceSpecifierObserver(this NSUserDefaults defaults, Action action)
 {
     defaults.AddObserver("PreferenceSpecifiers", NSKeyValueObservingOptions.New, (observedChange) =>
     {
         action?.Invoke();
     });
 }
Beispiel #2
0
        // createInitialData
        //
        // The Swift version of this app has a createInitialData method.
        // Each child class of the DataManager class overrides this method, and
        // then the DataManager base class calls the derived versions to get
        // the initial data. C# gives a compiler warning for this ("Virtual
        // member call in constructor"). Since in C# the base class constructor
        // is run before the child class constructor, having the base clas
        // constructor call out to a method on the derived class is calling
        // a method on an object that has not yet been fully constructed.
        // The C# version of this sample works around this problem by passing
        // in the initial data to the constructor.

        void ObserveChangesInUserDefaults()
        {
            var weakThis = new WeakReference <DataManager <ManagedDataType> >(this);
            Action <NSObservedChange> changeHandler = (change) =>
            {
                if (weakThis.TryGetTarget(out var dataManager))
                {
                    // Ignore any change notifications coming from data this
                    // instance just saved to `NSUserDefaults`.
                    if (dataManager is null || dataManager.IgnoreLocalUserDefaultsChanges)
                    {
                        return;
                    }

                    // The underlying data changed in `NSUserDefaults`, so
                    // update this instance with the change and notify clients
                    // of the change.
                    dataManager.LoadData();
                    dataManager.NotifyClientsDataChanged();
                }
            };

            UserDefaultsObserver = UserDefaults.AddObserver(
                StorageDescriptor.Key,
                NSKeyValueObservingOptions.Initial | NSKeyValueObservingOptions.New,
                changeHandler
                );
        }

        // Notifies clients the data changed by posting an `NSNotification` with
        // the key `NotificationKeys.DataChanged`
        void NotifyClientsDataChanged()
        {
            var notification = NSNotification.FromName(NotificationKeys.DataChanged, this);

            NSNotificationCenter.DefaultCenter.PostNotification(notification);
        }