2012-11-18 4 views
4

레벨과 관련된 많은 자료가있어서 저장해야합니다. 플레이어가 휴대 전화를 켜고 끄더라도 장치를 다시 시작하고 게임을 종료해도 저장됩니다. 기본적으로 영구 데이터입니다. 저는 많은 옵션을 살펴 보았지만 필요한 것이 무엇인지에 대해 간단하고 명확한 방법을 찾지 못했습니다. 누군가가 나를 도우 려하고 내 요구에 가장 적합한 방법의 기초를 구현하는 방법을 명확하게 보여주기를 바랍니다.iOS Cocos2d 게임용 게임 데이터를 저장하는 방법은 무엇입니까?

(이 환경 설정에 대한의로, 최고의 분명히하지, 내가 이해) 나는 다음과 같은 NSUSerDefaults 살펴 보았다 NSCoder/NSKeyedArchiver은 (단지 하나 하나 개의 클래스에서 간단한 데이터 유형을 저장하는 명확한 방법을 알아낼 수 없습니다 모든 데이터가 속성으로 저장 됨) SQLite3 (완전히 손실 됨)

모든 도움과 지침을 주시면 감사하겠습니다.

내 프로그램에서 저장하고 쉽게 액세스해야하는 데이터 유형은 NSStrings, NSArrays, Ints, Bools입니다.

도움 주셔서 감사 드리며 명확한 답변을 얻으시기 바랍니다.

+0

NSUserDefaults는 완벽 할 것입니다. 저장하는 데이터의 양에 대한 올바른 저장 옵션입니다. – MaxGabriel

+0

고맙습니다. NSUserDefaults는 단순함 때문에 끝났지 만 저장하지는 않습니다. 다른 저장 방법에 대한 코드 오버 헤드는 데이터가 얼마나 간단한 지 이해할 수 없습니다. –

답변

9

NSUserDefaults에 저장하는 데는 아무런 문제가 없지만 디스크에 속성을 저장하려면 .plist 파일로 저장 한 다음 나중에 검색 할 수 있도록 몇 가지 코드를 작성해야합니다. 이 gist에서도 찾을 수 있습니다.

Archives and Serialization Programming Guide을 확인, 추가 읽기를 위해로드

// Fetch NSDictionary containing possible saved state 
NSString *errorDesc = nil; 
NSPropertyListFormat format; 
NSString *plistPath; 
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
                  NSUserDomainMask, YES) objectAtIndex:0]; 
plistPath = [rootPath stringByAppendingPathComponent:@"SavedState.plist"]; 
NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath]; 
NSDictionary *unarchivedData = (NSDictionary *)[NSPropertyListSerialization 
             propertyListFromData:plistXML 
             mutabilityOption:NSPropertyListMutableContainersAndLeaves 
             format:&format 
             errorDescription:&errorDesc]; 

// If NSDictionary exists, look to see if it holds a saved game state 
if (!unarchivedData) 
{ 
    NSLog(@"Error reading plist: %@, format: %d", errorDesc, format); 
} 
else 
{ 
    // Load property list objects directly 
    NSString *myString = [unarchivedData objectForKey:@"MyString"]; 

    // Load primitives 
    NSNumber *boolValue = [unarchivedData objectForKey:@"SomeBoolValue"]; 
    BOOL someBool = [boolValue boolValue]; 
    NSNumber *integerValue = [unarchivedData objectForKey:@"SomeIntegerValue"]; 
    BOOL someBool = [integerValue integerValue]; 

    // Load your custom objects that conform to NSCoding 
    NSData *someObjectData = [unarchivedData objectForKey:@"SomeObject"]; 
    MyClass *someObject = [NSKeyedUnarchiver unarchiveObjectWithData:someObjectData]; 
} 

// We're going to save the data to SavedState.plist in our app's documents directory 
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 
NSString *plistPath = [rootPath stringByAppendingPathComponent:@"SavedState.plist"]; 

// Create a dictionary to store all your data 
NSMutableDictionary *dataToSave = [NSMutableDictionary dictionary]; 

// Store any NSData, NSString, NSArray, NSDictionary, NSDate, and NSNumber directly. See "NSPropertyListSerialization Class Reference" for more information. 
NSString *myString = @"Hello!" 
[dataToSave setObject:myString forKey:@"MyString"]; 

// Wrap primitives in NSValue or NSNumber objects. Here are some examples: 
BOOL someBool = YES; 
NSNumber *boolValue = [NSNumber numberWithBool:someBool]; 
[dataToSave setObject:boolValue forKey:@"SomeBoolValue"]; 
int someInteger = 99; 
NSInteger *integerValue = [NSNumber numberWithInteger:someInteger]; 
[dataToSave setObject:integerValue forKey:@"SomeIntegerValue"]; 

// Any objects that conform to NSCoding can be archived to an NSData instance. In this example, MyClass conforms to NSCoding. 
MyClass *someObject = [[MyClass alloc] init]; 
NSData *archivedStateOfSomeObject = [NSKeyedArchiver archivedDataWithRootObject:someObject]; 
[dataToSave setObject:archivedStateOfSomeObject forKey:@"SomeObject"]; 

// Create a serialized NSData instance, which can be written to a plist, from the data we've been storing in our NSMutableDictionary 
NSString *errorDescription; 
NSData *serializedData = [NSPropertyListSerialization dataFromPropertyList:dataToSave 
                    format:NSPropertyListXMLFormat_v1_0 
                  errorDescription:&errorDescription]; 
if(serializedData) 
{ 
    // Write file 
    NSError *error; 
    BOOL didWrite = [serializedData writeToFile:plistPath options:NSDataWritingFileProtectionComplete error:&error]; 

    NSLog(@"Error while writing: %@", [error description]); 

    if (didWrite) 
     NSLog(@"File did write"); 
    else 
     NSLog(@"File write failed"); 
} 
else 
{ 
    NSLog(@"Error in creating state data dictionary: %@", errorDescription); 
} 

저장.

+0

이것은 나를 위해 일했습니다. 감사. –