views:

65

answers:

2

I'm trying to pull some data from plist file and display 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];
}
A: 

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]];
tc.
thanks for the help. it's working now
hanumanDev
+2  A: 

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...

jmont
that worked perfectly. thanks so much!one follow up question - if i wanted to pull a random object from the plist, could i use the arc4random() function? if so, how would that fit in to the [myMessage setText:[dict objectForKey:@"text"]];thanks again.
hanumanDev
check my answer again, i've updated it to help you with arc4random(). Don't forget to mark this question as answered (if it works!) ;)
jmont
again, if you think this answered your question, mark this thread as answered (click the empty checkmark next to this post)
jmont