所以在Xcode中,我有一个利用核心数据的笔记应用程序。有两个字段,标题文本字段和消息文本视图。我遇到的一个问题是,如果用户做出注释并决定稍后进行编辑,则用户必须编辑该消息以使其能够再次保存。无论我是否更改消息或标题,我都希望它保存。感谢
#import "DeviceDetailViewController.h"
@interface DeviceDetailViewController ()
@end
@implementation DeviceDetailViewController
@synthesize device;
- (NSManagedObjectContext *)managedObjectContext {
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if ([delegate performSelector:@selector(managedObjectContext)]) {
context = [delegate managedObjectContext];
}
return context;
}
@synthesize message;
@synthesize titles;
@synthesize button;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[button setEnabled:NO];
titles.delegate = self;
message.delegate = (id)self;
// Do any additional setup after loading the view.
if (self.device) {
[self.titles setText:[self.device valueForKey:@"name"]];
[self.message setText:[self.device valueForKey:@"version"]];
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)cancel:(id)sender {
[self dismissViewControllerAnimated:YES completion:nil];
}
- (IBAction)save:(id)sender {
NSManagedObjectContext *context = [self managedObjectContext];
if (self.device) {
// Update existing device
[self.device setValue:self.titles.text forKey:@"name"];
[self.device setValue:self.message.text forKey:@"version"];
} else {
// Create a new device
NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:@"Device" inManagedObjectContext:context];
[newDevice setValue:self.titles.text forKey:@"name"];
[newDevice setValue:self.message.text forKey:@"version"];
}
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
}
[self dismissViewControllerAnimated:YES completion:nil];
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (titles.text.length >= 35 && range.length == 0)
return NO;
return YES;
}
//Code beyond this point is disabling keyboard when you click outside of textfield
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[message resignFirstResponder];
[titles resignFirstResponder];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[titles resignFirstResponder];
return NO;
}
//Enabling/disabling 'Save' button based on texfield data
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
if ([titles.text length] != 0 && [message.text length] != 0) {
[button setEnabled:YES];
}
else
{
[button setEnabled:NO];
}
return YES;
}
@end