Take the 2-minute tour ×

I have a array that reads a .txt file and when you click a button the label changes in one of the words of the .txt file, but the label doen't change.

This is the code:

if(sender == self.button) {
    NSArray *words = [[NSArray alloc] initWithObjects:@"words.txt", nil];
    [randomLabel setText:[words objectAtIndex:random() % [words count]]];

What should I do so the label changes when I press the button? What file do I use?

share|improve this question

2 Answers 2

up vote 2 down vote accepted

A few things here:

Reading in file into an array

Well, for starters you're not reading in the contents of the .txt file.


This creates a 1 element array, with that one element being @"words.txt". I don't know the format of your .txt file, so I can't say for sure how you have to load it in. See How do I format a text file to be read in using arrayWithContentsOfFile on how to potentially do this.

Setting button text

Also, you need to make sure randomLabel actually refers to the label contained within the button, otherwise the button text won't change. Typically for a button, you'd change the title using the method:


So in your instance, it'd be:

NSString* newTitle = [words objectAtIndex:random() % [words count]];
[self.button setTitle:newTitle forState:UIControlStateNormal];

Is the code actually being called?

Double check that sender == self.button evaluates to true (for readability and clarity, I'd use [sender isEqual:self.button]). Use the debugger to step through the code, to see if that particular piece of code is being called. See http://mobile.tutsplus.com/tutorials/iphone/xcode-debugging_iphone-sdk/ on how to achieve this.

share|improve this answer

You should try using

  • (id)initWithContentsOfFile:(NSString *)aPath
share|improve this answer

Your Answer


