添加对象到什么类型的变量?
我将使用这种方法将锻炼实体添加到例程中。我如何声明 SelectedRoutine 以及它是什么类型?我想我将其设置在此表的父表的 didSelectRow 方法中。
-(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];
}
I will be using this method to add an entity of Exercise to a Routine. How can I declare theSelectedRoutine and what type is it? I'm thinking I set it in this table's parent table's didSelectRow method.
-(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];
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有几种解决方案。首先,如果您不想为托管对象使用子类,您可以获取关系的可变集并向其中添加新的练习。
另一个目标是为您的例程创建一个子类:
然后您可以从那里直接调用
-addExerciseObject:
。请注意,无论哪种情况,您不需要都需要从
-insertNewObjectForEntityForName: inManagedObjectContext:
中设置锻炼对象的大小写。该调用的返回结果是id
,并且id
永远不需要进行强制转换。一般来说,Objective-C 中的类型转换是错误的。There are a couple of solutions. First, if you don't want to use subclasses for your managed object you can grab the mutable set for the relationship and add your new exercise to it.
The other object would be to create a subclass for your routine:
From there you can then call
-addExerciseObject:
directly.Note that in either case you DO NOT need to case your Exercise object from
-insertNewObjectForEntityForName: inManagedObjectContext:
. The return for that call is anid
andid
never needs to be cast. In general, casting in Objective-C is wrong.