#Cocos2dx+Lua源碼#UserDefault類

歡迎前往個人博客 駑馬點滴 和視頻空間 嗶哩嗶哩-《挨踢日志》

序言

在開發的過程中,我們會遇到這樣的一些需求:

  • 用戶注冊完賬號(如:UserAccount),在下次登錄的時候,能夠默認顯示該登錄的賬戶
  • 用戶設置了禁止音效禁止背景音樂等內容,在下次登錄的時候,希望能夠保持設置

于是,在開發的過程中,我們將這一類需求,抽象成:

本地數據存儲功能

Cocos2dx+Lua引擎中的UserDefault類,就為我們實現了其中一類數據的存儲。


UserDefault 類詳解

下面,將圍繞2點進行展開:

  1. UserDefault類的功能;
  1. UserDefault類的定義與實現;

功能

  • UserDefault 類在本地(指手機writable path下)創建一個UserDefault.xml文件,來作為存儲的數據庫。
  • UserDefault.xml 可以存儲以下的數據類型:布爾類型整型單精度浮點型雙精度浮點型字符串類型Data類型
  • UserDefault 提供了字符串為關鍵字的寫入讀取的API接口。

類定義與實現

類的定義

頭文件UserDefault.h如下:

#ifndef __SUPPORT_CCUSERDEFAULT_H__
#define __SUPPORT_CCUSERDEFAULT_H__
#include "platform/CCPlatformMacros.h"
#include <string>
#include "base/CCData.h"

/**
 * @addtogroup base
 * @{
 */
NS_CC_BEGIN


/**
 * UserDefault acts as a tiny database. You can save and get base type values by it.
 * For example, setBoolForKey("played", true) will add a bool value true into the database.
 * Its key is "played". You can get the value of the key by getBoolForKey("played").
 * 
 * It supports the following base types:
 * bool, int, float, double, string
 */
class CC_DLL UserDefault
{
public:
    // get value methods

    /**
     * Get bool value by key, if the key doesn't exist, will return false.
     * You can set the default value, or it is false.
     * @param key The key to get value.
     * @return Bool value by `key`.
     * @js NA
     */
    bool    getBoolForKey(const char* key);
    
    /**
     * Get bool value by key, if the key doesn't exist, will return passed default value.
     * @param key The key to get value.
     * @param defaultValue The default value to return if the key doesn't exist.
     * @js NA
     */
    virtual bool getBoolForKey(const char* key, bool defaultValue);
    
    /**
     * Get integer value by key, if the key doesn't exist, will return 0.
     * You can set the default value, or it is 0.
     * @param key The key to get value.
     * @return Integer value of the key.
     * @js NA
     */
    int     getIntegerForKey(const char* key);
    
    /**
     * Get bool value by key, if the key doesn't exist, will return passed default value.
     * @param key The key to get value.
     * @param defaultValue The default value to return if the key doesn't exist.
     * @return Integer value of the key.
     * @js NA
     */
    virtual int getIntegerForKey(const char* key, int defaultValue);
    
    /**
     * Get float value by key, if the key doesn't exist, will return 0.0.
     * @param key The key to get value.
     * @return Float value of the key.
     * @js NA
     */
    float    getFloatForKey(const char* key);
    
    /**
     * Get float value by key, if the key doesn't exist, will return passed default value.
     * @param key The key to get value.
     * @param defaultValue The default value to return if the key doesn't exist.
     * @return Float value of the key.
     * @js NA
     */
    virtual float getFloatForKey(const char* key, float defaultValue);
    
    /**
     * Get double value by key, if the key doesn't exist, will return 0.0.
     * @param key The key to get value.
     * @return Double value of the key.
     * @js NA
     */
    double  getDoubleForKey(const char* key);
    
    /**
     * Get double value by key, if the key doesn't exist, will return passed default value.
     * @param key The key to get value.
     * @param defaultValue The default value to return if the key doesn't exist.
     * @return Double value of the key.
     * @js NA
     */
    virtual double getDoubleForKey(const char* key, double defaultValue);
    
    /**
     * Get string value by key, if the key doesn't exist, will return an empty string.
     * @param key The key to get value.
     * @return String value of the key.
     * @js NA
     */
    std::string getStringForKey(const char* key);
    
    /**
     * Get string value by key, if the key doesn't exist, will return passed default value.
     * @param key The key to get value.
     * @param defaultValue The default value to return if the key doesn't exist.
     * @return String value of the key.
     * @js NA
     */
    virtual std::string getStringForKey(const char* key, const std::string & defaultValue);
    
    /**
     * Get Data value by key, if the key doesn't exist, will return an empty Data.
     * @param key The key to get value.
     * @return Data value of the key.
     * @js NA
     */
    Data getDataForKey(const char* key);
    
    /**
     * Get Data value by key, if the key doesn't exist, will return an empty Data.
     * @param key The key to get value.
     * @param defaultValue The default value to return if the key doesn't exist.
     * @return Data value of the key.
     * @js NA
     */
    virtual Data getDataForKey(const char* key, const Data& defaultValue);

    // set value methods

    /**
     * Set bool value by key.
     * @param key The key to set.
     * @param value A bool value to set to the key.
     * @js NA
     */
    virtual void setBoolForKey(const char* key, bool value);
    /**
     * Set integer value by key.
     * @param key The key to set.
     * @param value A integer value to set to the key.
     * @js NA
     */
    virtual void setIntegerForKey(const char* key, int value);
    /**
     * Set float value by key.
     * @param key The key to set.
     * @param value A float value to set to the key.
     * @js NA
     */
    virtual void setFloatForKey(const char* key, float value);
    /**
     * Set double value by key.
     * @param key The key to set.
     * @param value A double value to set to the key.
     * @js NA
     */
    virtual void setDoubleForKey(const char* key, double value);
    /**
     * Set string value by key.
     * @param key The key to set.
     * @param value A string value to set to the key.
     * @js NA
     */
    virtual void setStringForKey(const char* key, const std::string & value);
    /**
     * Set Data value by key.
     * @param key The key to set.
     * @param value A Data value to set to the key.
     * @js NA
     */
    virtual void setDataForKey(const char* key, const Data& value);
    /**
     * You should invoke this function to save values set by setXXXForKey().
     * @js NA
     */
    virtual void flush();

    /**
    * delete any value by key,
    * @param key The key to delete value.
    * @js NA
    */
    virtual void deleteValueForKey(const char* key);
    
    /** Returns the singleton.
     * @js NA
     * @lua NA
     */
    static UserDefault* getInstance();
    /**
     * @js NA
     */
    static void destroyInstance();

    /**
    * You can inherit from platform dependent implementation of UserDefault, such as UserDefaultAndroid,
    * and use this function to set delegate, then UserDefault will invoke delegate's implementation.
    * For example, your store native data base or other format store.
    *
    * If you don't want to system default implementation after setting delegate, you can just pass nullptr
    * to this function.
    *
    * @warning It will delete previous delegate
    */
    static void setDelegate(UserDefault *delegate);

    /** @deprecated Use getInstace() instead.
     * @js NA
     * @lua NA
     */
    CC_DEPRECATED_ATTRIBUTE static UserDefault* sharedUserDefault();
    /**@deprecated Use destroyInstance() instead.
     * @js NA
     */
    CC_DEPRECATED_ATTRIBUTE static void purgeSharedUserDefault();
    /** All supported platforms other iOS & Android use xml file to save values. This function is return the file path of the xml path.
     * @js NA
     */
    static const std::string& getXMLFilePath();
    /** All supported platforms other iOS & Android and CC_PLATFORM_WINRT use xml file to save values. This function checks whether the xml file exists or not.
     * @return True if the xml file exists, false if not.
     * @js NA
     */
    static bool isXMLFileExist();

protected:
    UserDefault();
    virtual ~UserDefault();
    
private:
    
    static bool createXMLFile();
    static void initXMLFilePath();
    
    static UserDefault* _userDefault;
    static std::string _filePath;
    static bool _isFilePathInitialized;
};


NS_CC_END
// end of base group
/** @} */

#endif // __SUPPORT_CCUSERDEFAULT_H__

為了方便起見,我們可以查看類視圖。


UserDefault.png

其中,方法名左側有一個圖標,它有三種不同的樣式:

Public樣式(圖標右下角為空)


Public

Protected樣式(圖標右下角為星號)


Protected

Private樣式(圖標右下角為鎖)


Private

字段的左側圖標,同理。

類的字段

類的Static字段初始化

UserDefault* UserDefault::_userDefault = nullptr;
string UserDefault::_filePath = string("");
bool UserDefault::_isFilePathInitialized = false;
  • _userDefault : UserDefault是一個單例,類的實例存儲在_userDefault字段中
  • _filePath : 記錄UserDefault.xml文件所在路徑(此處初始化為可讀寫路徑/UserDefault.xml)
  • _isFilePathInitialized:標記_filePath是否被初始化
類的方法

類的方法,其作用,在UserDefault中說的非常明白,這里不做重復的闡述。
只做一些補充:

  • 構造函數和析構函數放空,沒有業務邏輯,被聲明為Protected,可以被子類繼承,進行功能擴展。

類的實現:

  • 類的實現過程中,構建了特定結構的xml表:
<?xml version="1.0" encoding="UTF-8"?>
<userDefaultRoot>
    <Key1>Value1</Key1>
    <Key2>Value2</Key1>
    <Key3>Value3</Key1>
</userDefaultRoot>
  • 類中提供了6類數據結構的讀取和寫入接口,其實現,都是利用了tinyxml2類來操作規定了存儲結構的xml文件,對返回的數據做類型轉換。
tolua

lua_cocos2dx_auto.cpp文件中,注冊了lua端調用此類的接口

int lua_register_cocos2dx_UserDefault(lua_State* tolua_S)
{
    tolua_usertype(tolua_S,"cc.UserDefault");
    tolua_cclass(tolua_S,"UserDefault","cc.UserDefault","",nullptr);

    tolua_beginmodule(tolua_S,"UserDefault");
        tolua_function(tolua_S,"setIntegerForKey",lua_cocos2dx_UserDefault_setIntegerForKey);
        tolua_function(tolua_S,"deleteValueForKey",lua_cocos2dx_UserDefault_deleteValueForKey);
        tolua_function(tolua_S,"getFloatForKey",lua_cocos2dx_UserDefault_getFloatForKey);
        tolua_function(tolua_S,"getBoolForKey",lua_cocos2dx_UserDefault_getBoolForKey);
        tolua_function(tolua_S,"setDoubleForKey",lua_cocos2dx_UserDefault_setDoubleForKey);
        tolua_function(tolua_S,"setFloatForKey",lua_cocos2dx_UserDefault_setFloatForKey);
        tolua_function(tolua_S,"getStringForKey",lua_cocos2dx_UserDefault_getStringForKey);
        tolua_function(tolua_S,"setStringForKey",lua_cocos2dx_UserDefault_setStringForKey);
        tolua_function(tolua_S,"flush",lua_cocos2dx_UserDefault_flush);
        tolua_function(tolua_S,"getIntegerForKey",lua_cocos2dx_UserDefault_getIntegerForKey);
        tolua_function(tolua_S,"getDoubleForKey",lua_cocos2dx_UserDefault_getDoubleForKey);
        tolua_function(tolua_S,"setBoolForKey",lua_cocos2dx_UserDefault_setBoolForKey);
        tolua_function(tolua_S,"destroyInstance", lua_cocos2dx_UserDefault_destroyInstance);
        tolua_function(tolua_S,"getXMLFilePath", lua_cocos2dx_UserDefault_getXMLFilePath);
        tolua_function(tolua_S,"isXMLFileExist", lua_cocos2dx_UserDefault_isXMLFileExist);
    tolua_endmodule(tolua_S);
    std::string typeName = typeid(cocos2d::UserDefault).name();
    g_luaType[typeName] = "cc.UserDefault";
    g_typeCast["UserDefault"] = "cc.UserDefault";
    return 1;
}

總結

在通讀這個類后,我們完成了UserDefault類的源代碼閱讀。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容