0

我是新手NSManagedObjectContext。我Link在我的应用程序中创建了一个实体,其中包含一个NSString *url.

在我的应用程序的某个时刻,我需要Link在我的基础中插入一个新的,所以我只需这样做:

Link *link = [NSEntityDescription 
                         insertNewObjectForEntityForName:@"Link" 
                         inManagedObjectContext:self.managedObjectContext];
link.url = myUrl;

但在此之前,我想检查我的基地中是否还没有具有相同 url 的链接。而且我不知道该怎么做……我该怎么办?

编辑:从我在网上找到的工具中使用此方法从基础检索数据:

// Fetch objects with a predicate
+(NSMutableArray *)searchObjectsForEntity:(NSString*)entityName withPredicate:(NSPredicate *)predicate andSortKey:(NSString*)sortKey andSortAscending:(BOOL)sortAscending andContext:(NSManagedObjectContext *)managedObjectContext
{
    // Create fetch request
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:managedObjectContext];
    [request setEntity:entity];

    // If a predicate was specified then use it in the request
    if (predicate != nil)
        [request setPredicate:predicate];

    // If a sort key was passed then use it in the request
    if (sortKey != nil) {
        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:sortKey ascending:sortAscending];
        NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
        [request setSortDescriptors:sortDescriptors];
    }

    // Execute the fetch request
    NSError *error = nil;
    NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];

    // If the returned array was nil then there was an error
    if (mutableFetchResults == nil)
        NSLog(@"Couldn't get objects for entity %@", entityName);

    // Return the results
    return mutableFetchResults;
}

我想知道如何使用它。

谢谢你的帮助。

4

2 回答 2

4

您提供的方法只是搜索与 NSManagedObjectContext 中的属性匹配的 NSManagedObject,如果存在,则返回它。

但是,您需要实现的称为 Find-or-Create 模式,在 Core Data 编程指南中进行了讨论。基本上,您搜索匹配特定条件的对象,如果存在,则返回该对象。如果该对象不存在,则创建它。

核心数据编程指南

例如

+ (NSString *)entityName
{
    return NSStringFromClass([Link class]);
}

+ (instancetype)findUsingPredicate:(NSPredicate *)predicate withContext:(NSManagedObjectContext *)context
{
    Link * entity;

    // Setup the fetchRequest
    NSFetchRequest * fetchRequest = [NSFetchRequest fetchRequestWithEntityName:[[self class] entityName]];
    fetchRequest.predicate = predicate;

    // Credit: @Martin R
    [fetchRequest setFetchLimit:1];

    // Execute the fetchRequest
    NSError *error = nil;
    NSArray * matchingLinks = [context executeFetchRequest:fetchRequest error:&error];

    // MatchingLinks will only return nil if an error has occurred otherwise it will return 0
    if (!matchingLinks)
    {
        // handle error
        // Core data returns nil if an error occured
        NSLog(@"%s %@", __PRETTY_FUNCTION__, [error description]);
    }
    else if ([matchingLinks count] <= 0)
    {
        // if the count <= 0, there were no matches

        NSLog(@"%s Not found", __PRETTY_FUNCTION__);

    } else {

        // A link with a url that matches the url in the dictionary was found.
        NSLog(@"%s Found", __PRETTY_FUNCTION__);

        entity = [matchingLinks lastObject];
    }

    return entity;
}

+ (instancetype)findUsingPredicate:(NSPredicate *)predicate orCreateWithContext:(NSManagedObjectContext *)context
{
    Link * entity = [[self class] findUsingPredicate:predicate withContext:context];

    if (!entity) {
        entity = [[self class] createWithContext:context];
    }

    return entity;
}

+ (isntancetype)createWithContext:(NSManagedObjectContext *)context
{
    return [[self class] alloc] initWithContext:context];
}

- (instancetype)initWithContext:(NSManagedObjectContext *)context
{
    Link * entity = [NSEntityDescription insertNewObjectForEntityForName:[[self class] entityName] inManagedObjectContext:context];

    return entity;
}

用例:

NSString * url = @"http://www.mylink.com";
NSPredicate * predicate = [NSPredicate predicateWithFormat:@"url = %@", url];
Link * link = [Link findUsingPredicate:predicate orCreateWithContext:self.managedObjectContext];
link.url = url;
于 2013-11-06T18:39:29.903 回答
1

你可以这样做(用你的方法):

AppDelegate *del = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *managedObjectContext = del.managedObjectContext;
NSString *urlString = @"YOUR URL HERE";

NSMutableArray *fetchedResults =  [self  searchObjectsForEntity:@"Link" withPredicate:[NSPredicate predicateWithFormat:@"url == %@", urlString] andSortKey:@"url" andSortAscending:YES andContext:managedObjectContext];

BOOL exist = NO;

if(fetchedResults.count >= 1){
    exist = YES;
}
于 2013-11-06T19:09:16.673 回答