Lola
Lola

Reputation: 43

How to store the returning value of an NSArray.objectAtIndex to an NSString variable

I'm new to programming using objective c, I've only used java in the past. I'm trying to code a quick hangman game and I've come across errors that for the life of me I can't find a solution to.

So in this method, I'm trying to pick a random word from an NSArray and setting it equal to the instance variable word.

#import <Foundation/Foundation.h>

@interface Hangman : NSObject
{
    NSString *word;
}
-(void) randomWord;
-(void) guessLettter: (char) g;
-(void) guessWord: (NSString*) guess;
-(void) displayLetters: (char) x;
@end

#import "Hangman.h"
@implementation Hangman

-(void) randomWord;
{

NSArray *array = [NSArray arrayWithObjects:@"Mercedes", @"Banana", @"Porsche",
                  @"Dinosaur", @"Blue", @"owls", @"chicken", @"Lollipop", @"Table",
                  @"Hello", @"Corn", @"Uniform",nil];
int num = 11;
NSUInteger r = arc4random_uniform(11);
word = *[array objectAtIndex:(NSUInteger)r];


}

But trying to set word equal to whatever object is returned is giving me an error about assigning NSString Strong to type 'id' and I don't know what 'id' is.

Upvotes: 0

Views: 58

Answers (1)

rmaddy
rmaddy

Reputation: 318854

You have a simple typo. This line:

word = *[array objectAtIndex:(NSUInteger)r];

should be:

word = [array objectAtIndex:r];

or even better:

word = array[r];

Side note: Don't put the ivar in the .h file. Put it in the .m file. The public doesn't need to know about private details.

.h:

@interface Hangman : NSObject

-(void) randomWord;
-(void) guessLettter: (char) g;
-(void) guessWord: (NSString*) guess;
-(void) displayLetters: (char) x;

@end

.m:

#import "Hangman.h"

@implementation Hangman {
    NSString *word;
}

-(void)randomWord
{
    NSArray *array = @[@"Mercedes", @"Banana", @"Porsche",
                  @"Dinosaur", @"Blue", @"owls", @"chicken", @"Lollipop", @"Table",
                  @"Hello", @"Corn", @"Uniform"];
    NSUInteger r = arc4random_uniform(11);
    word = array[r];
}

Also get rid of the semicolon after the name of the randomWord method in the .m file.

And notice the use of modern array syntax.

Upvotes: 1

Related Questions