传递 NSDate
我是 iPhone 和 Objective-c 的新手,我仍在努力了解对象的所有权,所以请耐心等待。
我有一个 DOBViewController ,上面有一个日期选择器。我创建了一个自定义 init 方法:
-(id)initWithInitialDate(NSDate *)initialDate;
另一个视图控制器声明了一个保存值的日期实例 (NSDate *dob)。我想将其传递给 DOBViewController,以便它可以将日期选择器滚动到传递的值。
这是自定义 init 方法:
- (id)initWithInitialDate:(NSDate *)initialDate {
// Initialise ourselves
self = [super init];
// Set the date of the date picker
if (initialDate != nil) {
datePicker.date = initialDate;
}
else {
// Set it to today
datePicker.date = [NSDate date];
}
return self;
}
这就是我发送 dob NSDate 对象的方式:
DOBViewController *dobViewController = [[DOBViewController alloc] initWithInitialDate:dob];
其中 dob 是在头文件中声明的 NSDate 类型的变量。
这似乎不起作用,因为initialDate 始终为NULL。我做错了什么?
I'm new to the iPhone and objective-c and I am still trying to get my head around ownership of objects so bear with me.
I have a DOBViewController that has a datepicker on it. I have created a custom init method:
-(id)initWithInitialDate(NSDate *)initialDate;
Another view controller has a date instance declared (NSDate *dob) that holds a value. I would like to pass this to the DOBViewController so that it can scroll the datepicker to the passed value.
Here is the custom init method:
- (id)initWithInitialDate:(NSDate *)initialDate {
// Initialise ourselves
self = [super init];
// Set the date of the date picker
if (initialDate != nil) {
datePicker.date = initialDate;
}
else {
// Set it to today
datePicker.date = [NSDate date];
}
return self;
}
This is how I am sending the dob NSDate object:
DOBViewController *dobViewController = [[DOBViewController alloc] initWithInitialDate:dob];
Where dob is a variable of type NSDate that is declared in the header file.
This doesn't seem to work as initialDate is always NULL. What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当
init...
方法返回时,您的datePicker
出口尚未加载。您应该将NSDate
保存到实例变量中,然后使用更合适的方法进行设置,例如viewDidLoad
。Your
datePicker
outlet isn't loaded yet by the time theinit...
method returns. You should save theNSDate
into an instance variable, and then do the setting in a more appropriate method, likeviewDidLoad
.