核心数据不保存递增的整数

时间:2014-07-10 02:21:23

标签: ios objective-c core-data properties sprite-kit

我正在制作一个SpriteKit游戏,我需要使用Core Data保存玩家的分数。我有一个int值属性,开始时设置为“5”并将其增加x次。我保存它然后转换到另一个场景并获取它。它以初始值“5”显示未递增。

我是Core Data的新手,请原谅我这是一个愚蠢的问题,但是如何才能让核心数据增加到帐户?信息丢失了当我引用该属性时,我该如何防止这种情况?

    self.score = 5;

    self.score++

然后通过调用此方法进行保存。

AppDelegate.m

-(void) createObject {

    Score *scoreEntity = (Score *)[NSEntityDescription
                         insertNewObjectForEntityForName:@"Score"
                         inManagedObjectContext:self.managedObjectContext];

    SpaceshipScene *spaceshipSceneReference = [[SpaceshipScene alloc] init];


    id points = [NSNumber numberWithInteger: spaceshipSceneReference.score];

    scoreEntity.points = points;
    scoreEntity.playerName = @"Joe";


    NSError *error = nil;
    // Saves the managedObjectContext
    if (! [[self managedObjectContext] save:&error] ) {
        NSLog(@"An error! %@", error);
    }
}

这就是我所说的。

SpaceshipScene.m

    AppDelegate *appDelegateReference = [[AppDelegate alloc] init];
        [appDelegateReference createObject];

然后我使用此方法在另一个类/场景中获取它

AppDelegate.m

-(void)fetchObject {

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

    // Sort fetched data
    NSSortDescriptor *sortByPoints = [[NSSortDescriptor alloc] initWithKey:@"points" ascending:NO];
    // Put them in an array
    NSArray *sortDescriptor = [[NSArray alloc] initWithObjects:sortByPoints, nil];

    // Pass the array to the fetch request
    [fetchRequest setSortDescriptors:sortDescriptor];


    NSError *error = nil;
    NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"Problem %@", error);
    }

    for (Score *s in fetchedObjects) {
        NSLog(@" %@ %d",s.playerName, [s.points integerValue]);
    }
}

这就是我在最终场景/类中调用它的方式

    AppDelegate *appDelegateReference = [[AppDelegate alloc] init];
    [appDelegateReference fetchObject];

1 个答案:

答案 0 :(得分:0)

希望这会有用,在获取您的Score实体后,只需在其中指定新值,不要使用insert对象更新任何值。

 [scoreEntity setPoints:[NSNumber numberWithInteger: spaceshipSceneReference.score]];
 [scoreEntity setPlayerName:@"Joe"];

然后保存值:

NSError *error = nil;
// Saves the managedObjectContext
if (! [[self managedObjectContext] save:&error] ) {
    NSLog(@"An error! %@", error);
}