将 UITextView 中的文本保存到 NSUserDefaults 中的方式与将 UITextFIeld 保存在 Notes 应用程序中的方式相同
Posted
技术标签:
【中文标题】将 UITextView 中的文本保存到 NSUserDefaults 中的方式与将 UITextFIeld 保存在 Notes 应用程序中的方式相同【英文标题】:Saving text from a UITextView into NSUserDefaults the same way a UITextFIeld is saved in a Notes app 【发布时间】:2014-08-13 02:19:55 【问题描述】:我是 Objective-C 的新手,但有一些编程知识。所以我按照 Todd Perkin 的教程在 Lynda.com 上制作笔记应用程序。为了更熟悉 Objective-C,我想在这个笔记应用程序中添加一些东西以了解更多信息,但我有点卡住了。
目前,notes 应用程序内置在 Master Detail 应用程序模板中。所以MasterDetailView控制器中有一个Table View,DetailViewController中有一个detail view。当用户点击添加按钮时,它会转到 Detail 控制器,并且有一个您可以输入的 UITextField,当您单击 Back 时,它会将 UITextField 保存到 NSUserDefaults,这就是用于填充表格视图中的单元格的内容。
所以基本上,我所做的是为详细视图中的另一个位置添加一个 UITextView。但我想不出保存笔记标题的最佳方式。显然,每个音符都需要不同。这是我正在使用的类和代码:
MasterDetailController.h
#import <UIKit/UIKit.h>
@interface MasterViewController : UITableViewController
@end
MasterDetailController.m
@interface MasterViewController ()
NSMutableArray *_objects;
@end
@implementation MasterViewController
- (void)awakeFromNib
[super awakeFromNib];
- (void)viewDidLoad
[super viewDidLoad];
[self makeObjects];
// Do any additional setup after loading the view, typically from a nib.
//self.navigationItem.leftBarButtonItem = self.editButtonItem;
self.navigationController.navigationBar.titleTextAttributes = @NSForegroundColorAttributeName : [UIColor whiteColor];
self.navigationItem.titleView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Logo-Small.png"]];
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(insertNewObject:)];
self.navigationItem.rightBarButtonItem = addButton;
-(void)viewDidAppear:(BOOL)animated
[super viewWillAppear:animated];
[self makeObjects];
[self.tableView reloadData];
-(void)makeObjects
_objects = [NSMutableArray arrayWithArray:[[Data getAllNotes]allKeys]];
//Sorts notes by order they were created in
[_objects sortUsingComparator:^NSComparisonResult(NSDate * obj1, NSDate * obj2)
return [obj2 compare:obj1];
];
- (void)didReceiveMemoryWarning
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
- (void)insertNewObject:(id)sender
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];
[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];
NSString *object = _objects[indexPath.row];
cell.textLabel.text = [[Data getAllNotes]objectForKey:object];
return cell;
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
// Return NO if you do not want the specified item to be editable.
return YES;
- (void)tableView:(UITableView *)tableView commitEditingStyle: (UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
if (editingStyle == UITableViewCellEditingStyleDelete)
[Data removeNoteForKey:[_objects objectAtIndex:indexPath.row]];
[Data saveNote];
[_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.
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
// Return NO if you do not want the item to be re-orderable.
return YES;
*/
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
if ([[segue identifier] isEqualToString:@"showDetail"])
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
NSString *object = _objects[indexPath.row];
[[segue destinationViewController] setDetailItem:object];
@end
DetailViewController.h
#import <UIKit/UIKit.h>
@interface DetailViewController : UIViewController
@property (strong, nonatomic) id detailItem;
@property (weak, nonatomic) IBOutlet UITextView *rTView;
@property (weak, nonatomic) IBOutlet UITextField *tView;
@end
DetailViewController.m
#import "DetailViewController.h"
#import "Data.h"
@interface DetailViewController ()
- (void)configureView;
@end
@implementation DetailViewController
#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 getAllNote]objectForKey:[Data getCurrentKey]];
if (![currentNote isEqualToString:kDefaultText])
self.tView.text = currentNote;
else
self.tView.text = @"";
//Brings up the keyboard when you go into a note
//[self.tView becomeFirstResponder];
-(void) viewDidDisappear:(BOOL)animated
[super viewWillDisappear:animated];
if (![self.tView.text isEqualToString:@""])
[Data setNoteForCurrentKey:self.tView.text];
else
[Data removeNoteForKey:[Data getCurrentKey]];
[Data saveNotes];
- (void)viewDidLoad
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self configureView];
[[UITextField appearance] setTintColor:[UIColor orangeColor]];
self.rTView.tintColor = [UIColor orangeColor];
- (void)didReceiveMemoryWarning
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
-(UIStatusBarStyle)preferredStatusBarStyle
return UIStatusBarStyleLightContent;
@end
以及教程中的数据模型:
数据.h
#import <Foundation/Foundation.h>
#define kDefaultText @"New Note"
#define kAllNote @"notes"
#define kDetailView @"showDetail"
@interface Data : NSObject
+(NSMutableDictionary *)getAllNotes;
+(void)setCurrentKey: (NSString *)key;
+(NSString *)getCurrentKey;
+(void)setNoteForCurrentKey:(NSString*)note;
+(void)setNote:(NSString*)note forKey:(NSString*)key;
+(void)removeNoteForKey:(NSString*)key;
+(void)saveNotes;
@end
数据.m
@implementation Data
static NSMutableDictionary *allNotes=nil;
static NSString *currentKey=nil;
+(NSMutableDictionary *)getAllNotes
if (allNotes == nil)
allNotes = [[NSMutableDictionary alloc]initWithDictionary:[[NSUserDefaults standardUserDefaults]objectForKey:kAllNotes]];
return allNotes;
+(void)setCurrentKey: (NSString *)key
currentKey = key;
+(NSString *)getCurrentKey
return currentKey;
+(void)setNoteForCurrentKey:(NSString*)note
[self setNote:note forKey:currentKey];
+(void)setNote:(NSString*)note forKey:(NSString*)key
[allNotes setObject:note forKey:key];
+(void)removeNoteForKey:(NSString*)key
[allNotes removeObjectForKey:key];
+(void)saveNotes
[[NSUserDefaults standardUserDefaults]setObject:allNotes forKey:kAllNotes];
@end
呸。对不起。这是很多代码。所以 tView 是被保存的值。我已将 UITextView 定义为 rTView。但我不知道如何像为 UITextFIeld 所做的那样,为每个注释保存该文本视图。
我将不胜感激。请。
【问题讨论】:
【参考方案1】:这个想法是,现在您将为每个节点保存更多属性,并且它们应该聚集在一个集合中,例如 NSArray、NSDictionary 等。但是,要回答您的问题需要很多时间,我要去仅提供一些提示:
您需要先更改您的模型类,以包含您需要的所有属性。 在 DetailViewController.h 中,需要更改 configureView 方法,这一行:
NSString *currentNote = [[Data getAllNote]objectForKey:[Data getCurrentKey]];
应该是这样的:
NSDictionary *currentNote = [[Data getAllNote] objectForKey:[Data getCurrentKey]];
大概是这样的:
if (![[currentNote objectForKey:@"title"] isEqualToString:kDefaultTitle]) self.tView.text = [currentNote objectForKey:@"title"]; self.rView.text = [currentNote objectForKey:@"description"]; 别的 self.tView.text = @""; self.rView.text = @"";
另外,应该在该文件中更改 viewDidDisappear。
我的建议是先改变Model,然后一步步分析View Controller中的每一个方法,你就会明白了。
【讨论】:
以上是关于将 UITextView 中的文本保存到 NSUserDefaults 中的方式与将 UITextFIeld 保存在 Notes 应用程序中的方式相同的主要内容,如果未能解决你的问题,请参考以下文章
如何将两个 UITextView 中的数据保存到 UserDefaults
将字符串粘贴到 uitextview 中的文本底部时会添加额外的空间