~~~~本文章为 OwenTsang(fromOld-Boys-Studio)原创,转载务必在明显处注明:
原文连接:http://blog.csdn.net/owen_c/article/details/9750419
Cocos2dx如何保存一个数据的数据呢?只对于初学者来说,总感觉有点麻烦,特别是从cocos2d-iphone转过来cocos2dx的同学们,更是很烦恼,在IOS中使用NSKeyedArchiver和NSKeyedUnrarchiver就可以很容易地对数组的数据归档了,但初涉cocos2dx的同学感觉有点无措了,其实这果中方法很简单,就是加一个索引下标就可以了。闲话不叙,下面说说怎么加吧。
1 仿造NSCoding的OBCoding
- class OBCoding: public CCObject
- {
- protected:
- OBCoding():CCObject(){}
- public:
- virtual void encodeWithCoder(CCUserDefault* encoder,const char* primerKey = NULL) = 0;
- virtual OBCoding* initWithCoder(CCUserDefault* decoder,const char* primerKey = NULL) = 0;
- };
2 仿造NSKeyedArchiver宏
- #define OB_ARCHIVED_ARRAY(xmlWriter,arrayName,array) \
- {\
- if(!xmlWriter ||!arrayName || !array)\
- return;\
- int count =array->count();\
- xmlWriter->setIntegerForKey(CCString::createWithFormat("%s_count",arrayName)->getCString(),count);\
- for(int i = 0; i < count ; ++i)\
- {\
- OBCoding* coder= (OBCoding*)array->objectAtIndex(i);\
- coder->encodeWithCoder(xmlWriter,CCString::createWithFormat("%s_%d",arrayName,i)->getCString());\
- }\
- }
3 仿造NSKeyedUnrarchiver宏
- #define OB_UNARCHIVED_ARRAY(unarchivedArray,xmlReader,arrayName,TYPE_NAME)\
- {\
- if(!xmlReader ||!arrayName){\
- unarchivedArray= NULL; \
- }\
- else{\
- int count = 0; \
- OBCoding* coder= NULL;\
- count =xmlReader->getIntegerForKey(CCString::createWithFormat("%s_count",arrayName)->getCString(),count);\
- if(count <= 0){\
- unarchivedArray = NULL; \
- }\
- else{\
- unarchivedArray = CCArray::createWithCapacity(count);\
- for(int i = 0; i < count ; ++i)\
- {\
- coder =dynamic_cast<OBCoding*>(new TYPE_NAME());\
- assert(coder);\
- coder->initWithCoder(xmlReader,CCString::createWithFormat("%s_%d",arrayName,i)->getCString());\
- unarchivedArray->addObject(coder);\
- coder->release();\
- }\
- }\
- }\
- }
4 测试
1) 归档打包:
- CCUserDefault* writer = CCUserDefault::sharedUserDefault();
- OB_ARCHIVED_ARRAY(writer,"ClassOne",classOneArray);
- writer->flush();
2) 归档解包
- CCArray* classOneArray = NULL;
- CCUserDefault* reader = CCUserDefault::sharedUserDefault();
- OB_UNARCHIVED_ARRAY(classOneArray,reader,"ClassOne",Student);
5 测试结果:
Cocos2d: enterfunction testArrayArchived()~~
Cocos2d: displayClass One students' detail now ~~
Cocos2d: id = 1,name = Owen1
Cocos2d: id = 2,name = Owen2
Cocos2d: id = 3,name = Owen3
Cocos2d: enterfunction testArrayUnarchived().....
Cocos2d: displayClass One students' detail now ~~
Cocos2d: id = 1,name = Owen1
Cocos2d: id = 2,name = Owen2
Cocos2d: id = 3, name = Owen3
6 源码及demo下载地址
https://github.com/OwenTsang/TestArrayArchived
~~~~本文章为 OwenTsang(fromOld-Boys-Studio)原创,转载务必在明显处注明: