저는 SpriteKit 게임을 만들고 있는데 핵심 데이터를 사용하여 플레이어의 점수를 저장해야합니다. 나는 "5"로 설정되고 x 번 증가하는 int 값을 가진 속성을 가지고 있습니다. 나는 그것을 저장하고 다른 장면으로 전환하고 가져옵니다. 초기 값 "5"로 un-incremented로 표시됩니다.코어 데이터가 증가 된 정수를 저장하지 않습니다.
코어 데이터를 처음 사용하기 때문에 어리석은 질문 인 경우 용서해주세요. 어떻게 코어 데이터를 고려하여 계정을 늘릴 수 있습니까? 또는 재산을 참조 할 때 정보가 유실되었으며이를 방지하려면 어떻게해야합니까?
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];
하는 컨텍스트를 저장합니다. – Ryan
값을 변경 한 후에 "createobject"메서드를 호출하면 메서드의 끝에 if 문이 나에게 맞는 컨텍스트를 저장하지 않습니까? 아니면 잘못된 가정입니까? if (! [[self managedObjectContext] save : & error]) { NSLog (@ "오류! % @", 오류); } – user3822584
어디서나 self.score를 사용하고 있습니다. – LyricalPanda