Quote:
Originally Posted by Doodl3
Hey, im a newbie when it comes to xcode. So flame all you like for me asking this because we all had to start somewhere, so here we go. Is there anyone who would give a tut on using a plist to say... change the words on a lable when you press a button? I know you can do that by adding what text you'd liek the lable to say in the button method but i wanna learn how to use plists.
|
The simplest way to use plists is to create them with one of the writeToFile:atomically: methods.
Say I want to create a plist with an array of strings:
Code:
self.anArray = [NSArray arrayWithObjects: @"one", @"two", @"three"];
NSString* documentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]
NSString* filePath = [documentsDir stringByAppendingPathComponent: @"foo.plist"];
[anArray writeToFile: filePath atomically: TRUE];
Then, reading the array from the plist could not be easier:
Code:
NSString* documentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]
NSString* filePath = [documentsDir stringByAppendingPathComponent: @"foo.plist"];
self.anArray = [NSArray arrayWithContentsOfFile: filePath];
Once you've read the array from the plist, it's a regular array. You could use it to change the text on a button with code like this:
Code:
-(IBAction) changeButtonText: (id) sender;
{
int index = arc4random % [self.anArray count];
NSString* newText = [self.anArray objectAtindex: index];
((UIButton*) sender).text = newText;
}
There are probably a couple of minor syntax errors in the code above. I didn't proof it, much less compile and test it. It shows the basic idea.
The code above assumes that it's being used from a single class that has a retained property anArray. You'll need to add code to your object's dealloc method to release the retained property anArray.