开发者

editing file in objective c

开发者 https://www.devze.com 2023-02-27 17:59 出处:网络
i need a file with this structure: elementName -> value elementName -> value elementName -> value so i will use a .plist file. Sometimes i want modify the value of one of the t开发者_C百科hree ele

i need a file with this structure:

  • elementName -> value
  • elementName -> value
  • elementName -> value

so i will use a .plist file. Sometimes i want modify the value of one of the t开发者_C百科hree element, can i do this? Or must i read the whole file and rewrite?

any other solution is welcome.


Effectively, all of the file has to be read, so that it can be parsed and mapped into a correct structure into memory.

When saving, it has to be rewritten as well.


I guess reading the file in completely and then writing it back will be the easiest.

Example using a dictionary:

NSDictionary *myDictionary;
NSMutableDictionary *mutableDict;
NSString *filePath;
NSNumber *numApplicationLaunches;
int intValue;

filePath = @"/your/path/here.plist";

/* Read in and make mutable copy */
myDictionary = [[NSDictionary alloc] initWithContentsOfFile:filePath];
mutableDict = [myDictionary mutableCopy];
[myDictionary release];

/* Edit necessary */
numApplicationLaunches = [mutableDict objectForKey:@"NumAppLaunch"];
intValue = [numApplicationLaunches intValue];
intValue++;
numApplicationLaunches = [NSNumber numberWithInt:intValue];
[mutableDict setObject:numApplicationLaunches forKey:@"NumAppLaunch"];

/* Write To file */
[mutableDict writeToFile:filePath atomically:YES];
[mutableDict release];

Hope it helps,
ief2


There's an easier way:

NSString *path =  [[NSBundle mainBundle] pathForResource:fileName ofType:@"plist"];
NSData *data = [NSData dataWithContentsOfFile:path];
NSError *error = nil;
NSMutableArray *items = [NSPropertyListSerialization propertyListWithData:data
                                                       options:NSPropertyListMutableContainersAndLeaves
                                                        format:nil
                                                         error:&error];

Of course, depending on your plist, you might get something other than an NSArray. Adjust as necessary.

All objects (at all depths) in the array will be mutable. Iterate/edit as wanted and then write it back out as suggested by Henri.

0

精彩评论

暂无评论...
验证码 换一张
取 消