iOS核心数据更新实体对象

时间:2011-05-27 21:00:14

标签: iphone ios core-data entity

我正在为iPhone应用程序实施汽车经理而我在保存新车方面遇到了麻烦。所以我有一个“Car”实体(和每个加载的DB),包含多个属性。我有2个布尔“保存”和“选中”来跟踪用户添加到他的列表中的哪辆车(如果添加,保存= 1)以及当前选择了哪辆车。因此,当我创建一辆新车时,我取消选择旧车(选择= 0),并想要修改新车以设置其属性saved = 1和selected = 1.

这是我的职能:

- (IBAction)save
{
    // Disable the previous car selection.
    [self deselectCurrentSelectedCar];

    // Add new car as saved and selected.
    [self saveAndSelectNewCar];

    // Call the delegate to dismiss the modal view.
    [_delegate dismissAndSave];
}

- (void)deselectCurrentSelectedCar
{    
    // Fetched saved car.
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Car" inManagedObjectContext:[self managedObjectContext]];
    [fetchRequest setEntity:entity];

    // Set predicate and sort orderings...
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"selected = 1"];
    [fetchRequest setPredicate:predicate];

    // Execute the fetch -- create a mutable copy of the result.
    NSError *error = nil;
    NSMutableArray *mutableFetchResults = [[self.managedObjectContext executeFetchRequest:fetchRequest error:&error] mutableCopy];
    if (mutableFetchResults == nil) {
        // Handle the error.
        NSLog(@"[AddCarViewController] deselect car: car not found.");
    }
    else {
        // Get car and assign new selected value.
        Car *carToSave = (Car *)[mutableFetchResults objectAtIndex:0];
        [carToSave setSelected:[NSNumber numberWithInt:0]];

        // Save the car.
        NSError *error = nil;
        if (![self.managedObjectContext save:&error]) {
            // Handle the error.
            NSLog(@"[AddCarViewController] deselect car: error saving car.");
        }
        else {
            NSLog(@"[AddCarViewController] deselect car: car saved.");
        }
    }

    // Memory management.
    [fetchRequest release];
    [mutableFetchResults release];
}
- (void)saveAndSelectNewCar
{
    // Get the car, and pass to the delegate the new settings.
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Car" inManagedObjectContext:[self managedObjectContext]];
    [fetchRequest setEntity:entity];

    // Set predicate and sort orderings...
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(year=%@) AND (make=%@) AND (model=%@) AND (d=%@) AND (n=%@)", _car.year, _car.make, _car.model, _car.d, _car.n];
    [fetchRequest setPredicate:predicate];

    // Execute the fetch -- create a mutable copy of the result.
    NSError *error = nil;
    NSMutableArray *mutableFetchResults = [[self.managedObjectContext executeFetchRequest:fetchRequest error:&error] mutableCopy];
    if (mutableFetchResults == nil) {
        // Handle error.
        NSLog(@"[AddCarViewController] save and select: can't save the new car");
    }
    else {
        // Get the car selected.
        Car *selectedCar = (Car *)[mutableFetchResults objectAtIndex:0];
        [selectedCar setValue:[NSNumber numberWithInt:1] forKey:@"selected"];
        [selectedCar setValue:[NSNumber numberWithInt:1] forKey:@"saved"];

        // Save the car.
        NSError *error = nil;
        if (![self.managedObjectContext save:&error]) {
            // Handle the error.
            NSLog(@"[AddCarViewController] save and select: error saving car.");
        }
        else {
            NSLog(@"[AddCarViewController] save and select: car saved.");
        }

        // Add car to delegate.
        [EcoAppAppDelegate setUserCar:selectedCar];
    }

    // Memory management.
    [fetchRequest release];
    [mutableFetchResults release];
}

我一直都有这个日志:“车辆出错了。”两个功能。所以肯定有问题。

此外,获取我想要修改它的汽车非常烦人,而不是马上进行更新。如果有另一个请告诉我!

感谢。

1 个答案:

答案 0 :(得分:3)

在你的头文件中,你应该为你的汽车设置一个可变阵列。

NSMutableArray *carArray;

@property (nonatomic, retain) NSMutableArray *carArray;

然后确保在您的实现文件中合成它。然后,当从托管对象上下文中获取时,可以使用返回的内容设置数组

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Car" inManagedObjectContext:[self managedObjectContext]];
[fetchRequest setEntity:entity];

// Execute the fetch -- create a mutable copy of the result.
NSError *error = nil;
NSMutableArray *mutableFetchResults = [[self.managedObjectContext executeFetchRequest:fetchRequest error:&error] mutableCopy];
if (mutableFetchResults == nil) {
    // Handle the error.
    NSLog(@"[AddCarViewController] deselect car: car not found.");
} else {
    [self setCarArray:mutableFetchResults];
}

执行此操作将保留托管对象上下文中的所有对象,因此当您想要修改Car时,可以在那里找到它而不是再次获取。如果需要对其进行排序,可以将使用其中一个属性初始化的排序描述符作为键应用。例如:

NSSortDescriptor *sorter = [NSSortDescriptor sortDescriptorWithKey:@"selected" ascending:YES];
[carArray sortUsingDescriptors:[NSArray arrayWithObject:sorter]];

这将根据汽车是否被选中对汽车进行分类。

至于为什么你会收到错误,这可能是众多原因之一。通常,如果您的某个属性设置为nil,则MOC将无法保存,因此可能是原因。如果你设置了类似的内容,你可以从中获得一些细节

if (![self.managedObjectContext save:&error]) {
    NSLog(@"failed with error %@", error);
}

这将返回您遇到的实际错误。设置日志以确保指定Car是一个好主意。像NSLog(@"selected car %@", carToSave);之类的东西只是为了安全