这是一个谜:
我正在NSManagedObject
上调用setPrimitiveValue:forKey:
.键是对象的合法、持久、建模属性。但是,setPrimitiveValue:forKey: 失败,通常会为不同的任意属性设置值。 文档说,在为未建模的密钥调用setPrimitiveValue:forKey:
时,这种行为是预期的。因此,Core Data似乎认为关键是未建模的。
奇怪的部分:
当键被硬编码为字符串文本时,基元值确实设置成功。仅当键是变量时,它才会失败。我使用的变量恰好是从 observeValueForKeyPath:ofObject:change:context:
的 keyPath
参数传递的
keyPath
变量与字符串文本相同。 isEqual:
返回 true,并且哈希值相等。keyPath
变量的类型为 __NSCFString
。有谁知道为什么setPrimitiveValue:forKey:
会表现得不同? (此行为在 OS X 10.9.1 上)
包含更好信息的更新:
行为异常的密钥可以追溯到从磁盘上的文件加载的字符串。下面的示例是一个孤立的案例。如果将属性字符串"mainAttr"写入磁盘并读回,则setPrimitiveValue:forKey:
为错误的属性设置值,而不是"mainAttr"。
核心数据对象:
@interface Boo : NSManagedObject
@property (nonatomic, retain) NSNumber * mainAttr;
@property (nonatomic, retain) NSNumber * attr1;
@property (nonatomic, retain) NSNumber * attr2;
@property (nonatomic, retain) NSNumber * attr3;
@end
-
#import "Boo.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSManagedObjectContext *context = managedObjectContext();
NSString *key = @"mainAttr";
// write to disk, read back in
NSString *path = [@"~/Desktop/test.txt" stringByExpandingTildeInPath];
[key writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:NULL];
key = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:NULL];
Boo *boo = [NSEntityDescription insertNewObjectForEntityForName:@"Boo" inManagedObjectContext:context];
[boo setPrimitiveValue:@(5) forKey:key];
NSLog(@"Boo: %@", boo);
}
return 0;
}
您需要以下 3 个语句来设置值。试试吧。
[self willChangeValueForKey:key];
[boo setPrimitiveValue:@(5) forKey:key];
[self didChangeValueForKey:key];