ストーリーボードを使用していくつかのボタンとラベルを作成しXCode 4.6.3
ました。FirstViewController に配置されたボタンのクリックでいくつかのメソッドを起動し、メソッドが機能するようにいくつかの変数 / NSMutableArrays
(currentQuestionIndex、questions など) を定義しました。これらを初期化するためにカスタム init メソッドを使用したいと考えています。そのままinitWithNibName
にinitWithCoder
して新しいinitメソッドを作成し、その中に実装を作成すると、呼び出されません。
しかし、以下のスニペットに示すようにコードを操作すると、うまくいきました。
Storyboard
ここで行ったことはおそらく良い習慣ではないため、を使用してオブジェクトを作成するときにカスタム init メソッドを使用する方法を知りたいです。を使って初期化しようとしたところinitWithCoder
、うまくいきませんでした。しかし、私が思い出せる限り、私たちはinitWithCoder
から初期化するために使用していますStoryboard
よね? のボタン/ラベルはstoryboard
FirstViewController にあります。
これは私の FirstViewController.h ファイルです
#import <UIKit/UIKit.h>
@interface FirstViewController : UIViewController
{
int currentQuestionIndex;
// The model objects
NSMutableArray *questions;
NSMutableArray *answers;
//The view objects
IBOutlet UILabel *questionField;
IBOutlet UILabel *answerField;
}
@property (strong, nonatomic) UIWindow *window;
- (IBAction)showQuestion:(id)sender;
- (IBAction)showAnswer:(id)sender;
@end
と
これは私の FirstViewController.m ファイルです
#import "FirstViewController.h"
@interface FirstViewController ()
@end
@implementation FirstViewController
- (id)init {
// Call the init method implemented by the superclass
self = [super init];
if(self) {
currentQuestionIndex = -1;
// Create two arrays and make the pointers point to them
questions = [[NSMutableArray alloc] init];
answers = [[NSMutableArray alloc] init];
// Add questions and answers to the arrays
[questions addObject:@"What is 7 + 7?"];
[answers addObject:@"14"];
[questions addObject:@"What is the capital of Vermont?"];
[answers addObject:@"Montpelier"];
[questions addObject:@"From what is cognac made?"];
[answers addObject:@"Grapes"];
}
// Return the address of the new object
return self;
}
-(IBAction)showQuestion:(id)sender
{
currentQuestionIndex++;
if(currentQuestionIndex == [questions count])
currentQuestionIndex = 0;
NSLog(@"%d",[questions count]);
NSString *question = [questions objectAtIndex:currentQuestionIndex];
NSLog(@"dislaying question at index %d : %@" ,currentQuestionIndex,question);
[questionField setText:question];
[answerField setText:@"???"];
}
-(IBAction)showAnswer:(id)sender
{
NSString *answer = [answers objectAtIndex:currentQuestionIndex];
[answerField setText:answer];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end