【问题标题】:iOS : date problemiOS:日期问题
【发布时间】:2011-06-01 09:30:52
【问题描述】:

我有这个代码:

viewDidLoad:

dateForView = [[NSDate alloc] init]; (dateForView is a NSDate)

还有一个 IBAction:

- (IBAction) addDay{
    NSLog(@"dateforview1:%@", dateForView);
    dateForView = [dateForView dateByAddingTimeInterval:60*60*24*1];
    NSDateFormatter *formatter =[[[NSDateFormatter alloc] init] autorelease];
    [formatter setDateFormat:@"dd/MM/yyyy"];
    [dataLabel setText:[formatter stringFromDate:dateForView]];
}

当我按下连接到此 IBAction 的按钮时,第一次一切正常,但下一次它崩溃了。这是控制台崩溃的结果:

2011-06-01 11:29:55.238 Prenotazioni[554:707] dateforview1:(
    "<UIControlTargetAction: 0x1962d0>"
)
2011-06-01 11:29:55.246 Project[554:707] -[__NSArrayI dateByAddingTimeInterval:]: unrecognized selector sent to instance 0x1ba680
2011-06-01 11:29:55.264 Project[554:707] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayI dateByAddingTimeInterval:]: unrecognized selector sent to instance 0x1ba680'

【问题讨论】:

  • 一个需要考虑的问题与您的问题无关。简单地将 86,400 秒添加到日期可能不是添加一天的正确答案,因为它不适合 DST 更改。您可能应该使用 NSDateComponents developer.apple.com/library/mac/documentation/Cocoa/Conceptual/…
  • 我知道 nsdatecomponent,但是在与 NSDate 比较之后我会遇到问题
  • 您阅读我提供的链接了吗?您创建一个代表某一天的 NSDateComponent,然后使用 NSCalendar 将其添加到 dateForViewdateForView 仍然是 NSDate

标签: iphone objective-c xcode ios nsdate


【解决方案1】:

viewDidLoad 中,您将获得一个NSDate,您拥有一个引用(因为您使用init 创建它)。第一次运行addDay 时,您将其替换为自动释放的NSDate,您不再为其持有引用。当你离开addDay 时,这个对dateForView 的引用就失效了,下次你输入addDay 并尝试增加它时,你的应用程序就会崩溃。解决办法是:

  1. 使用 retain 策略将 dateForView 设为属性,
  2. viewDidLoad 中使用self.dateForView = [NSDate date]
  3. addDay 中使用self.dateForView = [self.dateForView dateByAddingTimeInterval:60*60*24*1]

另外,不要忘记在你的析构函数中设置self.dateForView = nil 以避免内存泄漏。

【讨论】:

  • self.dateForView = nil?或者 [dateforView release] 在 dealloc 中,不是吗?
  • 任何一个都可以;当我有与实例变量对应的属性时,我通常使用self.dateForView = nil
  • 如果可以避免,则不应在 dealloc 中使用属性。如果有一个显式声明的实例变量,则释放该实例变量。
【解决方案2】:

可能是 dateForView 发布的日期。为了解决这个问题,请使用 [dateForView retain];在ibaction中。但这会增加内存

【讨论】:

  • 如果您决定这样做,还必须释放addDay 中以前的dateForView 值,否则应用程序会泄漏内存。
【解决方案3】:

我已经执行了你的代码

你必须改变这一行:-

NSDateFormatter *formatter =[[[NSDateFormatter alloc] init] autorelease];

to
NSDateFormatter *formatter =[[NSDateFormatter alloc] init];
and at last 
[formatter release];

like:-

- (IBAction) addDay{

    NSLog(@"dateforview1:%@", dateForView);
    dateForView = [dateForView dateByAddingTimeInterval:60*60*24*1];
    NSDateFormatter *formatter =[[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"dd/MM/yyyy"];
    [dataLabel setText:[formatter stringFromDate:dateForView]]; 
    [formatter release];

}

【讨论】:

  • @blackguardian 执行一次代码,因为我没有遇到任何崩溃我更重要的是您在视图控制器的其他地方使用 dateForView。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多