为什么NSUserDefault不能与我的字典对象一起使用?

时间:2013-12-04 05:47:37

标签: objective-c

我为make think用户创建了一个存储用户名和密码的对象,然后我将该对象放入字典中。现在我正在尝试使用NSUserDefault存储字典,但它不让我。我理解最好不要使用NSUserDefault存储用户数据,但这只是我想学习的初学者。

/**interface file **/
#import "newUser.h"

@interface BWViewController : UIViewController
{

    IBOutlet UITextField *userNameField;
    IBOutlet UITextField *passwordField;
    IBOutlet UILabel * loginStatus;

}

@property (nonatomic, copy) NSDictionary * aUser;

-(IBAction)signUpButton;

@end


/**implementation file**/


@interface BWViewController ()

@end

@implementation BWViewController

@synthesize aUser;

- (void)viewDidLoad
{
    [super viewDidLoad];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

-(IBAction) signUpButton
{

    newUser * firstUser = [[newUser alloc] init];
    firstUser.userName = userNameField.text;
    firstUser.password = passwordField.text;

    NSLog(@"%@", firstUser.userName);  /**for testing**/
    NSLog(@"%@", firstUser.password);  /**for testing**/

    aUser = [[NSDictionary alloc] initWithObjects:[NSArray arrayWithObjects:firstUser, nil] forKeys:[NSArray arrayWithObjects:userNameField.text, nil]];

    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];

    [defaults setObject:aUser forKey:userNameField.text];
    [defaults synchronize];

    loginStatus.text = @"Thanks for signing up!";

}

1 个答案:

答案 0 :(得分:0)

更好的方法是存储两个用户默认值,一个用于用户名,另一个用于密码:

NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];

[defaults setObject:firstUser.userName forKey:@"USERNAME"];
[defaults setObject:firstUser.password forKey:@"PASSWORD"];

[defaults synchronize];

它不起作用,因为您希望将nsdictionary与nsarray一起存储为自定义对象(firstUser),但NSUserDefaults不允许您存储自定义对象。 希望这个帮助

//扩展

saveForKey:newUseFromKey:我的意思是:

+(void)saveForKey:(NSString*)key
{
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];

    [defaults setObject:self.userName forKey:[NSString stringWithFormat:@"%@_USERNAME", key]];
    [defaults setObject:self.password forKey:[NSString stringWithFormat:@"%@_PASSWORD", key]];
    //.... other properties

    [defaults synchronize];
}

+(newUser)newUseFromKey:(NSString*)key
{
    newUser * user = [[newUser alloc] init];
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    user.userName = [defaults objectForKey:[NSString stringWithFormat:@"%@_USERNAME", key]];
    user.password = [defaults objectForKey:[NSString stringWithFormat:@"%@_PASSWORD", key]];
    //.... other properties
    return user;

}

如果您没有存储太多的newUser对象并且它们没有太多属性,那么这是一个很好的解决方案。 最好的选择是将你的所有对象都放到数组/字典中(这取决于你,这两者之间没有最佳选择)并将其保存到文件中。请记住,如果要将自定义对象保存到文件系统,则必须实现NSCoding协议。