0

我正在使用 NSManagedObject 来保存一些值,但没有为此使用实体。因为我不想将其限制在某些实体上。我尝试使用 (Oist *)managedObject.entity,但不工作。如何使用这个 managedObject 来获取它是这样的:

Oist.h
@class File;

@interface Oist : NSManagedObject
@property (nonatomic, retain) NSSet *files;
@end

@interface Oist (CoreDataGeneratedAccessors)

- (void)addFilesObject:(File *)value;

File.h
@class Oist;

@interface File : NSManagedObject

@property (nonatomic, retain) Oist *gist;

@end

- (void)newManagedObjectWithClassName:(NSString *)className forRecords:(NSDictionary *)records
{
    NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:className inManagedObjectContext:[[GPCoreDataController sharedInstance] backgroundManagedObjectContext]];
    [records enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        [self setValue:obj forKey:key forManagedObject:newManagedObject];
    }];
}

- (void)setValue:(id)value forKey:(NSString *)key forManagedObject:(NSManagedObject *)managedObject
{
    File *fileEntity = [NSEntityDescription insertNewObjectForEntityForName:@"File" inManagedObjectContext:[[GPCoreDataController sharedInstance] backgroundManagedObjectContext]];

    if ([key isEqualToString:@"files"])
    {
        NSDictionary *files = (NSDictionary *)value;
        for (NSString *key in [files allKeys]) {
            NSDictionary *file = [files valueForKey:key];
            NSLog(@"%@", file[@"filename"]);
            [fileEntity setValue:file[@"filename"] forKey:@"filename"];
            [fileEntity setValue:file[@"type"] forKey:@"type"];
        }
    } else if ([key isEqualToString:@"id"])
    {
        if ([managedObject.entity.name isKindOfClass:[Oist class]]) {
        //here I want to use Oist's method - (void)addFilesObject:(File *)value; how to do that?
        }
        [managedObject setValue:[NSNumber numberWithInt:[value integerValue]] forKey:@"gistID"];
    }
}
4

1 回答 1

0

我可能误解了您的问题,但看起来您希望将通用类型 (NSManagedObject *) 转换为更具体类型的子类。

检查通常传递的指针是否实际上是子类的实例的方法是:

if ([managedObject isKindOfClass:[Oist self]]) {
    // managedObject may safely be cast to an Oist*
}

您可以在没有分配的情况下进行演员表,如下所示:

[(Oist *)managedObject addFiles...];

或者,使用适当的括号,访问一个属性(点运算符的优先级高于强制转换,因此您需要先告诉编译器您想要强制转换):

((Oist *)managedObject).entity

但我认为这对读者来说不太清楚,并且可能比带有演员表的显式分配更多的击键,这是我推荐的:

if ([managedObject isKindOfClass:[Oist self]]) {
   Oist *oist = (Oist *)managedObject;
   [oist addFilesObject:someFilesObject];
}
于 2013-09-04T04:20:19.520 回答