IOS Coredata检查属性是否存在 [英] IOS Coredata check if attribute is exist or not

查看:125
本文介绍了IOS Coredata检查属性是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发基于核心数据和基于XML解析[RSS Feed]的项目。我必须检查属性值是否在coredata中可用?



例如: -



我有3个属性在我的数据模型中。 name,websitename和feedurl。
现在,我必须使用用户的输入解析网址。但在解析时,我想检查 URLNAME 是否在coredata中可用。如果可用,则解析将不会插入到coredata中,如果 URL 不在coredata中,那么它将被插入到coredata中。



尝试从我能够在核心数据中插入url。但是使用这种方法,同样的url也会进入coredata。

   - (void)feedParserDidFinish:(MWFeedParser *)parser {

[HUD hide:YES];
// ** Coredata插入值** //
NSManagedObjectContext * context = [self managedObjectContext];

//创建一个新的托管对象
NSManagedObject * newDevice = [NSEntityDescription insertNewObjectForEntityForName:@IinManagedObjectContext:context];
[newDevice setValue:self.Name forKey:@name];
[newDevice setValue:self.WebsiteName forKey:@websitename];
[newDevice setValue:self.Feedlink forKey:@feedurl];

NSError * error = nil;
//将对象保存到持久存储
if(![context save:& error]){
NSLog(@无法保存!%@%@ [error localizedDescription]);
}

// **解析url ** //

NSLog(@Finished Parsing%@,(parser.stopped?@ ):@));
NSArray * array = [parsedItems sortedArrayUsingDescriptors:
[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@date
ascending:NO]
NSMutableDictionary * dict = [NSMutableDictionary new];
[dict setObject:chanelInfo forKey:@title];
[dict setObject:array forKey:@data];
[sectionheaders addObject:dict];
NSLog(@SectionHeader Count:%ld,(long)sectionheaders.count);
[self updateTableWithParsedItems];


}


解决方案

如果你想防止一个对象被插入,如果它已经在那里,你有两个基本的选择。



第一个是检查它的存在,只有

  NSFetchRequest * fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@I];如果不在数据库中, 
fetchRequest.predicate = [NSPredicate predicateWithFormat:@feedurl =%@,self.Feedlink];
if([[moc executeFetchRequest:fetchRequest error:NULL] count] == 0){
//创建一个新的托管对象
}

第二个是使用iOS9中引入的新的唯一约束。有关详细信息,请参阅WWDC 2015核心数据演示。



请注意,如果您有大量对象,则应该允许对搜索的属性进行索引,或者你将最终对每个对象进行线性搜索。



此外,如果你解析了很多对象,最好一次搜索多个项目,和/或使用更好的算法。



WWDC 2013核心数据性能演示文稿是您应该研究的实现更新或插入的一个很好的例子。 / p>

I am working on coredata based and XML parsing[RSS Feed] based project. I have to check that if attribute value is available or not in coredata ?

For example :-

I have 3 attribute in my datamodel. name,websitename and feedurl. Now i have to parsing the url with user's input. but at the time of parsing i want to check that if URLNAME is available in coredata or not. If available then parsing will done without inserting into coredata and if URL is not in coredata then it will be inserted into coredata.

Here is my try from where i am able to insert the url in core data. but with this method same url is also enters in coredata.

- (void)feedParserDidFinish:(MWFeedParser *)parser {

    [HUD hide:YES];
    //**Coredata inserting value**//
    NSManagedObjectContext *context = [self managedObjectContext];

    // Create a new managed object
    NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:@"I" inManagedObjectContext:context];
    [newDevice setValue:self.Name forKey:@"name"];
    [newDevice setValue:self.WebsiteName forKey:@"websitename"];
    [newDevice setValue:self.Feedlink forKey:@"feedurl"];

    NSError *error = nil;
    // Save the object to persistent store
    if (![context save:&error]) {
        NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
    }

    //**Parsing url**//

    NSLog(@"Finished Parsing%@", (parser.stopped ? @" (Stopped)" : @""));
    NSArray* array =[parsedItems sortedArrayUsingDescriptors:
                     [NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"date"
                                                                          ascending:NO]]];
        NSMutableDictionary* dict = [NSMutableDictionary new];
        [dict setObject:chanelInfo forKey:@"title"];
        [dict setObject:array forKey:@"data"];
        [sectionheaders addObject:dict];
            NSLog(@"SectionHeader Count:%ld",(long)sectionheaders.count);
            [self updateTableWithParsedItems];


}

解决方案

If you want to prevent an object from being inserted if it is already there, you have two basic options.

The first is to check for its existence, and only create the new eject if it is not in the database.

NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"I"];
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"feedurl = %@", self.Feedlink];
if ([[moc executeFetchRequest:fetchRequest error:NULL] count] == 0) {
    // Create a new managed object
}

The second is to use the new unique constraints introduced in iOS9. For details, please see the WWDC 2015 core data presentation.

Note, that if you have lots of objects, you should probably allow the attribute you search on to be indexed, or you will end up doing a linear search for every object.

Also, if you parse lots of objects, you are better off searching for multiple items at once, and/or using a much better algorithm.

The WWDC 2013 "Core Data Performance" presentation has an excellent example of implementing "update-or-insert" that you should study.

这篇关于IOS Coredata检查属性是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆