数据持久化

     首先是cocos2d-x自己封闭的CCUserDefault跨平台的文件存储类,它是用的xml格式,具体操作非常类似于应用开发的ini文件,可操作性不是很强,如果存取比较复杂的数据,那就得自己动手去解析一个字符串,下面是示例代码,基本一看就懂:

void UserDefaultTest::doTest()
{
    CCLOG("********************** init value ***********************");

    // set default value

    CCUserDefault::sharedUserDefault()->setStringForKey("username", "value1");
    CCUserDefault::sharedUserDefault()->setIntegerForKey("integer", 10);
    CCUserDefault::sharedUserDefault()->setFloatForKey("float", 2.3f);
    CCUserDefault::sharedUserDefault()->setDoubleForKey("double", 2.4);
    CCUserDefault::sharedUserDefault()->setBoolForKey("bool", true);

    // print value

    string ret = CCUserDefault::sharedUserDefault()->getStringForKey("string");
    CCLOG("string is %s", ret.c_str());

    double d = CCUserDefault::sharedUserDefault()->getDoubleForKey("double");
    CCLOG("double is %f", d);

    int i = CCUserDefault::sharedUserDefault()->getIntegerForKey("integer");
    CCLOG("integer is %d", i);

    float f = CCUserDefault::sharedUserDefault()->getFloatForKey("float");
    CCLOG("float is %f", f);

    bool b = CCUserDefault::sharedUserDefault()->getBoolForKey("bool");
    if (b)
    {
        CCLOG("bool is true");
    }
    else
    {
        CCLOG("bool is false");
    }
    
    //CCUserDefault::sharedUserDefault()->flush();

    CCLOG("********************** after change value ***********************");

    // change the value

    CCUserDefault::sharedUserDefault()->setStringForKey("username", "daoxwj");
    CCUserDefault::sharedUserDefault()->setIntegerForKey("integer", 11);
    CCUserDefault::sharedUserDefault()->setFloatForKey("float", 2.5f);
    CCUserDefault::sharedUserDefault()->setDoubleForKey("double", 2.6);
    CCUserDefault::sharedUserDefault()->setBoolForKey("bool", false);

    CCUserDefault::sharedUserDefault()->flush();

    // print value

    ret = CCUserDefault::sharedUserDefault()->getStringForKey("string");
    CCLOG("string is %s", ret.c_str());

    d = CCUserDefault::sharedUserDefault()->getDoubleForKey("double");
    CCLOG("double is %f", d);

    i = CCUserDefault::sharedUserDefault()->getIntegerForKey("integer");
    CCLOG("integer is %d", i);

    f = CCUserDefault::sharedUserDefault()->getFloatForKey("float");
    CCLOG("float is %f", f);

    b = CCUserDefault::sharedUserDefault()->getBoolForKey("bool");
    if (b)
    {
        CCLOG("bool is true");
    }
    else
    {
        CCLOG("bool is false");
    }
}
    很明显,这个xml文件d是明文的,如果你想稍微加密下,可以考虑用Base64,加密之后对数据做些处理,然后解密之前可以做些逆处理,这样貌似保险一点点。

    

你可能感兴趣的:(cocos2d-x,+,lua)