IOS开发3---文件的读取 与 写入,修改

1.建立一个 NSObject ,我们取名为operatePlist

2.在operatePlist.h中:

#import <Foundation/Foundation.h>

@interface operatePlist : NSObject

+(void)modifyed:(NSString*)value forkey:(NSString*)key;

+(NSString *) readShop:(NSString *)shopTemp;

@end

3.operatePlist.m中

#import "operatePlist.h"

@implementation operatePlist

+(void)modifyed:(NSString*)value forkey:(NSString*)key{     //修改数据方法 

    NSFileManager *fileManager = [NSFileManager defaultManager];   //建立文件管理器

    //get the plist file from bundle

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES); //获取
Library路径

    NSString *documentsDirectory = [NSString stringWithFormat:@"%@/Caches/",[paths objectAtIndex:0]];//获取Library/Caches目录

    NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:@"CustomIfro.plist"];//获取事先建的plist文件路径

    // build the array from the plist

    if ([fileManager fileExistsAtPath: plistPath]) 

    {

        NSMutableDictionary *  dict = [[NSMutableDictionary alloc]initWithContentsOfFile : plistPath];

        [[dict objectForKey:@"Student"] setValue:value forKey:key];

        //[dict setObject:@“” forKey:@“key”];  加入键值为key,值为@“”的物件

        [dict writeToFile : plistPath  atomically : YES  ] ;

        [dict release];

    }

    else {

        NSString *resourceSampleImagesFolderPath =[[NSBundle mainBundle]

                                                   pathForResource:@"CustomIfro"

                                                   ofType:@"plist"];

        NSData *mainBundleFile = [NSData dataWithContentsOfFile:resourceSampleImagesFolderPath];

        [[NSFileManager defaultManager] createFileAtPath:plistPath contents:mainBundleFile attributes:nil];

        NSMutableDictionary *  dict = [[NSMutableDictionary alloc]initWithContentsOfFile : plistPath];

        [[dict objectForKey:@"Student"] setValue:value forKey:key];

        //[dict setObject:@“” forKey:@“key”];  加入键值为key,值为@“”的物件

        [dict writeToFile : plistPath  atomically : YES  ] ;

        [dict release];

    }

}

+ (NSString *) readShop:(NSString *)shopTemp  //读数据方法

{

    NSString *temp = [[[NSString alloc]init]autorelease];

    //get the plist file from bundle

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);

    NSString *documentsDirectory = [NSString stringWithFormat:@"%@/Caches/",[paths objectAtIndex:0]];

    NSString *plistPath = [documentsDirectory stringByAppendingPathComponent:@"CustomIfro.plist"];

    // build the array from the plist

    NSMutableDictionary *  dict = [[[NSMutableDictionary alloc]initWithContentsOfFile : plistPath]autorelease];

    temp = [[dict objectForKey:@"Student"] objectForKey:shopTemp];

    return temp;

}

@end

4.方法调用:

在调用的M文件中 引入#import "operatePlist.h"

 [operatePlist modifyed:self.name.text forkey:@"Name"];  


 name.text=[operatePlist readShop:@"Name"];


你可能感兴趣的:(修改,ios开发,文件读取,写入)