Cocos2d-X 學習筆記 21 CCString 分析

CCString

簡介

CCString繼承至CCObject,CCObjecte這個基類主要是爲了自動內存管理而創建的。CCString提供一系列的接口,例如create,convert等等。

常用的方法

創建

    /**使用std::string創建了一個字符串, 你也可以傳遞一個c字符串指針,因爲std::string的構造函數可以訪問c字符串指針

     * @返回的 CCString 指針是一個自動釋放對象,

     *也就意味着你不需要調用release操作,除非你retain了.

     */

    static CCString* create(const std::string& str);

    /**使用格式化方式來創建一個字符串,這個方法和c語言裏面的‘sprintf’類似,默認緩存大小是(1024*100)bytes

     *假如你想要改變這個緩存大小,你可以去CCString.cpp中,更改kMaxStringLen 這個宏定義。


     * @返回的 CCString 指針是一個自動釋放對象,

     *也就意味着你不需要調用release操作,除非你retain了.

     */ 

    static CCString* createWithFormat(const char* format, …);

    /** 使用二進制數據來創建字符串 

     * @返回的 CCString 指針是一個自動釋放對象,

     *也就意味着你不需要調用release操作,除非你retain了.

     */

    static CCString* createWithData(const unsigned char* pData, unsigned long nLen);

    /**使用一個文件來創建一個字符串, 

     * @return A CCString pointer which is an autorelease object pointer,

     * it means that you needn't do a release operation unless you retain it.

     */

    static CCString* createWithContentsOfFile(const char* pszFileName);

轉換

CCString允許CCString實例變量轉換爲另外類型的變量。

    /** convert to int value */

    int intValue() const;

    /** convert to unsigned int value */

    unsigned int uintValue() const;

    /** convert to float value */

    float floatValue() const;

    /** convert to double value */

    double doubleValue() const;

    /** convert to bool value */

    bool boolValue() const;
    

常用的宏定義

#define CCStringMake(str) CCString::create(str)

#define ccs CCStringMake

使用這些宏可以非常方便的構建一個自動釋放的CCString對象。假如你想要新建很多的CCString對象並把他們增加到CCArray中。
使用下面的代碼就可以實現了,並且這些代碼看起來相當簡潔。


CCArray *stringArray = CCArray::create(

        ccs("Hello"),

        ccs("Variable"),

        ccs("Size"),

        ccs("!"),

        NULL);

CCString中有一個getString函數可以獲得字符串。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章