我用XCode 4.6.3
創建了幾個按鈕和標籤我想要點擊放置在FirstViewController中的按鈕的點擊方法和工作方法我已經定義了一些變量/ NSMutableArrays
(currentQuestionIndex,questions等)。我想使用一個自定義的初始化方法來初始化這些。 當我離開initWithNibName
和initWithCoder
照原樣編寫一個新的init方法並在其中寫入我的實現時,它不會被調用。當我們使用storyboard時,我們如何在objective-c中實現自定義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
是的,覆蓋initWithCoder(而不是init)應該工作。你是什麼意思「它沒有工作」?它不叫嗎? - 您也可以重寫awakeFromNib,當從故事板加載所有對象並且連接插座時調用awakeFromNib。 –
當我試圖覆蓋initWithCoder時,其中指定的初始化對我無效。我們用awakeFromNib究竟做了什麼? – ronilp
你的意思是「它沒有工作」是什麼意思? –