Patrick William Walsh
Patrick William Walsh

Reputation: 11

Storing a string from a text field as a Player name Objective C

I am trying to have multiple players for a card matching game. I have made a class that is a child of NSObject called Player. A Player object will have a name, high score, last score, and boolean is currently playing instance. I am trying to create a new player every time a new name is entered into a text field. I will work on storing the players later. Right now I just wish to make a new Player, have a user enter their name in the text field. And store the user's response in the text field. The following is my Player.m file

    #import "Player.h"

    @implementation Player

    -(NSString *) nameOfPlayer:(Player *)playerName{
        return self.name;
    }

    -(void) setPlayerName:(NSString *) nameOf{
        self.name = nameOf;
        self.lastScore = 0;
        self.highestScore = 0;
        self.playing = YES;
        return;
    }

    -(id)init{
        self = [super init];
        self.name = @"";
        self.lastScore = 0;
        self.highestScore = 0;
        self.playing = YES;
        return self;
   }

   @end

I didn't originally have that init until I tried looking for a solution online. I am a bit new to iOS coding so I wasn't sure how to set up a constructor (or if they even have those). Below is how I tried to instantiate a Player object:

    - (IBAction)handleButtonClick:(UIButton *)sender {
        Player * friend = nil;
        nameText = self.nameEntryField.text;
        [friend setPlayerName:nameText];
        NSLog(@"%@", [friend nameOfPlayer:friend]);
    }

My app breaks its thread as soon as I try to setPlayerName. I am a bit stuck on this so any help would be appreciated.

Upvotes: 0

Views: 66

Answers (2)

Patrick William Walsh
Patrick William Walsh

Reputation: 11

This is embarassing. I was unfamiliar with the xCode IDE and accidentally had selected that line of code for a breakpoint. The code is fine after previous answer.

Upvotes: 0

βhargavḯ
βhargavḯ

Reputation: 9836

- (IBAction)handleButtonClick:(UIButton *)sender {
        Player * friend = [[Player alloc] init]; // Initialize this
        nameText = self.nameEntryField.text;
        [friend setPlayerName:nameText];
        NSLog(@"%@", [friend nameOfPlayer:friend]);
 }

You have done like Player * friend = nil; mean this is the nil object. And then you are trying to use method setPlayerName:on nil object. Because of this app breaks.

So you need to initialize object using [[Player alloc] init].

Upvotes: 1

Related Questions