跳转至

针对h5的本地存储localStorage的扩展

本地存储本质上是存取一个键值对,键和值都是字符串,有时候我们想存储简单的数字或者bool值也会被变成字符串,当然有时候还会想存储一些json格式的数据,这里专门做了封装.
其他类似数组等也可以用同样类似的方法处理

export class LocalStorage
{
    private static _inst:LocalStorage;

    private constructor()
    {
    }

    /** 获取单例*/
    static getInst():LocalStorage
    {
        if(!this._inst)
        {
            this._inst = new LocalStorage();
        }
        return this._inst;
    }

    /** 移除本地存储中的某个键值对*/
    remove(key:string)
    {
        cc.sys.localStorage.removeItem(key);
    }

    /** 清空本地存储*/
    clear()
    {
        cc.sys.localStorage.clear();
    }

    /** 读取string值*/
    getString(key:string, defaultValue = "")
    {
        const value = cc.sys.localStorage.getItem(key);
        if(value != null) {
            return value;
        }
        return defaultValue;
    }

    /** 存储string值*/
    setString(key:string, value:string)
    {
        cc.sys.localStorage.setItem(key, value);
    }

    /** 存储int值*/
    getInt(key:string, defaultValue = 0)
    {
        const value = cc.sys.localStorage.getItem(key);
        if(value != null)
        {
            return parseInt(value);
        }
        return defaultValue;
    }

    /** 读取int值*/
    setInt(key:string, value:number)
    {
        cc.sys.localStorage.setItem(key, value.toString());
    }
    /** 读取boolean值*/
    getBool(key:string, defaultValue = false)
    {
        const value = cc.sys.localStorage.getItem(key);
        if(value != null)
        {
            return parseInt(value) == 1;
        }
        return defaultValue;
    }
    /** 存储boolean值*/
    setBool(key:string, value:boolean)
    {
        cc.sys.localStorage.setItem(key, value ? "1" : "0");
    }
    /** 读取浮点数*/
    getFloat(key:string, defaultValue = 0)
    {
        const value = cc.sys.localStorage.getItem(key);
        if(value != null)
        {
            return parseFloat(value);
        }
        return defaultValue;
    }

    /** 保存浮点数*/
    setFloat(key:string, value:number)
    {
        cc.sys.localStorage.setItem(key, value.toString());
    }

    /** 读取json对象*/
    getJson(key:string, defaultValue = null)
    {
        const value = cc.sys.localStorage.getItem(key);
        if(value != null)
        {
            return JSON.parse(value);
        }
        return defaultValue;
    }
    /** 存储json对象*/
    setJson(key:string, value:object)
    {
        cc.sys.localStorage.setItem(key, JSON.stringify(value));
    }
}

友情链接