笨鸟学iOS开发(2)ApplicationSettings

  • 目的

读写用户偏好



  • 环境

Mac OS X 10.7.2
Xcode4.2



  • 步骤

1:加入用户偏好文件并进行配置

往工程中加入“Settings Bundle”资源文件。
打开“Root.plist”,往其中加入一个“TextField”类型的配置项,并设置其”Identifier“属性值为"password_preference“以便之后在代码中引用,设置其”Text Field Is Secure“属性值为”YES“以便加密字符串。

2:构建界面(相当于写.aspx)

拖放以下控件到MainStoryboard_iPhone.storyboard上:
2个标签用于提示用户
2个文本框用于给用户填写用户名与密码
2个按钮用于载入与保存

3:映射控件(相当于写.aspx.design.cs。在VisualStudio中这一步是自动帮我们完成的)

映射两个文本框的Outlet名分别为txtName与txtPassword。
映射两个按钮的”Touch Up Inside“事件处理函数名分别为loadClicked与saveClicked。

4:写后台代码(相当于写.aspx.cs)

打开ViewController.m文件,将相应的事件处理函数替换为以下代码:

- (IBAction)loadClicked:(id)sender {
    NSUserDefaults* defaults=[NSUserDefaults standardUserDefaults];
    txtName.text=[defaults objectForKey:@"name_preference"];
    txtPassword.text=[defaults objectForKey:@"password_preference"];
    
    UIAlertView* alert=[[UIAlertView alloc]
                        initWithTitle:nil
                        message:@"载入完毕"
                        delegate:self
                        cancelButtonTitle:@"OK"
                        otherButtonTitles:nil];
    [alert show];
}

- (IBAction)saveClicked:(id)sender {
    NSUserDefaults* defaults=[NSUserDefaults standardUserDefaults];
    [defaults setObject:txtName.text
                 forKey:@"name_preference"];
    [defaults setObject:txtPassword.text
                 forKey:@"password_preference"];
    
    UIAlertView* alert=[[UIAlertView alloc]
                        initWithTitle:nil
                        message:@"保存完毕"
                        delegate:self
                        cancelButtonTitle:@"OK"
                        otherButtonTitles:nil];
    [alert show];
}




运行后可以在iOS的“设置”中直接配置此应用的这两个参数。





原文地址:https://www.cnblogs.com/beta2013/p/3377328.html