Инстанцирование пользовательского класса от NSDictionary

Изменить код на:

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "dept_id")
private Long deptId;
19
задан CIFilter 6 May 2009 в 17:03
поделиться

2 ответа

-setValuesForKeysWithDictionary: метод вместе с -dictionaryWithValuesForKeys :, это то, что вы хотите использовать.

Пример:

// In your custom class
+ (id)customClassWithProperties:(NSDictionary *)properties {
   return [[[self alloc] initWithProperties:properties] autorelease];
}

- (id)initWithProperties:(NSDictionary *)properties {
   if (self = [self init]) {
      [self setValuesForKeysWithDictionary:properties];
   }
   return self;
}

// ...and to easily derive the dictionary
NSDictionary *properties = [anObject dictionaryWithValuesForKeys:[anObject allKeys]];
26
ответ дан 30 November 2019 в 03:43
поделиться

Предполагая, что ваш класс соответствует протоколу Key-Value Coding , вы можете использовать следующее: (для удобства определено как категория в NSDictionary):

// myNSDictionaryCategory.h:
@interface NSDictionary (myCategory)
- (void)mapPropertiesToObject:(id)instance
@end


// myNSDictionaryCategory.m:
- (void)mapPropertiesToObject:(id)instance
{
    for (NSString * propertyKey in [self allKeys])
    {
        [instance setValue:[self objectForKey:propertyKey]
                    forKey:propertyKey];
    }
}

И вот как вы бы это использовали:

#import "myNSDictionaryCategory.h"
//...
[someDictionary mapPropertiesToObject:someObject];
3
ответ дан 30 November 2019 в 03:43
поделиться
Другие вопросы по тегам:

Похожие вопросы: