1

我是 coreData 的新手,我正在开发一个示例应用程序,在该示例应用程序中,我向一个名为“Test”的实体添加了一个名为 displayOrder 的浮点类型属性。我想在添加每个测试对象时增加这个显示顺序。为此,我编写了以下代码,但它不起作用,我想知道我哪里出错了

- (void)insertNewObject:(NSString *)fileName
{    
    Test *testName = [NSEntityDescription insertNewObjectForEntityForName:@"Test" inManagedObjectContext:self.managedObjectContext];

    [testName setName:fileName];

    NSManagedObject *lastObject = [self.controller.fetchedObjects lastObject];
    float lastObjectDisplayOrder = [[lastObject valueForKey:@"displayOrder"] floatValue];
    NSLog(@"%f",lastObjectDisplayOrder);
    [testName setValue:[NSNumber numberWithDouble:lastObjectDisplayOrder + 1.0] forKey:@"displayOrder"];

    // Save the context.
    NSError *error = nil;
    if (![self.managedObjectContext save:&error]) {
        // Replace this implementation with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
}

实际上,问题是它第一次递增,即从 0 到 1,但在此之后我总是得到 1。

问候兰吉特

4

2 回答 2

0

您的问题可能与您加载 lastObject 的部分有关,您可能不会更新 fetchedresultscontroller,我建议创建一个 iVar 并在 init 或 viewDidLoad 上分配值,然后使用该 iVar 更新并获得正确的值,如果您不为此使用小数,并且只需要顺序,那么整数应该会更好。

于 2012-11-06T07:19:48.267 回答
0

您可以使用核心数据聚合函数来获取最大 displayOrder 值。

就像是:

- (NSNumber *)nextDisplayOrder {
    NSManagedObjectContext *context = self.managedObjectContext;

    NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Test" inManagedObjectContext:context];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entityDescription];
    [request setResultType:NSDictionaryResultType];

    NSExpression *keyExpression = [NSExpression expressionForKeyPath:@"displayOrder"];
    NSExpression *maxExpression = [NSExpression expressionForFunction:@"max:" arguments:[NSArray arrayWithObject:keyExpression]];

    NSExpressionDescription *description = [[NSExpressionDescription alloc] init];
    [description setName:@"maxDisplayOrder"];
    [description setExpression:maxExpression];
    [description setExpressionResultType:NSFloatAttributeType];

    [request setPropertiesToFetch:[NSArray arrayWithObject:description]];

    NSError *error = nil;
    NSArray *results = [context executeFetchRequest:request error:&error];
    if (results.count == 1) {
        NSNumber *maxDisplayOrder = [[results objectAtIndex:0] valueForKey:@"displayOrder"];
        return [NSNumber numberWithFloat:[maxDisplayOrder floatValue] + 1.f];
    } else {
        NSLog(@"Could not get next displayOrder. Error: %@", error);
    }

    return nil;
}

一些附加说明:

于 2012-11-06T08:26:50.843 回答