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

Gail ·
更新时间:2024-11-13
· 733 次阅读

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;
}

您可能感兴趣的文章:Objective-C中使用NSString类操作字符串的方法小结NSString与C字符串之间的相互转换Objective-C中字符串的拼接方法小结Objective-C处理空字符串和页面传值及自定义拷贝IOS开发之路--C语言数组和字符串Objective-C中字符串NSString的常用操作方法总结



示例 字符串 存储 objective-c 字符

需要 登录 后方可回复, 如果你还没有账号请 注册新账号