开发者

iOS : date problem

I have this code:

in viewDidLoad:

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

and a IBAction:

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

When I push a button connected to this IBAction, it's all ok the first time but it crashes the next time around. This is the result of crash in console:

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'


In viewDidLoad, you are obtaining an NSDate for which you hold a reference (since you created it with init). The first time you run addDay, you replace this with an autoreleased NSDate for which you don't hold a reference any more. When you leave addDay, this reference to dateForView becomes invalid, and the next time you enter addDay and try to increment it, your app will crash. The solution is to:

  1. Make dateForView a property with retain policy,
  2. Use self.dateForView = [NSDate date] in viewDidLoad.
  3. Use self.dateForView = [self.dateForView dateByAddingTimeInterval:60*60*24*1] in addDay.

Also, don't forget to set self.dateForView = nil in your destructor to avoid leaking memory.


May be the dateForView is released. For solving this use the [dateForView retain]; in the ibaction.But this will increase the memory


I have executed your code

you have to change this line:-

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];

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜