【问题标题】:Var visible in the ViewDIdLoad but not somewhere elseVar 在 ViewDIdLoad 中可见,但在其他地方不可见
【发布时间】:2011-08-17 01:47:24
【问题描述】:

我正在编写一个 iphone 应用程序,但出现了问题;我可以在 viewDidLoad 方法中使用 NSDate 变量,但不能在其他地方使用!怎么做?怎么解决?

这是我的重要台词:

@interface GraphNavController : UINavigationController {

IBOutlet UIImage *image;
CGPoint gestureStartPoint;
IBOutlet UISegmentedControl *segmentedControl;

NSDateComponents *dateComponents;
NSCalendar *gregorian;

@public
NSDate *date;   

}

并且在实现代码中...

- (void)viewDidLoad {
[super viewDidLoad];

date = [[NSDate alloc] init];

//  Set the GMT @ 2
gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[gregorian setTimeZone:[NSTimeZone timeZoneWithName:@"GMT+2"]];

dateComponents = [[NSDateComponents alloc] init];
[dateComponents setMonth:11];

[dateComponents setMonth:11];// tests ^^
date = [gregorian dateByAddingComponents:dateComponents toDate:date options:0];

NSLog(@"-->  Date : %@ - DComponents's : %d-%d-%d - gregorian : %@",date, [dateComponents day], [dateComponents month], [dateComponents year], [gregorian calendarIdentifier]); // is running here completely well

}

并且日期变量隐藏在该类的任何其他方法中...

我已经尝试将该变量放入@public、@private、@package,...但没有运行。

该应用程序在没有给出任何问题描述的情况下被杀死!我只需要将日期日志放在 viewOnLoad 之外的任何其他位置,就会出现崩溃...

【问题讨论】:

  • 您是否要在当前日期上增加 11 个月?

标签: iphone objective-c global-variables instance-variables protected


【解决方案1】:

dateByAddingComponents:toDate:options: 返回一个自动释放的对象。你应该保留它。如果您使用属性:

@property(retain,nonatomic) NSDate *date;

那么你可以这样做:

self.date = [gregorian dateByAddingComponents:dateComponents toDate:[NSDate date] options:0];

【讨论】:

  • 更好的是,让它@property(retain,nonatomic) NSDate *date;
  • @Martin:我做了那个修改,但应用程序仍然崩溃:-/
  • @clement 如果您使用属性,请确保使用self.date 而不是date(参见编辑后的答案)
  • @clement 不要忘记@synthesize 日期;为您的财产
  • @clement 还有,你不需要date = [[NSDate alloc] init];,只需self.date = [gregorian dateByAddingComponents:dateComponents toDate:[NSDate date] options:0];
猜你喜欢
  • 2016-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-05
  • 2014-05-25
  • 1970-01-01
相关资源
最近更新 更多