I realize this is a dumb beginner question, but I have been stuck for at least an hour on trying to get an integer value from my array to display on a label when I press a button. The problem is that the label keeps displaying "(null)" no matter what index I put the label to look at. I have tried taking out the quotation marks on the NSArray objects too. It doesn't matter too much whether the objects within the NSArray are integers or strings, but I would at least like to know the syntax on how to put them into the array because I believe that's my problem. If not, show me otherwise please.

My code: (.h file)

@property (strong, nonatomic) NSArray *redOneTeams;

(.m file)

    - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        _redOneTeams = @[
                   @"4351",
                   @"4298",
                   ];
        }
    return self;
}

- (IBAction)saveBtn:(id)sender {
    _teamNumber.text = [[NSString alloc] initWithFormat: @"%@", [_redOneTeams objectAtIndex:0]];
}
有帮助吗?

解决方案

There are two possibilities with your issue.

  1. Just set a break point on initWithNibName and check if this method is triggering . I feel like this method is not getting called somehow. So you array is not getting set.
  2. If you are able not find out why initWithNibName is not getting called then you can shift your code into viewDidLoad method.

Just try out these things probably you will catch issue.

其他提示

So there are a couple of options here:

1- Put the numbers directly into your array as numbers:

_redOneTeams = @[
               @4351,
               @4298,
               ];

This is automatically recognized as literals/numbers. If you do this, then you can just call it with:

- (IBAction)saveBtn:(id)sender 
{
  _teamNumber.text = [[NSString alloc] initWithFormat: @"%i", [_redOneTeams objectAtIndex:0]];
}

2- Another more convoluted way but to show you how you can unwrap numbers from NSStrings:

Keep your array declared with NSString elements and then get the value form the NSString as follows:

- (IBAction)saveBtn:(id)sender 
{
  _teamNumber.text = [[NSString alloc] initWithFormat: @"%i", [[_redOneTeams objectAtIndex:0] intValue]];
}

Hope this helps

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top