我正在尝试在关闭SettingViewController之前分配文本字段条目,并在URLViewController出现时检查它们。
但是,一旦我检查它,即使用户输入了所有必需的信息,它也会返回null;
// SettingViewController
partial class SettingViewController : UIViewController
{
public ServerSettings sSettings;
public SettingViewController (IntPtr handle) : base (handle)
{
this.Title = "Settings";
this.sSettings = new ServerSettings();
}
public override void ViewWillDisappear (bool animated)
{
sSettings.server=serverTF.Text;
sSettings.port = portTF.Text;
sSettings.password = passwordTF.Text;
sSettings.userid = inboxuserTF.Text;
sSettings.username = usernameTF.Text;
}
}
// URLViewController
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear (animated);
SettingViewController callSetting = this.Storyboard.InstantiateViewController ("SettingViewController") as SettingViewController;
if (callSetting == null)
throw new Exception("callSetting is null"); // Or if you can handle having a null callSetting then correct for it, but realistically this is a problem, so I'd throw an Exception
if (callSetting.sSettings == null)
throw new Exception("sSetting is null"); // Or if you can handle having a null callSetting.sSetting then correct it (such as using a default value).
if (string.IsNullOrEmpty(callSetting.sSettings.password)==true)
Console.WriteLine("is null or empty");
else
Console.WriteLine (callSetting.sSettings.password);
}
即使用户填写了所有文本字段条目,它也会返回null。 // SettingsViewController
// URLViewController
答案 0 :(得分:1)
我会通过使用字典和&来解决这个问题。 userdefaults如下:
在B Viewcontroller中,将用户条目保留在字典中,映射并将其分配给用户默认。
partial class BViewController : UIViewController
{
const string server = "server";
const string port = "port";
const string password = "password";
const string username = "username";
const string inboxuserid = "inboxuserid";
.............
.............
public override void ViewWillDisappear (bool animated)
{
var appDefaults = new NSDictionary (server, serverTF.Text, port, portTF.Text, password, passwordTF.Text,username,usernameTF.Text, inboxuserid,inboxuserTF.Text);
NSUserDefaults.StandardUserDefaults.RegisterDefaults (appDefaults);
NSUserDefaults.StandardUserDefaults.Synchronize ();
}
}
并在A ViewController中检索它们,如下所示:
partial class AViewController : UIViewController
{
public override void ViewWillAppear(bool animated)
{
NSUserDefaults.StandardUserDefaults.RegisterDefaults (appDefaults);
NSUserDefaults.StandardUserDefaults.Synchronize ();
var username = NSUserDefaults.StandardUserDefaults.StringForKey ("username");
Console.WriteLine (username);
}
}
以下链接中也有很好的例子:
https://github.com/xamarin/monotouch-samples/blob/master/AppPrefs/Settings.cs http://forums.xamarin.com/discussion/9089/nsuserdefaults-standarduserdefaults-returns-null-first-time