Question

I have made an array of text strings and want to pull these out an into a label by EITHER swiping of pressing a button. So i have two different functions/methods, the button and the swipe method.

Where and how do I define the array so that these methods can refer to it? Should it be a 'extern NSArray' ?

I have uploaded the image of full code externally http://s1.postimg.org/b2e3m4v67/Sk_rmbillede_2014_05_11_kl_15_48_28.png Not sure though if that's a violation of some rules here(?)

Was it helpful?

Solution

You want the quote to change on swipe/button press.

In your button press/swipe methods you're setting the text property of the VC's label property to something called Quoteselected. And it looks like Quoteselected is a random element of the array Quotes - or at least maybe it is, since that random number could be 6-10, and you don't have any objects in the Quotes array at those indices - so if those numbers are ever generated by the random function, your program will crash due to an index out of bounds error.

What you probably want to do is generate a new random number on each user interaction and then at that point change the value of Quoteselected to be the object at that index of the array. And then assign that to the label's text property.

As far as defining the Array - I wouldn't have done it the way you did. What you've got there is an "ivar", an instance variable. On iOS, those are typically properties. And since it's a "private" array that outside classes won't need to know about, I'd declare it as a part of the class extension.

So,

@interface BOViewController()
@property NSArray *quotes;
@end

Also note my capitalization changes, that's better style.

So now you've got an array property declared, but there's no data in it. It depends on how you created your View Controller instance. Assuming you did it in a storyboard, it would go in awakeFromNib: or viewDidLoad: (if you instantiated the VC automatically, you might put it in the initWithNibName: method).

- (void)viewDidLoad {
   [super viewDidLoad];

   self.quotes = @[@"Test", @"Number 3"...];

Then when you want to reference the array in other parts of the class:

self.label.text = self.quotes[0];

Note that your existing code should work, it's just not typical Cocoa coding style.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top