I created a single view app, added a label, an un-editable text view and a button, I have an array of strings. Really simply just want to click the button and change the string at random.
- (IBAction)viewNextPressed:(id)sender {
NSArray *affirmationStrings = @[
@"String 1 Pressed",
@"String 2 Pressed",
@"String 3 Pressed"
];
//Generate a random index from our array
int randomNIndex = arc4random() % [affirmationStrings count];
//Display a string from our array
self.displayAffirmationText.text = affirmationStrings[randomNIndex];
}
@end
Obviously this works fine for this example but its horribly inefficient as its generating the array each time the button is clicked. Where is the best place to store the array so its generated upon load and I can just access it when needed?
I see viewDidLoad but as a beginner I want to try to understand best practice for simple tasks. Secondly is the way I am storing strings fine for a large sample of say 500-1k+ strings?
-viewNextPressed:. This is probably the simplest and best solution, assuming you don't have an insane number of strings and that the strings are fairly short. If there are multiple instances of the VC in question, you might consider a static instance variable.@property (nonatomic,strong) NSArray *affirmationStrings;Then setup the array in-viewDidLoad, as you do in the method, but using_affirmationStringsinstead ofNSArray *affirmationStrings. I strongly recommend you have a look at an introduction to Objective-C properties in order to understand exactly what it means and what it's doing, if you don't already understand properties