当我想在CoreData中存储标量时,我已经阅读了很多文章,他们说要明确地转换为NSNumber
:
@property (nonatomic, assign) NSInteger value;
- (NSInteger)value
{
return [value integerValue];
}
- (void)setValue:(NSInteger)val
{
value = [NSNumber numberWithInteger:val];
}
但是在我们的旧项目中,我们有很多属性,我们不进行这些操作(并且它们没有自定义访问器)!为什么会这样?
宣言。标量值不是短暂的。
@interface ProductProperty : NSManagedObject
@property (nonatomic, strong, readonly) NSString * propertyID;
@property (nonatomic, strong, readonly) NSString * title;
@property (nonatomic, strong, readonly) NSSet * values;
@property (nonatomic, assign, readonly) BOOL filter;
@property (nonatomic, strong, readonly) NSDate *update;
@property (nonatomic, strong, readonly) NSNumber *index;
@property (nonatomic, assign, readonly) BOOL system;
@end
#import "ProductProperty.h"
@implementation ProductProperty
@dynamic propertyID;
@dynamic title;
@dynamic values;
@dynamic filter;
@dynamic update;
@dynamic index;
@dynamic system;
@end
映射到对象。如果收到的JSON与现有JSON不同,则调用。否则它从CoreData存储中获取。
- (void)updateProperties:(NSArray*)properties
{
for (NSDictionary *_property in properties) {
NSString *propertyID = [_property objectForKey:@"id"];
ProductProperty *property = [state.productPropertiesWithIDs objectForKey:propertyID];
if (!property) {
property = [state.ctx newObjectWithEntityName:ProductProperty.entityName];
property.propertyID = propertyID;
[state.productPropertiesWithIDs setObject:property forKey:propertyID];
}
property.update = state.update;
property.title = [_property objectForKey:@"title"];
property.filter = [_property objectForKey:@"filter"] ? [[_property objectForKey:@"filter"] boolValue] : YES;
property.index = [propertyIndexes objectForKey:propertyID] ? [propertyIndexes objectForKey:propertyID] : [NSNumber numberWithInt:propertyIndex++];
property.system = [SYSTEM_PROPERTY_IDS containsObject:propertyID] ? YES : NO;
[self updatePropertyValues:[_property objectForKey:@"values"] forProperty:property];
}
}
- (ProductProperty*)productPropertyWithID:(NSString*)propertyId error:(NSError**)error
{
NSFetchRequest *req = [ProductProperty request];
req.predicate = [NSPredicate predicateWithFormat:@"propertyID == %@", propertyId];
return [[ctx executeFetchRequest:req error:error] lastObject];
}
答案 0 :(得分:2)
答案是,因为iOS 5 CoreData支持为标量自动生成访问器,所以我不需要手动实现它们。