SpriteKit 게임을 만들고 있으며 Core Data를 사용하여 플레이어의 점수를 저장해야합니다. int 값이 "5"로 설정되고 x만큼 증가하는 속성이 있습니다. 저장 한 다음 다른 장면으로 전환하고 가져옵니다. 초기 값 "5"로 증분되지 않은 상태로 표시됩니다.
저는 Core Data를 처음 사용하므로 이것이 어리석은 질문이라면 용서하십시오. 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];
이것이 작동하기를 바랍니다. Score 항목을 가져온 후 단순히 새 값을 할당하고 값을 업데이트하기 위해 삽입 개체를 사용하지 마십시오.
[scoreEntity setPoints:[NSNumber numberWithInteger: spaceshipSceneReference.score]];
[scoreEntity setPlayerName:@"Joe"];
그런 다음 값을 저장하십시오.
NSError *error = nil;
// Saves the managedObjectContext
if (! [[self managedObjectContext] save:&error] ) {
NSLog(@"An error! %@", error);
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다