从Core Data实体获取属性值

时间:2015-10-28 01:42:13

标签: ios core-data entity

我有一个viewcontroller,它在UIPicker中显示Core Data实体。选择一行,该实体作为属性传递给另一个viewcontroller进行显示。

我有一个方法可以返回Player实体的所有属性名称:

for(NSString* strThisField in arrFields) {

            UILabel* lblThisField = [[UILabel alloc] initWithFrame:CGRectMake(0.0, fieldY, vPlayerBox.frame.size.width, 30.0)];

            lblThisField.text = [Player valueForKeyPath:strThisField];

            lblThisField.textColor = AO_Brown;
            lblThisField.font = AO_SansSerif_Font;
            [vPlayerBox addSubview:lblThisField];

            fieldY = fieldY + 35.0;
        }

然后我试图以这种方式显示这些属性的值:

- (NSDictionary*) getKeyValuesOfEntity : (Player*) thisEntity {

    NSArray* arrProperties = [self getProperties];

    NSMutableDictionary* dictKeysAndValues = [[NSMutableDictionary alloc] init];

    for(NSString* strThisKey in arrProperties) {

        id value = [thisEntity valueForKey:strThisKey];

        if ([value isKindOfClass:[NSString class]]) {

            NSString* strValue = (NSString*)value;
            [dictKeysAndValues setObject:strValue forKey:strThisKey];

        } else if ([value isKindOfClass:[NSDate class]]) {

            NSDate* dtValue = (NSDate*)value;
            [dictKeysAndValues setObject:dtValue forKey:strThisKey];

        } else if ([value isKindOfClass:[NSNumber class]]) {

            NSNumber* numValue = (NSNumber*)value;
            [dictKeysAndValues setObject:numValue forKey:strThisKey];

        } else if ([value isKindOfClass:[NSSet class]]) {

            NSSet* setValue = (NSSet*)value;
            [dictKeysAndValues setObject:setValue forKey:strThisKey];

        }
    }

    return dictKeysAndValues;

}



- (NSArray *)getProperties  {

    unsigned count;
    objc_property_t *properties = class_copyPropertyList([Player class], &count);

    NSMutableArray *rv = [NSMutableArray array];

    unsigned i;
    for (i = 0; i < count; i++)
    {
        objc_property_t property = properties[i];
        NSString *name = [NSString stringWithUTF8String:property_getName(property)];
        [rv addObject:name];
    }

    free(properties);

    return rv;
}

但是我崩溃了valueForKeyPath行,所以显然我做错了。有没有办法以这种方式获得房产价值,还是我走向死胡同?

由于

编辑:

我的UILabel.text属性出错了 - 应该读取lblThisField.text = [self.myPlayer getValueForKey:strThisKey];但即使改变它仍然会崩溃。我写了第二种方法来将值和键放入字典中,尽管它起作用,但它似乎是一个笨重的解决方案。

navbar-right

1 个答案:

答案 0 :(得分:1)

我不知道&#34;播放器&#34;在你的for-in循环代表一个类或一个实例。方法 - [NSObject valueForKeypath]是一个实例方法。所以你需要通过这样做来初始化类Player的实例:

Player *player = [NSEntityDescription insertNewObjectForEntityForName:@"Player" inManagedObjectContext:appDelegate.managedObjectContext];

一切都会变得很酷。希望这会有所帮助。