需求,最近做ios程序,需要将用户密码和帐号保存到本地磁盘,而用用户不止一个,想到boost库里的serialization比较适合,用户就用标准库里的map来保存,也就是std::map<std::string, std::string>,代码如下:
UserInfo.h:
//
// UserInfo.h
// app1
//
// Created by xp y on 12-8-23.
// Copyright (c) 2012年 xp y. All rights reserved.
//
#ifndef __app1__UserInfo__
#define __app1__UserInfo__
#import <map>
#import <string>
#import <fstream>
#import <boost/archive/binary_iarchive.hpp>
#import <boost/archive/binary_oarchive.hpp>
#import <boost/serialization/map.hpp>
#include <iostream>
// use this to ease the archive selection
typedef boost::archive::binary_iarchive iarchive;
typedef boost::archive::binary_oarchive oarchive;
class UserInfo
{
friend class boost::serialization::access;
protected :
template <class Archive>
void serialize(Archive& ar, const unsigned int /* file_version */ );
public :
std::map<std::string, std::string> users;
void setData();
void showData();
static void saveData(const std::map<std::string, std::string>& obj, std::string fileName)
{
std::ofstream ofs(fileName.c_str());
oarchive oa(ofs);
oa << obj;
}
static void loadData(std::map<std::string, std::string>& obj, std::string fileName)
{
std::ifstream ifs(fileName.c_str());
iarchive ia(ifs);
ia >> obj;
}
UserInfo();
virtual ~UserInfo();
};
#endif /* defined(__app1__UserInfo__) */
UserInfo.mm:
#include "UserInfo.h"
#import <map>
#import <string>
template <class Archive>
void UserInfo::serialize(Archive& ar, const unsigned int /* file_version */ )
{
ar & users;
}
void UserInfo::setData() {
users["aa"] = "hello";
users["bb"] = "good";
}
void UserInfo::showData() {
std::map<std::string, std::string>::iterator it = users.begin();
std::cout << it->first << ":" << it->second << "\n";
++it;
std::cout << it->first << ":" << it->second << "\n";
}
调用代码:
UserInfo u,u2;
u.mInt = 3 ;
u.setData();
UserInfo::saveData(u.users, "/Users/leejinchen/Downloads/output.txt");
UserInfo::loadData(u2.users, "/Users/leejinchen/Downloads/output.txt");
u2.showData();
输出:
aa:hello
bb:good
注意一定要包含
#import <boost/serialization/map.hpp>,否则会报类似以下错误:
error C2039: 'serialize' : is not a member of 'stdext::map<_Kty,_Ty>'
原因是因为序列化的是map类型,内部是多个键值对,如果序列化非集合类型应该不会出现这种错误 ,
如果你序列化的是其他的集合类型,可以到boost/serialization/下对应的头文件,除此外还要加上链接库
libboost_serialization-xgcc42-d-1_49.a,xcode里是在targets>>build phases>>link binary with libraries
根据平台和版本的不同,xgcc42-d-1_49是会变化的