UserDefault运行时错误

使用UserDefault写数据,会不定期出现

Get data from file(xxx/frameworks/runtime-src/proj.win32/Debug.win32/UserDefault.xml) failed, error code is 0
can not read xml file

的错误

顶一下!!!

搞了很久,终于搞定。

主要原因是写入文件的时候,不能保证每次都成功。

static void setValueForKey(const char* pKey, const char* pValue)
{
tinyxml2::XMLElement* rootNode;
tinyxml2::XMLDocument* doc;
tinyxml2::XMLElement* node;
// check the params
if (! pKey || ! pValue)
{
return;
}
// find the node
node = getXMLNodeForKey(pKey, &rootNode, &doc);

// if node exist, change the content
if (node)
{
    if (node->FirstChild())
    {
        node->FirstChild()->SetValue(pValue);
    }
    else
    {
        tinyxml2::XMLText* content = doc->NewText(pValue);
        node->LinkEndChild(content);
    }
}
else
{
    if (rootNode)
    {
        tinyxml2::XMLElement* tmpNode = doc->NewElement(pKey);//new tinyxml2::XMLElement(pKey);
        rootNode->LinkEndChild(tmpNode);
        tinyxml2::XMLText* content = doc->NewText(pValue);//new tinyxml2::XMLText(pValue);
        tmpNode->LinkEndChild(content);
    }    
}

// save file and free doc
if (doc)
{
    doc->SaveFile(UserDefault::getInstance()->getXMLFilePath().c_str());
    delete doc;
}

}

node = getXMLNodeForKey(pKey, &rootNode, &doc);
返回的node为空,但是rootNode,doc没有赋初值,不能保证为空,而进行下一步操作,其实只要
tinyxml2::XMLElement* rootNode=NULL;
tinyxml2::XMLDocument* doc=NULL;
tinyxml2::XMLElement* node=NULL;
然后保证getXMLNodeForKey 失败时候不会改变传入的参数值即可。