【问题标题】:How to save data with NSUserDefaults using data from NSMutableArray如何使用 NSMutableArray 中的数据使用 NSUserDefaults 保存数据
【发布时间】:2013-03-13 20:59:57
【问题描述】:

我的NSMutableArray 像这样在我的.h 文件中声明

@property (strong, nonatomic) NSMutableArray * numbers;

如何使用NSMutableArray将输入的数据保存到NSUserDefaults

感谢所有帮助

提前致谢

.h 文件中的代码

@property (retain, nonatomic) IBOutlet UITableView *myTableView;
@property (strong, nonatomic) NSMutableArray * numbers;

.m 中的代码

@synthesize myTableView, numbers;

-(void) viewDidLoad
{

    NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
    [defaults setObject:numbers forKey:@"numberArray"];

    NSMutableArray *resultArray = [NSMutableArray arrayWithArray:[defaults objectForKey:@"numberArray"]];



    [super viewDidLoad];
    // instantiate our NSMutableArray
    numbers = [[NSMutableArray alloc]initWithObjects:@"",@"", nil];






    //Add a edit button
    self.navigationItem.leftBarButtonItem = self.editButtonItem;

    //Add the Add button
    UIBarButtonItem * addButton = [[UIBarButtonItem alloc]
                                   initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target: self action: @selector(insertNewObject)];

    self.navigationItem.rightBarButtonItem = addButton;

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

}

-(void)setEditing:(BOOL)editing animated:(BOOL)animated
{

    [super setEditing:editing animated:animated];
    [myTableView setEditing:editing animated:animated];




}


-(void) insertNewObject
{

    //Display a UIAlertView
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Enter HomeWork" message: @"" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok", nil];


    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    [alert show];

}



#pragma mark - UITableView Datasource

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return numbers.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIdentifier = @"cell";

    UITableViewCell *cell = [ tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    if(cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault
                                      reuseIdentifier: cellIdentifier];
    }

    cell.textLabel.text = [numbers objectAtIndex:indexPath.row];

    return cell;
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;

}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        //remove our NSMutableArray
        [numbers removeObjectAtIndex:indexPath.row];
        //remove from our tableView
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }


}


#pragma mark - UITableView Delegate methods


#pragma mark - UIAlertViewDelegate Methods


-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //Only perform the following actions if the user hits the ok button
    if (buttonIndex == 1)
    {
        NSString * tmpTextField = [alertView textFieldAtIndex:0].text;



        if(!numbers)

            numbers = [[NSMutableArray alloc]init];




    [numbers insertObject:tmpTextField atIndex:0];



        NSIndexPath * indexPath = [NSIndexPath indexPathForRow:0 inSection:0];

        [self.myTableView insertRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationAutomatic];



        }



}


@end

好的,在我的应用中,有一个 UITableView

当用户点击“加号”按钮时,UIAlertView 会显示一个 UITextField,当用户键入一个单词时,文本会转到 UITableView,但是当用户退出应用程序时,文本会从表格中消失.我想保存用户输入的文本,所以当用户退出应用程序并返回时,我希望保存文本。我想用 NSUserDefaults 保存它。

【问题讨论】:

    标签: ios objective-c nsuserdefaults


    【解决方案1】:
    //For saving 
    NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
    [defaults setObject:self.numbers forKey:@"numberArray"];
    [defaults synchronize];
    
    //For retrieving  
    NSMutableArray *resultArray = [NSMutableArray arrayWithArray:[defaults objectForKey:@"numberArray"]];
    

    根据您在退出后运行应用程序的情况...您应该在viewDidLoad 检查NSUserDefaults 中的keyExists 是否存在,然后检索数组中的结果并显示在UITableView 中。对于保存数据,最好在用户最小化应用程序时听取通知,只需将数据保存到默认值即可。

    这是您案例的工作代码

    - (void)viewDidLoad{
    
       [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
        //Add a edit button
       self.navigationController.navigationItem.leftBarButtonItem = self.editButtonItem;
    
      // check here if key exists in the defaults or not, if yes the retrieve results in array
      if([[NSUserDefaults standardUserDefaults] objectForKey:@"numberArray"] != nil) {
       self.numbers = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"numberArray"]];
    
    }
    
       //Register for the notification when user go to background or minimize the app, just save the array objects in the defaults
    
    [[NSNotificationCenter defaultCenter]   addObserver:self
                                                       selector:@selector(appWillGoToBackground:)
                                                           name:UIApplicationWillResignActiveNotification
                                                         object:[UIApplication sharedApplication]];
    
    
    
        //Add the Add button
    UIBarButtonItem * addButton = [[UIBarButtonItem alloc]
                                   initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target: self action: @selector(insertNewObject)];
    
    self.navigationController.navigationItem.rightBarButtonItem = addButton;
    }
    
    -(void)setEditing:(BOOL)editing animated:(BOOL)animated {
        [super setEditing:editing animated:animated];
        [self.myTableView setEditing:editing animated:animated];
    
    }
    -(void)appWillGoToBackground:(NSNotification *)note {
        NSLog(@"terminate");
    
        NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
        [defaults setObject:self.numbers forKey:@"numberArray"];
        [defaults synchronize];
    
    }
    
    -(void)insertNewObject{
            //Display a UIAlertView
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Enter HomeWork" message: @"" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok", nil];
    
    
        alert.alertViewStyle = UIAlertViewStylePlainTextInput;
        [alert show];
    
    
    }
    
    -(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
    {
            //Only perform the following actions if the user hits the ok button
        if (buttonIndex == 1)
            {
            NSString * tmpTextField = [alertView textFieldAtIndex:0].text;
    
    
    
            if(!self. numbers){
    
                self.numbers = [[NSMutableArray alloc]init];
            }
    
    
    
            [self.numbers insertObject:tmpTextField atIndex:0];
    
    
    
            NSIndexPath * indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    
            [self.myTableView insertRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationAutomatic];
    
    
    
    
    }
    
    
    
    -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
        return 1;
    }
    
    -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
        return self.numbers.count;
    }
    
    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
        static NSString *cellIdentifier = @"cell";
    
        UITableViewCell *cell = [ tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
        if(cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault
                                          reuseIdentifier: cellIdentifier];
        }
    
        cell.textLabel.text = [self.numbers objectAtIndex:indexPath.row];
    
        return cell;
    }
    
    -(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
    {
        return YES;
    
    }
    
    -(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
    {
        if (editingStyle == UITableViewCellEditingStyleDelete)
            {
                //remove our NSMutableArray
            [self.numbers removeObjectAtIndex:indexPath.row];
                //remove from our tableView
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
            }
    
    
    }
    

    【讨论】:

    • 感谢您正确地制作了一个新的可变数组,而不是假设原始的可变数组在您取回时仍然是可变的:)
    • 我要把它放在 .m 文件中的任何地方吗?
    • 用户点击加号按钮并输入一些文本并被添加到表格视图中,我使用 NSMutableArray 来识别文本。我如何保存它
    • 您要先在数组中添加数据吗?这就是你想要的?
    • 当我关闭并打开应用程序时,我之前输入的文字不见了
    猜你喜欢
    • 2013-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-24
    • 2013-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多