如何使用NSMutableArray中的数据使用NSUserDefaults保存数据 [英] How to save data with NSUserDefaults using data from NSMutableArray

查看:63
本文介绍了如何使用NSMutableArray中的数据使用NSUserDefaults保存数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 NSMutableArray 在我的.h文件中声明如下

My NSMutableArray is declared in my .h file like this

@property (strong, nonatomic) NSMutableArray * numbers;

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

How do I use the NSMutableArray to save the data that is inputed to save to 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

Ok, in my app, there is a UITableView

当用户点击加号按钮时,UIAlertView显示UITextField,当用户键入单词时,文本将转到UITableView,但当用户退出应用程序时,文本将从表中消失。我想保存用户输入的文本,因此当用户退出应用程序并返回时,我希望文本保存。我想用NSUserDefaults保存它。

when the user taps the "plus" button, a UIAlertView shows up with a UITextField, when the user types a word, the text goes to the UITableView, but when the user exits the app, the text is gone from the table. I want to save the text the user puts in, so when the user exits the app and comes back, i want the text to save. I want to save it with NSUserDefaults.

推荐答案

//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 。对于保存数据,最好在用户最小化应用时收听通知,只需将数据保存为默认值。

According to you scenario when you running application after exiting... you should in viewDidLoad check if the keyExists in the NSUserDefaults then retrieve the results in the array and show in the UITableView. For Saving the Data, it is good idea to listen to a notification when user minimize the app, just save the data into the defaults.

这是您的工作代码case

Here is the working code for your case

- (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];
        }


}

这篇关于如何使用NSMutableArray中的数据使用NSUserDefaults保存数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆