对象引用未设置到 xamarin ios 应用程序组中对象的实例

Object reference not set to an instance of an object in xamarin ios app group

我正在尝试在 Xamarin 中构建今天的小部件。 在模拟器中一切正常,但是当我 运行 它在真实设备上时,我的小部件崩溃并出现以下异常:

object reference not set to an instance of an object.

我的代码是:

var defs = new NSUserDefaults("group.com.gto.extension", NSUserDefaultsType.SuiteName);
defs.Synchronize(); 

var equities = defs.ValueForKey(new NSString("key1"));--> this row crashes my widget.

尝试访问单个应用程序或一组应用程序的 NSUserDefaults 之间存在差异。后者是您目前正在努力实现的目标。我将在这个答案中尝试总结两种策略之间的区别。

应用组用户默认设置

我假设您正在尝试从您创建的另一个应用程序或扩展中读取 NSUserDefaults 中的条目?只有在这种情况下,使用给定的 NSUserDefaults 才是明智的。如果是这样,您需要确保以下几点:

First, you will need to ensure that the App Group and the required App IDs have been properly configured in the Certificates, Identifiers & Profiles section on iOS Dev Center and have been installed on in the development environment.

Next, your App and/or Extension projects will need to be one of the valid App IDs created above, that the Entitlements.plist file has the App Groups enabled and specified and that it get's included in the App Bundle.

With this all in place, the shared App Group user Defaults can be accessed [...]

https://developer.xamarin.com/guides/ios/application_fundamentals/user-defaults/#Accessing_an_App_Group_NSUserDefaults_Instance

以上两点可能是您的应用程序崩溃的原因。

单应用程序用户默认设置

另一方面,如果您只需要从当前应用程序的 NSUserDefaults 访问一个值,您可以简单地执行以下操作:

var defs = NSUserDefaults.StandardUserDefaults;

读取值

要从 NSUserDefaults 中读取值,如 guide and documentation 中所示,您应该执行以下操作:

var boolForKey = defs.BoolForKey("key");
var stringForKey = defs.StringForKey("key");
....

其中 "key" 参数是您之前存储在 NSUserDefaults 词典中的 valuekey

将任何从 NSUserDefaults 检索值的调用包围在 try/catch 中也很可能是明智的。 key 可能还不存在于 NSUserDefaults 中,这很可能是您遇到的问题。