Iphone 要将对象添加到哪种类型的变量?
我将使用此方法将练习实体添加到例程中。如何声明SelectedRoutine及其类型?我想我在这个表的父表的didSelectRow方法中设置了它Iphone 要将对象添加到哪种类型的变量?,iphone,objective-c,core-data,Iphone,Objective C,Core Data,我将使用此方法将练习实体添加到例程中。如何声明SelectedRoutine及其类型?我想我在这个表的父表的didSelectRow方法中设置了它 -(void)addExercise { NSError *error = nil; Exercise *exercise = (Exercise *)[NSEntityDescription insertNewObjectForEntityForName:@"Exercise" inManagedObjectContext:
-(void)addExercise
{
NSError *error = nil;
Exercise *exercise = (Exercise *)[NSEntityDescription insertNewObjectForEntityForName:@"Exercise" inManagedObjectContext:managedObjectContext];
exercise.name = selectedExercise;
[theSelectedRoutine addExerciseObject: exercise];
if (![managedObjectContext save:&error])
{
// Handle the error.
}
NSLog(@"%@", error);
[self.routineTableView reloadData];
}
有两种解决方案。首先,如果您不想为托管对象使用子类,您可以获取关系的可变集,并将新练习添加到其中
-(void)addExercise
{
NSError *error = nil;
Exercise *exercise = [NSEntityDescription insertNewObjectForEntityForName:@"Exercise" inManagedObjectContext:managedObjectContext];
[exercise setName:selectedExercise];
[[theSelectedRoutine mutableSetForKey:@"exercise"] addObject:exercise];
if (![managedObjectContext save:&error]) {
NSLog(@"Failed to save: %@\n%@", [error localizedDescription], [error userInfo]);
}
[[self routineTableView] reloadData];
}
另一个对象是为例程创建一个子类:
@interface Routine : NSManagedObject
- (void)addExerciseObject:(NSManagedObject*)exercise;
@end
@implementation Routine
- (void)addExerciseObject:(Employee *)value
{
NSSet *changedObjects = [[NSSet alloc] initWithObjects:&value count:1];
NSMutableSet *primitiveEmployees = [self primitiveValueForKey:@"exercise"];
[self willChangeValueForKey:@"exercise" withSetMutation:NSKeyValueUnionSetMutation usingObjects:changedObjects];
[[self primitiveEmployees] addObject:value];
[self didChangeValueForKey:@"exercise" withSetMutation:NSKeyValueUnionSetMutation usingObjects:changedObjects];
[changedObjects release];
}
@end
然后可以从那里直接调用-addExerciseObject:directly
-(void)addExercise
{
NSError *error = nil;
Exercise *exercise = [NSEntityDescription insertNewObjectForEntityForName:@"Exercise" inManagedObjectContext:managedObjectContext];
[exercise setName:selectedExercise];
[theSelectedRoutine addExerciseObject:exercise];
if (![managedObjectContext save:&error]) {
NSLog(@"Failed to save: %@\n%@", [error localizedDescription], [error userInfo]);
}
[[self routineTableView] reloadData];
}
请注意,在这两种情况下,您都不需要将练习对象从-insertNewObjectForEntityForName:inManagedObjectContext:设置为大小写。该调用的返回是一个id,并且永远不需要强制转换id。一般来说,在Objective-C中进行转换是错误的。是否为所选例程创建了相应的核心数据实体?否,我有一个仅为例程的实体。也许我只是使用常规而不是选择的常规?这是我的核心数据模型:我不能100%肯定我理解你的问题。你能澄清一下吗?你看到数据模型了吗?我有一个表,我可以在其中添加例程的实体。每个例行程序都应该有一个与该例行程序练习相关的子表。我发布的代码将练习添加到例程中。但我需要告诉代码要将练习添加到哪个例程中。这就是SelectedRoutine应该是什么。我只是不知道如何设置它的值。我想它可能是您持有的模块级变量,以便用用户的选择填充它。例如,它可以是一个@属性,您可以在推送详图视图控制器时设置该属性。我只是在这里猜测,因为我不知道你是如何设计你的应用程序的。谢谢马库斯,我的问题是,我如何获得所选的程序。我没有声明它,也不知道如何设置它。如果你没有声明它,那么你需要将它作为一个属性,并在有意义的地方设置它。由于你提供的信息很少,我不能说得更具体了。