如何使用NSUserDefaults从ViewController保存数据并在app重新运行时将其检索到TableViewController

时间:2014-05-07 14:38:23

标签: ios objective-c uitableview nsuserdefaults

我很绝望,已经解决了好几个小时..所以我有一个类“WishListItem”,一个TableViewController和一个ViewController。我在保存数据块并从TableViewController中检索数据时遇到了困难?如何有效地做到这一点?

我要粘贴我的所有代码,因为我不知道是否有重要内容必须包含在我的问题中。所以我很抱歉,请耐心等待。在这里。

ViewController.h:

#import <UIKit/UIKit.h>
#import "WishlistItem.h"

@interface JLSViewController : UIViewController
@property (strong, nonatomic) IBOutlet UIBarButtonItem *addWishListButton;
@property (strong, nonatomic) IBOutlet UITextField *wishTextField;
@property (strong, nonatomic) IBOutlet UITextField *descTextField;
@property (strong, nonatomic) IBOutlet UIDatePicker *targetDatePicker;

@property WishlistItem *wishItem;

@end

ViewController.m

#import "JLSViewController.h"
#import "WishlistTableViewController.h"

@interface JLSViewController ()

@property NSMutableArray *wishlistItem;

@end

@implementation JLSViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    NSDate *myDate = self.targetDatePicker.date;
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"MMM d, YYYY"];
    NSString *prettyVersion = [dateFormat stringFromDate:myDate];

    if (sender != self.addWishListButton) return;
    if (self.wishTextField.text.length > 0) {
        self.wishItem = [[WishlistItem alloc] init];
        self.wishItem.wishlistItem  = self.wishTextField.text;
        self.wishItem.descWishItem = self.descTextField.text;
        self.wishItem.targetDate = prettyVersion;
    }
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:self.wishItem.wishlistItem forKey:@"itemWish"];
    [defaults setObject:self.wishItem.descWishItem forKey:@"itemDesc"];
    [defaults setObject:self.wishItem.targetDate forKey:@"itemDate"];
    [defaults synchronize];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
    [super touchesBegan:touches withEvent:event];
}

@end

TableViewController.h

#import <UIKit/UIKit.h>
#import "DetailViewController.h"

@interface WishlistTableViewController : UITableViewController

- (IBAction)unwindToWishlistTableViewController:(UIStoryboardSegue *)unwindSegue;


@property NSMutableArray *wishlistItem;


@end

TableViewController.m

#import "WishlistTableViewController.h"
#import "WishlistItem.h"
#import "JLSViewController.h"
#import "DetailViewController.h"

@interface WishlistTableViewController ()



@end

@implementation WishlistTableViewController


- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.wishlistItem = [[NSMutableArray alloc]init];


}

- (IBAction)unwindToWishlistTableViewController:(UIStoryboardSegue *)unwindSegue {

    JLSViewController *source = [unwindSegue sourceViewController];
    WishlistItem *item = source.wishItem;
    if (item != nil) {
        [self.wishlistItem addObject:item];
        [self.tableView reloadData];
    }
}

- (IBAction)delete:(id)sender {

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return [self.wishlistItem count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *cellIdentifier = @"wishlistCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    WishlistItem *wish = [self.wishlistItem objectAtIndex:indexPath.row];

    // Configure the cell...
    //Set target date string
    NSString *targetDate = [NSString stringWithFormat:@"Target Date: %@", wish.targetDate];

    //Set wishlist item string
    NSString *wishItemString = wish.wishlistItem;

    cell.textLabel.text = wishItemString;
    cell.detailTextLabel.text = targetDate;

    return cell;
}

/*
 #pragma mark - Navigation

 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    WishlistItem *wish = [self.wishlistItem objectAtIndex:indexPath.row];
    DetailViewController *dvc = [self.storyboard instantiateViewControllerWithIdentifier:@"dvcID"];

    dvc.wishItemStr = wish.wishlistItem;
    dvc.dateItemStr = wish.targetDate;
    dvc.descItemStr = wish.descWishItem;


    [self.navigationController pushViewController:dvc animated:YES];
}




// Delete row/cell
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Remove the row from data model
    [self.wishlistItem removeObjectAtIndex:indexPath.row];

    // Request table view to reload
    [tableView reloadData];
}

@end

从我的ViewController中,我想保存所有正在添加的条目,并稍后将其检索到我的TableViewController。谢谢,我真的很抱歉发布我的所有代码,因为我已经非常沮丧,已经解决了几个小时。提前谢谢。

我在prepareForSegue中使用过NSUserDefaults。但我想我无法从我的TableViewController中正确检索它。

我仅使用NSUserDefaults包含了我的“保存数据”,因为我不知道如何将“加载数据”实现到我的TableViewController。

我很抱歉我的代码。现在只是个初学者。

我唯一的目标就是保存我的3个字符串(Wish Item,Wish Description,Target Date),我只想在每次应用重新运行时检索这些数据。

4 个答案:

答案 0 :(得分:1)

-(void)yourSaveMethod
 { 
   NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
   [defaults setValue:@"My saved Data" forKey:@"infoString"];
 }

 -(void)yourLoadMethod
 {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    cell.tableview.text = [defaults objectForKey:@"infoString"];
 }``

答案 1 :(得分:0)

要保存阵列状态,请使用此视图,即在视图控制器中

NSString *valueToSave = @"someValue";
[[NSUserDefaults standardUserDefaults] setObject:valueToSave forKey:@"preferenceName"];
[[NSUserDefaults standardUserDefaults] synchronize];

在想要检索变量的地方使用它。 intableViewController

 NSString *savedValue = [[NSUserDefaults standardUserDefaults]
            stringForKey:@"preferenceName"];

答案 2 :(得分:0)

我也会推荐Core Data。

但是,如果您真的想使用NSUserDefaults,则应该在一个密钥中保留NSArrayNSDictionary个。您现在的行事方式是,您每次UITableView只能显示一个项目,因为每次prepareForSegue时都会覆盖相同的键。

将其放在单独的头文件中并在必要时导入:

#define WISH_ITEMS_KEY @"wishItems"

执行此代码一次(可能在AppDelegate中这样):

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults registerDefaults:@{WISH_ITEMS_KEY: @[]}];
    [defaults synchronize];
    return YES;
}

然后在prepareForSegue

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *wishItems = [[defaults arrayForKey:WISH_ITEMS_KEY] mutableCopy];
[wishItems addObject:@{@"itemWish": self.wishItem.wishlistItem,
                       @"itemDesc": self.wishItem.descWishItem,
                       @"itemDate": self.wishItem.targetDate}];
[defaults setObject:wishItems forKey:WISH_ITEMS_KEY];
[defaults synchronize];

TableViewController的{​​{1}}:

viewDidLoad

然后在NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; self.wishlistItem = [[defaults arrayForKey:WISH_ITEMS_KEY] mutableCopy]; 中,您可以检索每个项目并设置您的单元格:

cellForRowAtIndexPath

希望有所帮助。

答案 3 :(得分:0)

@Rhenzzz:你必须替换这个

cell.textLabel.text = wishItemString; 
cell.detailTextLabel.text = targetDate;

通过

cell.textLabel.text = itemWish ; 
cell.detailTextLabel.text = itemDate;
杰伊的代码中的