将变量存储在属性列表文件Cocos2d中

时间:2012-01-27 23:41:45

标签: variables cocos2d-iphone plist store retain

我正在编写一个cocos2d游戏,在大多数游戏中,您必须完成之前的级别才能继续下一个级别。每个级别位于不同的层(节点)中。我想将整数(1-20)存储到属性列表中,以便在整个游戏中保留变量。是的,我一直在网上搜索大约一个小时,无法找到任何东西。

我找到了存储变量的代码,但我不知道如何正确使用它。

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentPath = [paths objectAtIndex:0];
    NSString *path = [documentPath stringByAppendingPathComponent:@"levelscompleted.save"];


    NSMutableDictionary* myDict = [[NSMutableDictionary alloc] init];


    myDict = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    NSString *nssLevelsCompleted = [myDict objectForKey:@"LevelsCompleted"];
    LevelsCompleted = [nssLevelsCompleted intValue];

    LevelsCompleted = 445;


    [myDict setObject:nssLevelsCompleted forKey:@"LevelsCompleted"];



    [NSKeyedArchiver archiveRootObject:myDict toFile:path];

1 个答案:

答案 0 :(得分:0)

以下是一些获得想法的示例代码(使用ARC进行内存管理):

- (NSString*) filePath {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *filePath = [NSString stringWithFormat:@"%@/%@",documentsDirectory,@"myfile.plist"];
    return filePath;
}

- (void)writeScoreToPlist:(NSInteger)score level:(NSString*)level {
    NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:[self filePath]];    
    if(plistDict==nil){
        plistDict = [[NSMutableDictionary alloc] init];    
    }
    [plistDict setObject:[NSNumber numberWithInteger:score] forKey:level];
    [plistDict writeToFile:[self filePath] atomically: YES];
}

- (NSInteger)readScoreFromPlist:(NSString*)level {
    NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:[self filePath]];
    NSNumber *value = [plistDict objectForKey:level];
    return value.integerValue;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.

    [self writeScoreToPlist:999 level:@"Level1Highscore"];
    NSInteger score = [self readScoreFromPlist:@"Level1Highscore"];
    NSLog(@"Achieved score for level 1: %d",score);

    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}

输出:

2012-01-29 16:24:30.844 plistTest[23531:f803] Achieved score for level 1: 999