Coredata更新问题

时间:2015-06-19 05:15:24

标签: ios cocoa-touch core-data

我尝试使用此功能更新coredata中的某些货币缩写。

- (void)updateCurrencies
{
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {

        NSFetchRequest *request = [[NSFetchRequest alloc] init];
        [request setEntity:[NSEntityDescription entityForName:@"Transaction" inManagedObjectContext:managedObjectContext]];

        NSError *error = nil;
        NSArray *results = [managedObjectContext executeFetchRequest:request error:&error];
        NSLog(@"Number of data : %lu", (unsigned long)[results count]);

        for (int i = 0; i < [results count]; i++) {
            Transaction* t = [results objectAtIndex:0];
            NSLog(@"currency: %@", t.currency);
            if ([t.currency isEqualToString:@"CAN"]) {
                t.currency = @"CAD";
                NSLog(@"new currency set.");
            }
            [self saveContext];
        }
    }
}

我在didFinishLaunchingWithOptions中调用此函数。现在,日志确实通知我t.currency已更新为CAD。但是,当我在HomeViewController中再次检索数据并记录货币时,它又回到了CAN。这是HomeViewController中的代码,

NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *transaction = [NSEntityDescription entityForName:@"Transaction" inManagedObjectContext:_managedObjectContext];
[request setEntity:transaction];
request.predicate = [NSPredicate predicateWithFormat:@"transactionToUser = %@", [self.content objectAtIndex:i]];

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"postdate" ascending:NO];
NSArray *descriptors = [[NSArray alloc] initWithObjects:descriptor, nil];
[request setSortDescriptors:descriptors];

NSError *error = nil;
NSMutableArray *mutableResult = [[_managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
if (mutableResult == nil) {
    //handle error
}

for (int k = 0; k < [mutableResult count]; k++) {
    Transaction *t = [mutableResult objectAtIndex:k];
    NSLog(@"currency xx: %@", t.currency);
}

我做错了什么?任何帮助表示赞赏。感谢。

1 个答案:

答案 0 :(得分:0)

使用不同的for循环修复它。

for (Transaction *t in results) 
{
    ...
}