欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Objective-C封装字符串存储操作示例

程序员文章站 2022-03-08 16:26:57
objective-c简单封装 字符串的存储操作,省去中间沙盒处理方式 复制代码 代码如下:/存储publickey和sessionid -- writecontent:...

objective-c简单封装 字符串的存储操作,省去中间沙盒处理方式

复制代码 代码如下:

/存储publickey和sessionid -- writecontent: nil - 仅取出数据, 其他 - 修改原内容并提取
+(nsstring *)storefile:(nsstring *)filename content:(nsstring *)writecontent
{
    nsstring *pathdocuments=[nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask, yes) objectatindex:0];

    nsstring *createpath=[nsstring stringwithformat:@"%@/%@",pathdocuments,filename];//用文件名补全路径
    nserror *readfileerror;
    nsstring *readcontent ;
    nsdata *data ;
    if ([[nsfilemanager defaultmanager] fileexistsatpath:createpath])//判断文件是否已存在
    {
        if (nil == writecontent) {
            readcontent = [nsstring stringwithcontentsoffile:createpath encoding:nsutf8stringencoding error:&readfileerror;];
        }else{
            data = [writecontent datausingencoding:nsutf8stringencoding];//新文件的初始数据
            [[nsfilemanager defaultmanager] createfileatpath:createpath contents:data attributes:nil];//创建文件
            readcontent = [nsstring stringwithcontentsoffile:createpath encoding:nsutf8stringencoding error:&readfileerror;];           
        }
    }
    else
    {
        if (nil == writecontent) {
            return nil;
        }else{
            data = [writecontent datausingencoding:nsutf8stringencoding];//新文件的初始数据
            [[nsfilemanager defaultmanager] createfileatpath:createpath contents:data attributes:nil];//创建文件
            readcontent = [nsstring stringwithcontentsoffile:createpath encoding:nsutf8stringencoding error:&readfileerror;];
        }
    }
    return readcontent;
}

+ ( nsarray * )storearryfile:(nsstring *)filename content:( nsarray *)writearry
{
    //步骤
    //存 :将 数组放入 字典
    //取: 从字典取出数组
    if ( writearry == nil)//读取文件
    {
        nsstring *storestr = [fnprorequest storefile:filename content:nil];
        nsdictionary *dic = (nsdictionary *)[storestr jsonvalue];

        nslog(@"%@", dic);

        return (nsarray *)[dic objectforkey:filename];
    }
    else
    {
        nsarray *objectsarry = [[nsarray alloc]initwithobjects:writearry,nil ];
        nsarray *keysarry    = [[nsarray alloc]initwithobjects:filename,nil ];
        nsdictionary *dic = [[nsdictionary alloc]initwithobjects:objectsarry forkeys:keysarry];
        nsstring *storestr = [dic jsonrepresentation];
        [self storefile:filename content:storestr];
        [objectsarry release];
        [keysarry release];
        [dic release];
    }
    return nil;
}