开发者

pulling data from a plist

I'm trying to pull some data from plist file and displa开发者_如何转开发y it in a text field (from a UIButton click). the code below pulls the address of the plist and not the data. any help is greatly appreciated. thanks

-(IBAction) buttonPress {

    NSString *path = [[NSBundle mainBundle] pathForResource:@"messages" ofType:@"plist"];
    NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:path];

    [myMessage setText:path];
}


yeah, you're printing out the path, not any item in the array. Change

[myMessage setText:path];

to

[myMessage setText:[array objectAtIndex:x]; //x = whatever index in the array contains your string.

Also you can change your plist to contain a dict and not an array so you could call specific text -

-(IBAction) buttonPress {

    NSString *path = [[NSBundle mainBundle] pathForResource:@"messages" ofType:@"plist"];
    NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];

    [myMessage setText:[dict objectForKey:@"text"]];
}

In response to your question about arc4random.

Create an enum so that you can create a switch statement -

typedef enum {
    MESSAGE1,
    MESSAGE2,
    MESSAGE3
} messageIDs;

then create a random integer and mod it by x so that you get a number btw 0 and x-1. (In this case, since we have 3 things inside the enum, x = 3)

int randomValue = arc4random() % 3;

then use that random int in a switch statement

switch (randomValue) {
    case MESSAGE1:
          [myMessage setText:[dict objectForKey:@"message1"]]; //or [myMessage setText:[array objectAtIndex:MESSAGE1]]
    break;
    case MESSAGE2:
          [myMessage setText:[dict objectForKey:@"message2"]];
    break;
    case MESSAGE3:
          [myMessage setText:[dict objectForKey:@"message3"]];
    break;
    default:
    break;
}

hope this works. I havent tried this before...


It does exactly what you tell it to.

Assuming messages.plist contains an array of strings, you can easily get the last item in the array:

[myMessage setText:[array lastObject]];
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜