将bool保存到NSUserDefaults

时间:2017-03-08 17:11:26

标签: c# xamarin xamarin.ios

我得到了非常有趣的异常。首先看它很简单,但是当我看到异常的堆栈跟踪时,我无法弄清楚我做错了什么。

我在PCL中拥有将值保存到NSUserDefaults的属性。代码看起来像

public class MainSettingsService : IMainSettingsService
{
        readonly ISettingsBaseService _settingsBaseService;

        public MainSettingsService(ISettingsBaseService settingsBaseService)
        {
            _settingsBaseService = settingsBaseService;
        }

        public bool NotificationEnabled
        {
            get { return _settingsBaseService.Get(true); }
            set { _settingsBaseService.Set(value); }
        }
}

SettingsBaseService课很简单

    public class iOSSettingsBaseService : ISettingsBaseService
    {
        private const string NULL = "!NULL";
        private readonly NSUserDefaults _preferences;

        public iOSSettingsBaseService()
        {
            _preferences = NSUserDefaults.StandardUserDefaults;
        }

        public void Set<T>(T value, [CallerMemberNameAttribute] string key = "")
        {
            var str = JsonConvert.SerializeObject(value);
            _preferences.SetString(str ?? NULL, key);
        }

        public T Get<T>(T defaultValue = default(T), [CallerMemberNameAttribute] string key = "")
        {
            var str = _preferences.StringForKey(key);
            if (str == NULL || string.IsNullOrEmpty(str))
            {
                return defaultValue;
            }
            var obj = JsonConvert.DeserializeObject<T>(str);
            return obj;
        }
    }

一切都很简单,但有时在发布时我会在hockeyapp上遇到跟踪堆栈跟踪的崩溃

[String bzero_aligned_8(System.Byte* dest, System.Int32 len)]
System.NullReferenceException: Object reference not set to an instance of an object
at System.String.bzero_aligned_8(byte* dest, int len)
at First.iOS.Services.iOSSettingsBaseService.Set<T>(T value, string key)
at First.Core.Services.Implementations.MainSettingsService.set_NotificationEnabled(bool value)

所以现在我真的很好奇,怎么可以在System.String中进行null引用?这是Mono的错误吗?此异常随机触发,很少发生。刚刚赶上iPhone 4s和iPhone 5s。我只为两个ARM64和ARMv7构建。 寻找任何建议。

0 个答案:

没有答案