1
假设我从远程Web服务下载数据。更准确地说,我从Web服务下载新闻列表,每个新闻都有一个newsID,我们可以将其视为服务的主键,因此我们不会找到两个相同的newsID。核心数据属性唯一性
我怎样才能确定我只插入了一个尚不存在的newsID的数据?
我已经草拟我用这种方法解决:
- (BOOL)validateNewsID:(NSNumber **)newsID error:(NSError **)error
{
NSError *countError = nil;
NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init] autorelease];
[fetchRequest setEntity:[self entity]];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"newsID == %@", *newsID];
[fetchRequest setPredicate:predicate];
NSUInteger resultCount = [SharedManagedObjectContext countForFetchRequest:fetchRequest error:&countError];
if (countError) {
OLog(countError);
*error = countError;
return NO;
}
if (resultCount > 0) {
NSString *errorString = @"NewsID should be unique";
NSDictionary *userInfoDict = [NSDictionary dictionaryWithObject:errorString
forKey:NSLocalizedDescriptionKey];
NSError *uniquenessError = [[[NSError alloc] initWithDomain:kNewsValidationDomain
code:kNewsValidationUniquenessCode
userInfo:userInfoDict] autorelease];
*error = uniquenessError;
return NO;
}
return YES;
}
,但确实如预期,因为,我想,当我执行读取请求,我发现我的同一个对象之前在上下文中插入不工作。我错了吗?
我该如何解决?
你为什么要发送一个指针作为newsID的指针? – 2012-03-05 19:39:05
因为声明了参数(NSNumber **)newsID – 2012-03-06 08:27:52