В прошлый раз я спросил, как сложить значение при нажатии кнопки в методе
-(IBAction)addTap:(id)sender;
теперь меня научили использовать tapCount++; (tapCount - это переменная типа int) для добавления 1 при каждом нажатии кнопки.
Однако я обнаружил, что значение оставалось неизменным независимо от того, сколько раз я нажимал на него.
Я хочу сделать значение tapCount равным 1, если я нажму кнопку один раз, и сделать его равным 2, если я нажму кнопку дважды, и так далее.
Может кто подскажет, как это сделать?
Деталь:
Допустим, у меня есть класс Player, член с именем int tapCount и int result
при каждом нажатии кнопки значение будет добавлено к tapCount, и значение будет отображаться в конце (когда, скажем, конец игры)
На данный момент значение остается прежним, когда я использую NSLog для его проверки.
Player.h
@class TappingViewController;
@interface Player : NSObject {
NSString *name;
int tapCount;
int result;
}
@property (nonatomic, assign) NSString *name;
@property (nonatomic, assign) int tapCount;
@property (nonatomic, assign) int result;
@end
TappingViewController.h
@interface TappingViewController : UIViewController {
}
-(IBAction)addTap:(id)sender;
@end
TappIngViewController.m
#import "TappingViewController.h"
#import "Player.h"
@class Player;
int tapCount;
@implementation TappingViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
}
return self;
}
/*
- (void)loadView {
}
*/
- (void)viewDidLoad
{
Player *aPlayer = [[Player alloc]init];
NSLog(@"tapCount:%d", aPlayer.tapCount);
[super viewDidLoad];
}
-(IBAction)addTap:(id)sender;
{
NSLog(@"BeforeL %d", tapCount);
tapCount++;
NSLog(@"After: %d", tapCount);
}
/*
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload {
}
- (void)dealloc {
[super dealloc];
}
@end
Ответ 1 · Jonathan.
В методе addTap: вы ссылаетесь на tapCount Контроллера TappingViewController, который отличается от tapCount проигрывателя, хотя у них одно и то же имя, они разные. Итак, вам нужно сослаться на свойство aPlayer tapCount:
aPlayer.tapCount++;
Однако aPlayer не входит в сферу применения addTap: метода. Единственное место, где вы можете сейчас ссылаться на aPlayer, - это метод viewDidLoad.
Вот что вам нужно изменить: (вам не нужны комментарии, которые я добавил, чтобы указать на изменения)
TappingViewController.h
@class Player; //**You have imported the Player class in the .m file so if you use the Player class in the header you need to add it as a forward class.
@interface TappingViewController : UIViewController {
Player *aPlayer; //**This is an instance variable (ivar) so you can access it in any method in the implementation (.m file), however you still need to put something in this ivar (see viewDidLoad)**
}
//**You can add a property for aPlayer if you want, but remember to do the memory management properly**
-(IBAction)addTap:(id)sender;
@end
TappIngViewController.m
#import "TappingViewController.h"
#import "Player.h"
//**Get rid of the forward class, as you have imported it above**
//**Get rid of the tapCount that was were**
@implementation TappingViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
}
return self;
}
/*
- (void)loadView {
}
*/
- (void)viewDidLoad
{
aPlayer = [[Player alloc] init]; //**remove the declaration of a new var**
NSLog(@"tapCount:%d", aPlayer.tapCount);
[super viewDidLoad];
}
-(IBAction)addTap:(id)sender;
{
NSLog(@"BeforeL %d", tapCount);
aPlayer.tapCount++; //**reference the player's tapCount**
NSLog(@"After: %d", tapCount);
}
/*
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload {
}
- (void)dealloc {
[super dealloc];
}
@end
Ответ 2 · Erik B
Мне действительно не кажется, что вы предоставляете достаточно информации, чтобы мы могли сказать вам, что идет не так. При этом я мог бы указать вам в правильном направлении.
Прежде всего, я бы посоветовал вам попробовать следующий код:
-(IBAction)addTap:(id)sender {
NSLog(@"Before: %d", tapCount);
tapCount++;
NSLog(@"After: %d", tapCount);
}
Я добавил их оба, чтобы показать вам, что увеличение переменной действительно работает.
Если вы получите следующий результат:
Before: 0
After: 1
Before: 0
After: 1
Before: 0
After: 1
Это означает, что вы устанавливаете tapCount = 0; снова и снова.
Если вы не получаете никакого вывода, это означает, что ваш IBAction не подключен должным образом.
Если вы получите ожидаемый результат, но это то же самое, когда вы "NSLog to check it". Это означает, что вы случайно снова запустили tapCount = 0;.
Другая возможность - что-то не так с вашим NSLog.
Если у вас есть вопросы, не стесняйтесь спросить.
Ответ 3 · Black Frog
Я предполагаю, что IBAction находится в вашем контроллере. Вам нужно будет добавить переменную в свой заголовок. В контроллере например:
Учитывая, что у вас есть счетчик нажатий в другом классе, вашему контроллеру нужен указатель на этот класс.
// controller header file
Player *myPlayer;
// controller implementation file
-(void)awakeFromNib {
myPlayer = [Player alloc] init]; // initialized the player
// do whatever else you need to do
// load previous data from NSUserDefaults, maybe
}
-(IBAction)addTap:(id)sender {
myPlayer.tapCount++;
}