在Core Data中更新数据库的配方

时间:2013-03-05 21:44:01

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

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

这是我的代码:

- (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];
}

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

-(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];
    }
}

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

1 个答案:

答案 0 :(得分:0)

我对你的问题不太确定,但我会尝试给出一些提示。

<强>第一

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循环。这可以提升您应用中的性能。没有必要在循环中每次保存。只在最后做。

希望有所帮助。

P.S。如果你想知道其他事情,请告诉我。