cocos-js,数据本地存储

一、前言

cocos-js 3.0以上的版本中,当我们用到本地存储的时候,发现以前用到的UserDefault在JS中并没有导出,而是换成了LocalStorage。


二、基本使用

/** Initializes the database. If path is null,it will create an in-memory DB. */
void CC_DLL localStorageInit( const std::string& fullpath = "");

/** Frees the allocated resources. */
void CC_DLL localStorageFree();

/** Sets an item in the JS. */
void CC_DLL localStorageSetItem( const std::string& key,const std::string& value);

/** Gets an item from the JS. */
bool CC_DLL localStorageGetItem( const std::string& key,std::string *outItem );

/** Removes an item from the JS. */
void CC_DLL localStorageRemoveItem( const std::string& key );

/** Removes all items from the JS. */
void CC_DLL localStorageClear();

LocalStorage.h文件中我们查看了一下源码,使用方法就是设置Key-Value的方式

  • 存储数据:cc.sys.localStorage.setItem(“key”,”value”)
  • 获取数据:cc.sys.localStorage.getItem(“key”)
  • 移除数据:cc.sys.localStorage.removeItem(“key”)
  • 清除所有:cc.sys.localStorage.clear()

三、重点注意

void localStorageSetItem( const std::string& key,const std::string& value)
{
    assert( _initialized );

    int ok = sqlite3_bind_text(_stmt_update,1,key.c_str(),-1,SQLITE_TRANSIENT);
    ok |= sqlite3_bind_text(_stmt_update,2,value.c_str(),SQLITE_TRANSIENT);

    ok |= sqlite3_step(_stmt_update);

    ok |= sqlite3_reset(_stmt_update);

    if( ok != SQLITE_OK && ok != SQLITE_DONE)
        printf("Error in localStorage.setItem()\n");
}

在setItem的实现方法中,我们可以看到是使用了sqlite3数据库的方法实现本地存储。
并且,我们只能保存字符串数据,所以如果要保存其他类型的数据的时候,要记得进行数据转换。


四、模仿UserDefault实现数据封装

var LocalKeyConst = {
    IS_SHIP_SKIP : "IS_SHIP_SKIP",//战舰自动跳过动画
}

var LocalManager = {

    setBool:function(_key,_value){
        cc.sys.localStorage.setItem(_key,_value.toString())
    },getBool:function(_key){
        return cc.sys.localStorage.getItem(_key) == "false" ? false : true
    },setInt:function(_key,getInt:function(_key){
        return Number(cc.sys.localStorage.getItem(_key))
    },setString:function(_key,_value)
    },getString:function(_key){
        return cc.sys.localStorage.getItem(_key)
    },setObject:function(_key,JSON.stringify(_value))
    },getObject:function(_key){
        return JSON.parse(cc.sys.localStorage.getItem(_key))
    },}

相关文章

    本文实践自 RayWenderlich、Ali Hafizji 的文章《...
Cocos-code-ide使用入门学习地点:杭州滨江邮箱:appdevzw@1...
第一次開始用手游引擎挺激动!!!进入正题。下载资源1:从C...
    Cocos2d-x是一款强大的基于OpenGLES的跨平台游戏开发...
1.  来源 QuickV3sample项目中的2048样例游戏,以及最近《...
   Cocos2d-x3.x已经支持使用CMake来进行构建了,这里尝试...