一对多关系:CoreData [英] One-to-Many Relationship: CoreData
问题描述
我对coredata相当陌生,并且一直困扰于一个问题。
任何帮助将不胜感激。
I'm fairly new to coredata and have been stuck on an issue. Any assistance will be greatly appreciated.
信息:
我有一个用于实体的核心数据应用程序;
列表和任务。
列表和任务具有一对多关系。
Information: I have a core data app with to entities; List and Task. List and Task have a one-to-many relationship.
Task.h
@class List;
@interface Task : NSManagedObject
@property (nonatomic, retain) NSString * task;
@property (nonatomic, retain) NSString * note;
@property (nonatomic, retain) List *list;
@end
List.h
@class Task;
@interface List : NSManagedObject
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSDate * dateCreated;
@property (nonatomic, retain) NSNumber * sortOrder;
@property (nonatomic, retain) NSSet *task;
@end
@interface List (CoreDataGeneratedAccessors)
- (void)addTaskObject:(Task *)value;
- (void)removeTaskObject:(Task *)value;
- (void)addTask:(NSSet *)values;
- (void)removeTask:(NSSet *)values;
@end
我使用创建列表;
NSManagedObjectContext *context = [self managedObjectContext];
if ([self.listTextField.text length] == 0) { // Quit here if no text is entered
[self dismissViewControllerAnimated:YES completion:nil];
return;
}
// Create a new list.
// Create an NSManagedObject for our database entity.
list = [NSEntityDescription insertNewObjectForEntityForName:@"List" inManagedObjectContext:context];
// Add the new task to the object (which in turns adds to our database).
[list setValue:self.listTextField.text forKey:@"name"];
// Get current date and time.
NSDate *todayDate = [NSDate date];
// Add the date to the object (which in turns adds to our database).
[list setValue:todayDate forKey:@"dateCreated"];
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];
我可以使用下面的代码通过cellaccessorybuttontapped来更新已创建的列表;
I can update already created lists using the code below with cellaccessorybuttontapped;
NSManagedObjectContext *context = [self managedObjectContext];
if ([self.listTextField.text length] == 0) {
// Delete object from database.
[context deleteObject:self.list];
NSError *error = nil;
// Save the action to persistent store
if (![context save:&error]) {
NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
}
[self dismissViewControllerAnimated:YES completion:nil];
} else {
// Update existing task.
[self.list setValue:self.listTextField.text forKey:@"name"];
// Get current date and time.
NSDate *todayDate = [NSDate date];
// Add the date to the object (which in turns adds to our database).
[list setValue:todayDate forKey:@"dateCreated"];
NSError *error = nil;
// Save the action to persistent store
if (![context save:&error]) {
NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
}
}
[self dismissViewControllerAnimated:YES completion:nil];
然后我可以导航至列表。
I can then navigate into a list.
我的问题是我该如何为刚刚导航到的列表创建一个任务?
已经有2天了,我一直没能在Google上找到任何东西。
My question is how can I then create a task for the list I have just navigated into? It's been 2 days and I've not been able to find anything on Google.
我建议已添加;
@property (strong, nonatomic) List *selectedList;
我现在将其作为保存方法
I now have this as my Save method
NSManagedObjectContext * context = [selfmanagedObjectContext];
NSManagedObjectContext *context = [self managedObjectContext];
// Saving a new task.
Task *task = [NSEntityDescription insertNewObjectForEntityForName:@"Task" inManagedObjectContext:context];
task.task = self.taskText.text;
task.note = self.noteText.text;
task.list = self.selectedList;
NSLog(@"The selected list is: %@", [self.selectedList description]);
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
}
[self.selectedList addTaskObject:task];
[self dismissViewControllerAnimated:YES completion:nil];
新任务已创建,但在所有列表中均已创建。
是否可能正在运行,而我不是根据任务列表来获取任务?
The new task is created but it is created in all lists. Is it possible that this is working and I'm not fetching tasks based on their list?
这是我导航到列表时的获取请求:
This is my fetch request when I navigate into a list:
if (fetchedResultsController != nil) {
return fetchedResultsController;
}
// Create a fetch request.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Create an entity so fetch the data from.
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Task" inManagedObjectContext:self.managedObjectContext];
// Set the entity of the fetch request.
[fetchRequest setEntity:entity];
// Set the amount to be fetched at a time
[fetchRequest setFetchBatchSize:20];
// Create a sort descriptor.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"task" ascending:NO];
// Attach the sort descriptor to the fetch request.
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
// Create a fetch result controller using the fetch request
NSFetchedResultsController *theFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:self.managedObjectContext
sectionNameKeyPath:nil
cacheName:nil];
self.fetchedResultsController = theFetchedResultsController;
theFetchedResultsController.delegate = self;
// Perform fetch.
NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error]) {
// Handle error.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
exit(-1); // Fail
}
return fetchedResultsController;
推荐答案
您需要跟踪拥有的列表导航到。做到这一点的一种方法是像这样创建一个名为 parentList
的属性
You need to keep track of the list that you have navigated into. One way of doing it would be to create a property called as parentList
like so
@property(nonatomic,strong) List *parentList
在视图控制器中创建任务
in the view controller you create a task in. And just before navigating to the view controller set this property.
在任务视图控制器中,您执行与 List 类似的插入操作。 code>对象,使用
Task * reqdTask = [NSEntityDescription insertNewObjectForEntityForName:@ Task inManagedObjectContext:context];
然后设置所有值一次,只要说
In the task view controller you do a insert similar to the List
object using Task *reqdTask = [NSEntityDescription insertNewObjectForEntityForName:@"Task" inManagedObjectContext:context];
and then set all the values once say Save
button is pressed.
[parentList addTaskObject: reqdTask];
完成。这将在任务实体中创建一个 Task
并将其映射到 List
实体。希望对您有所帮助。
and ur done. This will create a Task
in the task entity and map it to the List
entity. Hope this helps.
**编辑***
您需要在保存上下文之前,先执行 [parentList addTaskObject:reqdTask];
。
You need to do this [parentList addTaskObject: reqdTask];
before saving your context.
将此内容添加到 NSFectResultsController
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@ list =%@,self.parentList]];
所以会是这样
// Create a fetch request.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Create an entity so fetch the data from.
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Task" inManagedObjectContext:self.managedObjectContext];
// Set the entity of the fetch request.
[fetchRequest setEntity:entity];
// Set the amount to be fetched at a time
[fetchRequest setFetchBatchSize:20];
// Create a Predicate.
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"list = %@",self.parentList]];
//continue
这将带来与所选列表相关的任务。
this will bring the task associated with the selected list.
这篇关于一对多关系:CoreData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!