【发布时间】:2014-01-02 07:02:39
【问题描述】:
我在XCode 4.6.3 中使用情节提要创建了一些按钮和标签
我想在单击放置在 FirstViewController 中的按钮时触发一些方法,并且为了使这些方法起作用,我已经定义了一些变量/NSMutableArrays(currentQuestionIndex、questions 等)。我想使用自定义初始化方法来初始化这些。
当我保留 initWithNibName 和 initWithCoder 并编写一个新的 init 方法并在其中编写我的实现时,它不会被调用。
但是当我按照下面的 sn-ps 所示操作代码时,它起作用了。
我想知道在使用Storyboard 创建对象时如何使用自定义初始化方法,因为我在这里所做的可能不是一个好习惯。当我尝试使用 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,当所有对象都从情节提要加载并且插座连接时调用。
-
当我试图覆盖 initWithCoder 时,其中指定的初始化对我不起作用。我们到底用 awakeFromNib 做什么?
-
“它没有用”是什么意思?
-
我的意思是初始化没有发生。例如 currentQuestionIndex = -1;该语句从未被执行。
-
initWithCoder 是所谓的“指定初始化器”,比较developer.apple.com/library/ios/documentation/general/…。
标签: ios objective-c storyboard init initwithcoder