IOS開發3---文件的讀取 與 寫入,修改

1.創建一個 NSObject ,咱們取名爲operatePlistui

2.在operatePlist.h中:atom

#import <Foundation/Foundation.h>

@interface operatePlist : NSObject

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

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

@end

3.operatePlist.m中spa

#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.方法調用:.net

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

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


 name.text=[operatePlist readShop:@"Name"];
相關文章
相關標籤/搜索