在Xcode中保存来自多个文本字段的数据时出现问题

时间:2014-02-13 23:18:00

标签: ios objective-c

我是Xcode的新手,所以我为任何明显的错误道歉。

我正在构建一个简单的应用程序,其中包括使用NSUserDefaults从多个文本字段中保存数据并将它们填充到表格视图中。

第一个文本字段(tField)保存得很好(也用于填充工作正常的表视图)。我试图包含第二个(tField2)并且在输入时它没有将数据保存到正确的位置,此时代码实际上将数据从第一个字段保存到第二个字段并删除输入到第二个字段中的任何内容。 / p>

这是一些代码,我认为最好的风险包括太多而不是太少。如果需要,我会提供任何进一步的信息,非常感谢!

Appdelegate.m

#import "AppDelegate.h"
#import "Data.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    [Data getAllNotes];
    return YES;
}

Masterview.m

#import "MasterViewController.h"
#import "DetailViewController.h"
#import "Data.h"

@interface MasterViewController () {
    NSMutableArray *_objects;
}
@end

@implementation MasterViewController

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

    UIBarButtonItem *addButton = [[UIBarButtonItem alloc]
                                  initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self
                                  action:@selector(insertNewObject:)];
    self.navigationItem.rightBarButtonItem = addButton;
}

-(void)viewWillAppear:(BOOL)animated
{
    ///This ensures the re-generation of list items in Table View after new saves or edits.
    [super viewWillAppear:animated];
    [self makeObjects];
    [self.tableView reloadData];
}

-(void)makeObjects
{
    ///This ensures list is generated in order of creation date & time.
    _objects = [NSMutableArray arrayWithArray:[[Data getAllNotes] allKeys]];
    [_objects sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [(NSDate *)obj2 compare:(NSDate *)obj1];
    }];
}

- (void)insertNewObject:(id)sender
{
    [self makeObjects];
    NSString *key = [[NSDate date] description];
    [Data setNote:kDefaultText forKey:key];
    [Data setCurrentKey:key];
    [_objects insertObject:key atIndex:0];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.tableView insertRowsAtIndexPaths:@[indexPath]
                          withRowAnimation:UITableViewRowAnimationAutomatic];
    ///Enables transition to Detail View when New Object is created.
    [self performSegueWithIdentifier:kDetailView sender:self];
}

#pragma mark - Table View

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

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"
                                                            forIndexPath:indexPath];

    NSDate *object = _objects[indexPath.row];
    ///This determines which data is used to generate cell title in Table View.
    cell.textLabel.text = [[Data getAllNotes] objectForKey:[object description]];
    return cell;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:
(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        ///This controls Editing Style of how Notes are deleted.
        [Data removeNoteForKey:[_objects objectAtIndex:indexPath.row]];
        [Data saveNotes];
        [_objects removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:@[indexPath]
                         withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add
        a new row to the table view.
    }
}

Detailview.h

#import <UIKit/UIKit.h>

@interface DetailViewController : UIViewController

@property (strong, nonatomic) id detailItem;
///This links UI elements to code.
@property (weak, nonatomic) IBOutlet UITextField *tField;
///Edited from original to include price field.
@property (weak, nonatomic) IBOutlet UITextField *tField2;

@end

Detailview.m

@synthesize tField;
///Edited from original to include price field.
@synthesize tField2;

#pragma mark - Managing the detail item

- (void)setDetailItem:(id)newDetailItem
{
    if (_detailItem != newDetailItem) {
        _detailItem = newDetailItem;
        [Data setCurrentKey:_detailItem];
        // Update the view.
        [self configureView];
    }
}

- (void)configureView
{
    NSString *currentNote = [[Data getAllNotes] objectForKey:[Data getCurrentKey]];
    if (![currentNote isEqualToString:kDefaultText]) {
        self.tField.text = currentNote;
    }
    else {
        self.tField.text = @"";
    }

    ///Edited from original. (Result: saves data from field1 in field2)

    NSString *currentNote2 = [[Data getAllNotes] objectForKey:[Data getCurrentKey]];
    if (![currentNote2 isEqualToString:kDefaultText]) {
        self.tField2.text = currentNote2;
    }
    else {
        self.tField2.text = @"";
    }

    ///This is what initalizes keyboard upon entry.
    [self.tField becomeFirstResponder];
}

-(void)viewWillDisappear:(BOOL)animated
{
    if (![self.tField.text isEqualToString:@""]) {
        [Data setNoteForCurrentKey:self.tField.text];
    }
    else {
        [Data removeNoteForKey:[Data getCurrentKey]];
    }
    [Data saveNotes];
}

1 个答案:

答案 0 :(得分:-1)

您的viewWillAppear仅保存第一个数据。

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (![self.tField.text isEqualToString:@""]) {
        //SET THE CURRENT KEY HERE
        [Data setNoteForCurrentKey:self.tField.text];
    }
    else {
        //SET THE CURRENT KEY HERE
        [Data removeNoteForKey:[Data getCurrentKey]];
    }

    if (![self.tField2.text isEqualToString:@""]) {
        //SET THE CURRENT KEY HERE
        [Data setNoteForCurrentKey:self.tField2.text];
    }
    else {
        //SET THE CURRENT KEY HERE
        [Data removeNoteForKey:[Data getCurrentKey]];
    }
    [Data saveNotes];

}

还有一个问题就是你只有一个细节项目。这意味着你只有一个指向第二个项目的指针(它将保持你的currentNote。为了解决这个问题,你需要有两个detailItem属性(一个用于第一个音符,一个用于第二个。然后,当你保存时)注意,设置正确的一个以激活。