我想存储文本字段中的数据。然后使用此数据填充视图控制器内标签中的文本。这可能吗?我已经弄乱了它,但似乎没有任何作用。有什么想法吗?这是我的两种方法......
- (IBAction)saveButton:(id)sender {
CoreDataStack *coreDataStack = [CoreDataStack defaultStack];
NSManagedObject *noteEntry = [NSEntityDescription insertNewObjectForEntityForName:@"Notes" inManagedObjectContext:coreDataStack.managedObjectContext];
[noteEntry setValue:_notesField.text forKey:@"notes"];
NSError *error = nil;
// Save the object to persistent store
if (![coreDataStack.managedObjectContext save:&error]) {
NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
}
[coreDataStack saveContext];
}
这是我的观点做了加载方法:
- (void)viewDidLoad
{
[super viewDidLoad];
CoreDataStack *coreDataStack = [CoreDataStack defaultStack];
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Notes"];
Notes *entry = [NSEntityDescription insertNewObjectForEntityForName:@"Notes" inManagedObjectContext:coreDataStack.managedObjectContext];
_outputLabel.text = entry.notes;
}
答案 0 :(得分:0)
saveButton:
方法中的代码似乎没问题。但是viewDidLoad
方法中的代码似乎有误。您是否尝试执行以下操作?
- (void)viewDidLoad {
[super viewDidLoad];
CoreDataStack *coreDataStack = [CoreDataStack defaultStack];
//First way to init your fetchRequest:
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Notes"];
//Second way to init your fetchRequest:
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Notes" inManagedObjectContext:coreDataStack];
[fetchRequest setEntity:entity];
//Having a NSEntityDescription object can be usefull if you need to group your data, for example
//Set some predicates, if necessary
//Set some sortdescriptors, if necessary
NSError *error;
NSArray *resultsArray = [coreDataStack executeFetchRequest:request error:&error];
NSLog(@"%@", resultsArray);
_outputLabel.text = [[resultsArray firstObject] notes]; //if your array can only have one object
}
NSLog将为您提供获取阵列的结构(我无法猜测)。然后,您就可以设置_outputLabel.text
。
答案 1 :(得分:0)
@ user1966109的回答是完全正确的答案你正在寻找的。由于您需要在标签中显示文本,因此您需要设置谓词以获得单行。将谓词设置如下
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"value == abc"];//considerin abc is the word you are looking for.
request.predicate = predicate;
//then execute the query.