本文介绍了如何使用 NSUserDefaults 从 ViewController 保存数据并在应用程序重新运行时将其检索到 TableViewController的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

ViewController.h:

#import #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;@结尾

ViewController.m

#import "JLSViewController.h"#import "WishlistTableViewController.h"@interface JLSViewController()@property NSMutableArray *wishlistItem;@结尾@implementation JLSViewController- (void)viewDidLoad{[超级viewDidLoad];//在加载视图后做任何额外的设置,通常是从笔尖.}- (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];如果(发件人!= self.addWishListButton)返回;如果(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 = 漂亮版本;}NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];[默认 setObject:self.wishItem.wishlistItem forKey:@"itemWish"];[默认 setObject:self.wishItem.descWishItem forKey:@"itemDesc"];[默认 setObject:self.wishItem.targetDate forKey:@"itemDate"];[默认同步];}- (void)didReceiveMemoryWarning{[超级 didReceiveMemoryWarning];//处理任何可以重新创建的资源.}- (BOOL)textFieldShouldReturn:(UITextField *)textField {[textField resignFirstResponder];返回是;}- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {[self.view endEditing:YES];[super touchesBegan:touches withEvent:event];}@结尾

TableViewController.h

#import #import "DetailViewController.h"@interface WishlistTableViewController : UITableViewController- (IBAction)unwindToWishlistTableViewController:(UIStoryboardSegue *)unwindSegue;@property NSMutableArray *wishlistItem;@结尾

TableViewController.m

#import "WishlistTableViewController.h"#import "WishlistItem.h"#import "JLSViewController.h"#import "DetailViewController.h"@interface WishlistTableViewController ()@结尾@implementation WishlistTableViewController- (id)initWithStyle:(UITableViewStyle)style{self = [super initWithStyle:style];如果(自我){//自定义初始化}回归自我;}- (void)viewDidLoad{[超级viewDidLoad];self.wishlistItem = [[NSMutableArray alloc]init];}- (IBAction)unwindToWishlistTableViewController:(UIStoryboardSegue *)unwindSegue {JLSViewController *source = [unwindSegue sourceViewController];WishlistItem *item = source.wishItem;如果(项目!= nil){[self.wishlistItem addObject:item];[self.tableView reloadData];}}- (IBAction)delete:(id)sender {}- (void)didReceiveMemoryWarning{[超级 didReceiveMemoryWarning];//处理任何可以重新创建的资源.}#pragma mark - 表视图数据源- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{//#warning 可能不完整的方法实现.//返回段数.返回 1;}- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{//#warning 方法实现不完整.//返回部分中的行数.返回 [self.wishlistItem 计数];}- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{静态 NSString *cellIdentifier = @"wishlistCell";UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];WishlistItem *wish = [self.wishlistItem objectAtIndex:indexPath.row];//配置单元格...//设置目标日期字符串NSString *targetDate = [NSString stringWithFormat:@"目标日期:%@", wish.targetDate];//设置心愿单项目字符串NSString *wishItemString = wish.wishlistItem;cell.textLabel.text = WishItemString;cell.detailTextLabel.text = targetDate;返回单元格;}/*#pragma mark - 导航//在基于故事板的应用程序中,您通常需要在导航前做一些准备工作- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{//使用 [segue destinationViewController] 获取新的视图控制器.//将选中的对象传递给新的视图控制器.}*/-(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 动画:YES];}//删除行/单元格- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{//从数据模型中删除行[self.wishlistItem removeObjectAtIndex:indexPath.row];//请求重新加载表格视图[tableView reloadData];}@结尾

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

我在我的 prepareForSegue 中使用了 NSUserDefaults.但我认为我无法从 TableViewController 中正确检索它.

我只使用 NSUserDefaults 包含了我的保存数据",因为我不知道如何将加载数据"实现到我的 TableViewController.

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

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

解决方案

@Rhenzzz : 你必须更换这个

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

cell.textLabel.text = itemWish ;cell.detailTextLabel.text = itemDate;

在 Jay 的代码中.

I'm desperate, been solving this for hours.. So I have a class "WishListItem", a TableViewController and a ViewController. I'm having difficulties in saving chunk of data and retrieving it from TableViewController? How to do this effectively?

I'm going to paste all my codes because I don't know if there something important that must be included to my question. So I'm sorry, please bear with me. Here it is.

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

From my ViewController, i want to save every entries that's being added and retrieve it later to my TableViewController. Thank you and I'm really sorry for posting all my codes because I'm really frustrated already, been solving this for several hours. Thank you in advance.

I've used NSUserDefaults in my prepareForSegue. But I think I can't retrieve it properly from my TableViewController.

I've included my "Saving Data" only using NSUserDefaults because I don't know how I will implement the "Loading Data" to my TableViewController.

I'm sorry for my code. Just a beginner for now.

My only goal is just to save my 3 strings(Wish Item, Wish Description, Target Date) and I just want to retrieve those data every time the app reruns..

解决方案

@Rhenzzz : you have to replace this

by

in Jay's code.

这篇关于如何使用 NSUserDefaults 从 ViewController 保存数据并在应用程序重新运行时将其检索到 TableViewController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 21:39