【问题标题】:Recipes to update database in Core Data在 Core Data 中更新数据库的方法
【发布时间】:2013-02-20 11:59:27
【问题描述】:

我有一种在卡片上添加印章的方法,从二维码阅读器到网络服务 我的问题是,

这是我的代码:

- (void)addStamp
{    
    NSString *url = [_URL stringByAppendingString:@"add-stamp"];
    NSString *post = [NSString stringWithFormat:@"userId=%@&code=%@", self.userId, self.code ];
    post = [post stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSData *postData = [NSData dataWithBytes:[post UTF8String]
                                      length:[post lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL 
    URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:600];

    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:postData];
}

现在我想用新方法更新我的数据库 -> 如果代码重复添加标记,如果没有创建添加新卡:

-(void)addStampInDB:(int)cardId
{
    NSManagedObjectContext* managedObjectContext = [(AppDelegate*) [[UIApplication 
    sharedApplication] delegate] managedObjectContext];

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Card"
                                          inManagedObjectContext:managedObjectContext];
    [fetchRequest setEntity:entity];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"remote_id = %d", cardId];
    [fetchRequest setPredicate:predicate];
    [managedObjectContext lock];

    NSError *error;
    NSArray *fetchedObjects = [managedObjectContext executeFetchRequest:fetchRequest
    error:&error];
    [managedObjectContext unlock];

    Card *d = nil;
    if([fetchedObjects count] > 0 ){
        d = [fetchedObjects objectAtIndex:0];
        cardId++;

    } else{ 
        d = [NSEntityDescription insertNewObjectForEntityForName:@"Card" 
                                          inManagedObjectContext:managedObjectContext];
    }

    NSArray *test;
    for(NSDictionary *stamp in test)
    {   
        d.remote_id = [NSNumber numberWithInt:[[stamp objectForKey:@"id"] intValue]];
        d.stampNumber = [NSNumber numberWithInt:[[stamp objectForKey:@"stampNumber"] intValue]];
        d.createdAt = [NSDate dateWithTimeIntervalSince1970:[[stamp objectForKey:@"createdAt"] 
        intValue]];

        [managedObjectContext lock];
        NSError *error;
        if (![managedObjectContext save:&error])
        {
            NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
            NSLog(@"Failed to save to data store: %@", [error localizedDescription]);
            NSArray* detailedErrors = [[error userInfo] objectForKey:NSDetailedErrorsKey];
            if(detailedErrors != nil && [detailedErrors count] > 0) {
                for(NSError* detailedError in detailedErrors) {
                    NSLog(@"  DetailedError: %@", [detailedError userInfo]);
                }
            } else {
                NSLog(@"  %@", [error userInfo]);
            }
        }
        [managedObjectContext unlock];
    }
}

我不知道我的方法是否正确以及如何测试我的方法?

【问题讨论】:

    标签: objective-c xcode core-data nspredicate nsfetchedresultscontroller


    【解决方案1】:

    我不太确定您的问题,但我会尝试提供一些提示。

    第一

    Card *d = nil;
    if([fetchedObjects count] > 0 ){
        d = [fetchedObjects objectAtIndex:0];
        cardId++;
    
    } else{ 
        d = [NSEntityDescription insertNewObjectForEntityForName:@"Card" 
                                          inManagedObjectContext:managedObjectContext];
    }
    

    在这里你找到了一张现有的卡片,你使用它,否则你创建一个新的。问:cardId 呢?用在什么地方?

    第二

    for(NSDictionary *stamp in test)
    {   
        d.remote_id = [NSNumber numberWithInt:[[stamp objectForKey:@"id"] intValue]];
        d.stampNumber = [NSNumber numberWithInt:[[stamp objectForKey:@"stampNumber"] intValue]];
        d.createdAt = [NSDate dateWithTimeIntervalSince1970:[[stamp objectForKey:@"createdAt"] 
        intValue]];
    
        // other code here
    }
    

    如果循环test,则每次都会覆盖您卡上的值d。对吗?

    第三

    for(NSDictionary *stamp in test)
    {   
        // other code here
    }
    
    // save here
    

    将保存移出 for 循环。这可以提高您的应用程序的性能。不必在循环中每次都保存。只在最后做。

    希望对您有所帮助。

    附:如果您想了解其他信息,请告诉我。

    【讨论】:

    • 感谢您的 cmets cardId,它在网络服务上,// 此处的其他代码是什么意思,我是否应该执行循环?
    • @adam about // other code here 我的意思是您正在使用的代码。为了简单起见,我不会重复您的代码。关于循环,这取决于您的要求。您要每次都覆盖卡片吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-27
    • 2020-12-02
    • 1970-01-01
    • 2020-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多