-[__NSDate timeIntervalSinceReferenceDate]: message sent to deallocated - iphone

I am working on an iphone app, in which to count the number of days between two dates I am using the code as follows:
double intevalInSeconds = [selectedDate2 timeIntervalSinceDate:newfromdate];
int dayInSeconds = 60 * 60 * 24;
int day = intevalInSeconds / dayInSeconds;
NSLog(#"counted days are:%d",day);
NSDateFormatter *df=[[NSDateFormatter alloc] init];
[df setDateFormat:#"yyyy-MM-dd"];
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:
NSGregorianCalendar];
NSDateComponents *days = [[NSDateComponents alloc] init];
NSInteger dayCount = 0;
while ( TRUE ) {
[days setDay: ++dayCount];
NSDate *date = [gregorianCalendar dateByAddingComponents: days toDate: newfromdate
options: 0];
if ( [date compare: selectedDate2] == NSOrderedDescending )
break;
NSString *dateForAdd=[df stringFromDate:date];
[countdays addObject:dateForAdd];
}
NSLog(#"daysdetail:%#",countdays);
appendarray = countdays;
NSLog(#"append array is:%#",appendarray);
}
When i run this app on simulator it is working fine but whenever I tried to run it on device it is giving the error|:- [__NSDate timeIntervalSinceReferenceDate]: message sent to deallocated instance 0x65a30b0
Please tell me if I doing some wrong in the above code.
Thanks alot.

timeIntervalSinceDate: calls timeIntervalSinceReferenceDate.
So your code seems to be deallocating one of the NSDates somewhere before the code you are showing us.

Related

Local notifications are not coming on the datetime I want

I'm working with local notification. I got the notifications working. But I'm struggling with setting the correct date.
Let me first sketch the situation. I am making a festival app. This festival is on the 28-29-30 JUNE. Every artist object has an art_day. This can be 1 - 2 or 3.
1 --> 28 JUNE
2 --> 29 JUNE
3 --> 30 JUNE
I want a local notification 15 min before the start time of the artist. So this is how I'm making my fireDate of the notification.
-(NSDate *)getDateForArtist:(Artists *)artist{
int day = [artist.art_day intValue];
int timeStart = [artist.art_timestart intValue];
NSString *timeStart2 = [self getTimeStamp:artist.art_timestart];
int hours = [[timeStart2 substringWithRange:NSMakeRange(0,2)]intValue];
int minutes = [[timeStart2 substringWithRange:NSMakeRange(2,2)]intValue];
//in my db timeStart looks like 1530 --> 15h30 (I know bad db structure!!!)
int day2;
if(day == 1){
NSLog(#"day is 28");
day2 = 28;
}else if (day == 2){
NSLog(#"day is 29");
day2 = 29;
}else{
NSLog(#"day is 30");
day2 = 30;
}
NSDateComponents *comps = [[NSDateComponents alloc] init];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:#"GMT"];
[comps setTimeZone:timeZone];
[comps setDay:day2];
[comps setMonth:06];
[comps setYear:2013];
[comps setHour:hours];
[comps setMinute:minutes];
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date = [gregorian dateFromComponents:comps];
NSLog(#"date is %#",date);
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setMinute:-15];
NSDate *date2 = [gregorian dateByAddingComponents:offsetComponents toDate:date options:0];
NSLog(#"date -15 min %#", date2);
return date2;
}
This is how I create my notification
UIApplication* app = [UIApplication sharedApplication];
UILocalNotification* notifyAlarm = [[UILocalNotification alloc]
init];
if (notifyAlarm)
{
NSDate *datePush = [self getDateForArtist:artist];
NSLog(#"artist plays on: %# on hour %#",artist.art_day,artist.art_timestart);
NSLog(#"Push notification should send on: %#",datePush);
notifyAlarm.fireDate = datePush;
NSDictionary *dicNotification = [[NSDictionary alloc]initWithObjectsAndKeys:artist.art_id,#"pushKey", nil];
notifyAlarm.userInfo = dicNotification;
notifyAlarm.timeZone = [NSTimeZone defaultTimeZone];
notifyAlarm.repeatInterval = 0;
notifyAlarm.soundName = #"Glass.aiff";
notifyAlarm.alertBody = [NSString stringWithFormat:#"%# starts in 15 minutes",artist.art_name];
[app scheduleLocalNotification:notifyAlarm];
NSLog(#"Added");
}
But for some reason I don't get any push notification. Or I think that the date is not correct.
This is what I get from my logs
2013-06-29 15:37:17.801 genkonstage[14120:907] artist plays on day: 2 on hour 2020
2013-06-29 15:37:17.803 genkonstage[14120:907] Push notification should send on: 2013-06-29 20:05:00 +0000
Can anybody help me with this?

Local notifications are not working

I am trying to get my app working with local notifications. But I can't get my head arround. I'm looking after the problem for days. I have in my core database an entity Favorites (all my favorite artists) and an entity Artists (artist his detail information.
I have a button to set the local notification on. When I press the button, I do the following.
-(void)addLocalNotifications{
GenkonStageDataModel *model = [[GenkonStageDataModel alloc]init];
NSMutableArray *allFavorites = [model getAllFavorites];
NSLog(#"allFavoriets count is %d",allFavorites.count);
UIApplication* app = [UIApplication sharedApplication];
for (int i = 0; i<allFavorites.count; i++){
Favorites *favorite = [allFavorites objectAtIndex:i];
int artId = [favorite.fav_art_id intValue];
Artists *artist = [model getArtistById:artId];
UILocalNotification* notifyAlarm = [[UILocalNotification alloc]
init];
if (notifyAlarm)
{
NSDate *datePush = [self getDateForArtist:artist];
NSLog(#"Push notification should send on: %#",datePush);
notifyAlarm.fireDate = datePush;
NSDictionary *dicNotification = [[NSDictionary alloc]initWithObjectsAndKeys:artist.art_id,#"pushKey", nil];
notifyAlarm.userInfo = dicNotification;
notifyAlarm.repeatInterval = 0;
notifyAlarm.soundName = #"Glass.aiff";
notifyAlarm.alertBody = [NSString stringWithFormat:#"%# starts in 15 minutes",artist.art_name];
[app scheduleLocalNotification:notifyAlarm];
NSLog(#"Added");
}
}
}
What this method does is the following.
1. Get all the favorites
2. Loop through the favorites and get the artists linked with that favorite by ID
3. Get the date for when the local notification should be sent
4. Set in the userInfo dictionary the artist ID (I do this for deleting the local notification when I want to)
5. Shedule the local notification.
Now all these are added (I think) because it loops correctly through the array and also always gives me the correct date and "ADDED" in my log.
But now when I change my device it's dateTime to the time that I normally should receive the local notification. I do not receive anything!!!!
I also changed my date to 2hours earlier for the correct time. Because when I was testing with an example local notification. They setted the fireDate like this.
NSDate *alertTime = [NSDate date];
This caused that the local notifcation was sent immedialty after that I clicked the button. But when I logged this I noticed that is was 2 hours before the actual time... ?
I seriously hope that anybody can help me with this problem!
Thanks in advance!
EDIT
This is how I get my fireDate
-(NSDate *)getDateForArtist:(Artists *)artist{
int day = [artist.art_day intValue];
int timeStart = [artist.art_timestart intValue];
NSString *timeStart2 = [self getTimeStamp:artist.art_timestart];
int hours = [[timeStart2 substringWithRange:NSMakeRange(0,2)]intValue];
int minutes = [[timeStart2 substringWithRange:NSMakeRange(2,2)]intValue];
int day2;
if(timeStart >=2400 ){
day = day++;
}
if(day == 1){
NSLog(#"day is 28");
day2 = 28;
}else if (day == 2){
NSLog(#"day is 29");
day2 = 29;
}else{
NSLog(#"day is 30");
day2 = 30;
}
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:day2];
[comps setMonth:06];
[comps setYear:2013];
[comps setHour:hours];
[comps setMinute:minutes];
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date = [gregorian dateFromComponents:comps];
NSLog(#"date is %#",date);
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setMinute:-15];
NSDate *date2 = [gregorian dateByAddingComponents:offsetComponents toDate:date options:0];
NSLog(#"date -15 min %#", date2);
return date2;
}
And I get this LOG
2013-06-30 14:37:13.910 genkonstage[1633:907] date is 2013-06-30 16:50:00 +0000
2013-06-30 14:37:13.913 genkonstage[1633:907] Push notification should send on: 2013-06-30 16:35:00 +0000
From your comment (works 10 seconds ahead) it sounds like it's working fine.
When you change the device's date/time how are you doing it? forwards in time? backwards? are you altering the timezone?
Also are you scheduling notifications with a date/time that is in the past? If you specify a date that is in the past (or nil) the notification is delivered immediately.
The fire date is evaluated using the timeZone property of the UILocalNotification object, so if you do not set the timezone the fire data is considered to be GMT time. try:
notifyAlarm.timeZone = [NSTimeZone defaultTimeZone];
If you set a fire date of 09:00 and then move to a different time zone the alarm will still fire at 09:00 in the new time zone.

how to stop the result on the current date?

I'm having prob,when i open the app i can see the latest result,when i swipe left of the uiview i can see the previous result,the problem that i face i wanted to swipe right to come for the latest result again.
the is the code for swipe left
-(void)swipeLeft
{
NSLog(#"Mag Date:%#",magCurDate);
NSDate *tempDate;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd/MM/yyyy"];
tempDate = [formatter dateFromString:magCurDate];
NSLog(#"temp Date:%#",tempDate);
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setDay:-1];
[dateComponents setHour:8];
NSDate *targetDate = [gregorian dateByAddingComponents:dateComponents toDate:tempDate options:0];
NSLog(#"target Date:%#",targetDate);
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"ddMMYYYY"];
NSString *sDate = [df stringFromDate:targetDate];
NSLog(#"sDate Date:%#",sDate);
[self LoadMagnumResult:sDate];
}
this is my swipe right code,but i couldn't stop on the latest result,i want the last swipe to be the latest result.
-(void)swipeRight
{
NSLog(#"Mag Date:%#",magCurDate);
NSDate *tempDate;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd/MM/yyyy"];
tempDate = [formatter dateFromString:magCurDate];
NSLog(#"temp Date:%#",tempDate);
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setDay:+1];
[dateComponents setHour:8];
NSDate *targetDate = [gregorian dateByAddingComponents:dateComponents toDate:tempDate options:0];
NSLog(#"target Date:%#",targetDate);
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"ddMMYYYY"];
NSString *sDate = [df stringFromDate:targetDate];
NSLog(#"sDate Date:%#",sDate);
[self LoadMagnumResult:sDate];
}
I'm assuming that the latest result cannot be in the future. In other words, the max date for "latest result" is today. I'm also assuming that a left swipe should increment the information until today is reached. If you want a left swipe to jump to today, then the code is even easier. Let me know if that's what you meant. Since I don't have your application, I just made an internal variable that stored a date called testDate. I also put a label on screen and called it outputLabel. You can modify the code to fit your needs.
Finally, I changed the methods to make the right swipe go back in time and the left swipe go forward in time. A user is already used to thinking of a right swipe as going backwards (back on a web browser, etc). Remember a right swipe starts on the left and ends on the right.
First, I would build a helper method to turn dates into strings:
- (NSString*)stringFromDate:(NSDate*)date
{
//Helper method to return a string from a date
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd/MM/yy"];
return [formatter stringFromDate:date];
}
This is my right swipe method. Notice how I use time intervals to increment dates. That can save you a few lines of code from your methods. Unless I'm wrong, it looks like you are trying to increment the date by 24 hours for each swipe. I also made a constant before these two methods so you don't have to search through your code if you want to change the days to increment per swipe.
#define kDaysPerSwipe 1
- (void)swipeRight:(UISwipeGestureRecognizer*)swipeRight
{
NSLog(#"right swipe received");
//Number of days to add
int numberOfDaysToAdd = kDaysPerSwipe;
//Generate a new date
NSDate *newDate = [self.testDate dateByAddingTimeInterval:-(60*60*24*numberOfDaysToAdd)];
//Store the new date
self.testDate = newDate;
//Output the new date
self.outputLabel.text = [self stringFromDate:self.testDate];
}
Here is my left swipe method. Notice how I compare the newDate to today and then only store the EARLIER date of the two before proceeding.
- (void)swipeLeft:(UISwipeGestureRecognizer*)swipeLeft
{
NSLog(#"left swipe received");
//Number of days to add
int numberOfDaysToAdd = kDaysPerSwipe;
//Generate a new date
NSDate *newDate = [self.testDate dateByAddingTimeInterval:(60*60*24*numberOfDaysToAdd)];
NSLog(#"newDate: %#", [self stringFromDate:newDate]);
//Compare newDate to today. Return whichever is earlier.
newDate = [[NSDate date] earlierDate:newDate];
self.testDate = newDate;
//Show the output on the screen
self.outputLabel.text = [self stringFromDate:self.testDate];
}

Calculate time elapsed between pressing the same button twice

I've tried all the time calculating examples I found on this site but somehow I'm getting 0 as value every time. I'm new to IOS and the NSDate is giving me a run for it's money :)
I want to record time A when I press button "startStop", and then record time B when I press it again. Pressing it a second time (deselecting) has to calculate the time elapsed between these 2 dates. So far I have this:
-(IBAction)buttonClick {
NSDate *startStopDate = [NSDate alloc];
NSDateFormatter *formatter= [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"hh:mm:ss"];
NSString *currentTime = [[NSString alloc] init];
NSString *currentTime2 = [[NSString alloc]init];
NSDate *start =[ [NSDate alloc]init];
NSDate *stop = [[NSDate alloc] init];
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
if (startStop.selected==NO) {
NSLog(#"started");
[startStop setSelected:YES];
startStopDate = [NSDate date];
currentTime = [formatter stringFromDate:startStopDate];
NSLog(#"Current timestarted is %#",currentTime);
startTime.text = currentTime;
start = [formatter dateFromString:currentTime];
}
else {
NSLog(#"Selected");
[startStop setSelected:NO];
startStopDate = [NSDate date];
currentTime2 = [formatter stringFromDate:startStopDate];
NSLog(#"Current time is %#",currentTime2);
stopTime.text = currentTime2;
stop = [formatter dateFromString:currentTime2];
NSUInteger unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *components = [gregorianCalendar components:unitFlags
fromDate:start
toDate:stop
options:0];
NSInteger hours = [components hour];
NSInteger minutes = [components minute];
NSInteger seconds = [components second];
NSLog(#"hello %d, %d, %d", hours, minutes, seconds);
}
}
My labels give the correct hour:minute output when pressed, but I can't seem to get them to transfer to the date calculation.
I've been trying numerous variations with dateFromString and stringFromDate and multiple date/string objects as you can see, but so far I only get big negative numbers or just zero as result. Any help appreciated ;)
Greets, Nick
That's because start is a local variable. When the button is clicked the second time, your code will skip the if block and go straight to the else block, leaving the start variable allocated but not initialized to anything useful. You need to store this start value outside of a local context if you want to use it to calculate the difference between the start and stop times.

NSDateFormatter causing zombie woes

I've always had some issues getting the infamously picky NSDateFormatter from causing memory instability in my code. I must not grasp how to use it properly. I've looked at tons of sample code and modeled my method after this, but it seems memory issues still plague me. The issues I'm having is that this method is creating a zombie - not too sure how / why. Some insight would be wonderful!!
-(NSString *)getTimeZoneFormatedDate:(int)subtractMinutes TimeZoneOffset:(NSString *)timeZoneOffset
{
float timeZoneOffsetInt = [timeZoneOffset floatValue];
//Calculate the requested UTC time
NSDate *UTCDateTimeNow = [NSDate date];
NSDate *UTCDateTimePast = [UTCDateTimeNow dateByAddingTimeInterval:((subtractMinutes*60)+(timeZoneOffsetInt*60*60))];
//Round the minutes down
NSDateComponents *time = [[NSCalendar currentCalendar]
components:NSHourCalendarUnit | NSMinuteCalendarUnit
fromDate:UTCDateTimePast];
int minutes = [time minute];
float minuteUnit = floorf((float) minutes / 10);
minutes = minuteUnit * 10;
//Format the minutes string
NSString *minuteString;
minuteString = [NSString stringWithFormat:#"%d",minutes];
if ([minuteString length] < 2)
minuteString = [#"0" stringByAppendingString:minuteString];
//Format the rest of the date & time
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:#"UTC"];
NSDateFormatter *dateFormatter;
dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setTimeZone:timeZone];
[dateFormatter setDateFormat:#"yyyy-MM-dd, HH:"];
NSString *yearMonthDayHourString = [dateFormatter stringFromDate:UTCDateTimePast];
//Put the two together and return it!
return [yearMonthDayHourString stringByAppendingString:minuteString];
}
I'm implementing it like so:
NSString *timeZoneText = [self getTimeZoneFormatedDate:minuteModifier*-10 TimeZoneOffset:radarTimeZoneOffset];
If I run my project with the dateformatter commented out and my method just returning:
return #"blah blah";
No issues - everything runs bug free. So, I believe it's safe to assume the issue lies within! Thanks for the help!
I think the problem is that your "NSString *yearMonthDayHourString" is autoreleased string.
You can retain it in your implementation code something like that
self.timeZoneText = blabla if timeZoneText is property with retain
or just [timeZoneText retain]; and release later;
You can try out NSDateFormatter's getObjectValue:forString:range:error: method. Maybe returned NSError provides you a reasonable explanation why it failed.
On the other hand there might be an easier way to get the result:
NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"dd-MMM-yyyy HH:mm:ss"];
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US"];
[dateFormatter setLocale:usLocale];
[usLocale release];
return [dateFormatter stringFromDate:date];