开发者

How do I store lines of text in a property list on the iPhone?

开发者 https://www.devze.com 2022-12-16 16:44 出处:网络
This is my scenario: I need to save 50 lines of text and access each line of text after my applications launches.That is, for a change in a control paramenter the text displayed on the iPhone should c

This is my scenario: I need to save 50 lines of text and access each line of text after my applications launches. That is, for a change in a control paramenter the text displayed on the iPhone should change (i.e. point to the second line of text, then the third...). Instead of going for SQLite, I want to store this data in a property list and then access the data accordingly (no changes to the data model required).

Initially, I thought of creating an instance of NSDictionary and storing string objects (text lines). However, the dilemma is: how do I go about creating the property list for the aforementioned case, and then access开发者_开发百科 the data during runtime.

Sample code would be really appreciated. I have been trying to get my head around property lists, but I still am not able to figure them out. Thanks.


If I understood well, you are trying to save a plist file, in your application's document directory. This is how you read a plist file embedded in your app bundle, and later save it in your documents directory:

- (void)applicationDidFinishLaunching:(UIApplication *)application 
{
    // If your plist file is in the app bundle, and is called "file.plist":
    NSString *path = [[NSBundle mainBundle] pathForResource:@"file" ofType:@"plist"];
    NSArray *array = [[NSArray alloc] initWithContentsOfFile:path];

    // Do something with your array...

    // If your plist has to be created or saved at runtime, you can't store it in the
    // main bundle, but you can do it in the app's document directory:
    NSString *documents = [self documentsDirectory];
    path = [documents stringByAppendingPathComponent:@"another_file.plist"];
    [array writeToFile:path atomically:YES];
    [array release];

    // ~/Library/Application Support/iPhone Simulator/User/Applications/[YOUR_APP_ID_HERE]/Documents/another_file.plist
    NSLog(@"%@", path);

    // You can read the file later again doing initWithContentsOfFile: again
    // with the new file path.

    [window makeKeyAndVisible];
}

- (NSString *)documentsDirectory
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    return [paths objectAtIndex:0];
}

The file.plist file could be something like this:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
    <string>test</string>
    <string>wetwert</string>
    <string>dfdfh</string>
    <integer>345634</integer>
</array>
</plist>
0

精彩评论

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

关注公众号