添加对象的变量类型是什么?

时间:2011-04-27 16:51:56

标签: iphone objective-c core-data

我将使用此方法将一个练习实体添加到例程。如何声明选择的例程以及它是什么类型的?我想我在这个表的父表的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];
}

1 个答案:

答案 0 :(得分:0)

有几种解决方案。首先,如果您不想为托管对象使用子类,则可以获取该关系的可变集并将新练习添加到该对象中。

-(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:

-(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:开始对您的Exercise对象进行操作。该调用的返回值为idid永远不需要进行投射。通常,在Objective-C中进行转换是错误的。