Segmentation Error In Objective C - objective-c

I am trying to write a program for NSDate in ubuntu (as I don't have mac so I am using Ubuntu to run my objective c programs).
While compiling the program I am getting an error "Segmentation fault (core dumped)".
Below is my code
#import <Foundation/Foundation.h>
#import <objc/objc.h>
#import <objc/Object.h>
int main()
{
NSAutoreleasePool * pool=[[NSAutoreleasePool alloc] init];
NSDate *now = [NSDate date];
NSLog(#"now %#", now);
NSTimeInterval secondsInAWeek = 7 * 24 * 60 * 60;
NSLog(#"secondsInAWeek %#", secondsInAWeek);
NSDate *lastWeek = [NSDate dateWithTimeInterval: secondsInAWeek
sinceDate:now];
NSLog(#"last week %#", lastWeek);
NSDate *nextWeek = [NSDate dateWithTimeInterval: secondsInAWeek
sinceDate:now];
NSLog(#"next week %#", nextWeek);
[pool drain];
return 0;
}
Please help me to find the error. I am able to get the output for NSDate *now, but after that i am getting the segmentation error.
Ask me if you need any more info regarding the code.

I guess I am able to get a solution to my answer. I was trying different things and this solution worked but still I don't know how it did.
#import <Foundation/Foundation.h>
#import <objc/objc.h>
#import <objc/Object.h>
int main()
{
NSAutoreleasePool * pool=[[NSAutoreleasePool alloc] init];
NSDate *now = [NSDate date];
NSLog(#"now %#", now);
NSTimeInterval secondsInAWeek = 7 * 24 * 60 * 60;
NSLog(#"secondsInAWeek %f", secondsInAWeek);
NSDate* lastWeek = [[[NSDate alloc] initWithTimeInterval:-secondsInAWeek sinceDate:now] autorelease];
NSLog(#"last week %#", lastWeek);
NSDate *nextWeek = [[[NSDate alloc] initWithTimeInterval:secondsInAWeek sinceDate:now] autorelease];
NSLog(#"next week %#", nextWeek);
[pool drain];
return 0;
}
I have changed
NSDate *lastWeek = [NSDate dateWithTimeInterval: secondsInAWeek
sinceDate:now];
with
NSDate *lastWeek = [[[NSDate alloc]
initWithTimeInterval:secondsInAWeek sinceDate:now] autorelease];
Its working fine and giving the desired output.
I still don't know why and how it worked. :)

Related

Instances and Calendar Error? Objective-C

This application is supposed to Log how many seconds it's been since a birthdate(1996) but when I try and log NSLog(#"It has been %f seconds since the start of 1996.", seconds); it logs:
2014-01-29 11:36:15.756 TimeAfterTime[750:303] It has been (null) seconds since the start of 1996.
my question is why does it print (null)? This is a Objective-C Command Line Tool application in Xcode. Any suggestions would be greatly appreciated! Thanks
Code I'm using:
// main.m
// TimeAfterTime
//
// Created by JP on 1/28/14.
// Copyright (c) 2014 Big Nerd Ranch. All rights reserved.
//
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
#autoreleasepool {
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setYear:1996];
[comps setMonth:11];
[comps setDay:7];
[comps setHour:13];
[comps setMinute:23];
[comps setSecond:0];
NSCalendar *g = [[[NSCalendar alloc] init] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *dateOfBirth = [g dateFromComponents:comps];
NSDate *now = [[NSDate alloc] init];
NSLog(#"This NSDate object lives at %p", now);
NSLog(#"The date is %#", now);
double seconds = [now timeIntervalSinceDate:dateOfBirth];
NSLog(#"It has been %f seconds since the start of 1996.", seconds);
}
return 0;
}
The result it prints in the console:
2014-01-29 11:36:15.752 TimeAfterTime[750:303] This NSDate object lives at 0x100103680
2014-01-29 11:36:15.756 TimeAfterTime[750:303] The date is 2014-01-29 16:36:15 +0000
2014-01-29 11:36:15.756 TimeAfterTime[750:303] It has been (null) seconds since the start of 1996.
Program ended with exit code: 0
NSCalendar *g = [[[NSCalendar alloc] init] initWithCalendarIdentifier:NSGregorianCalendar];
should be
NSCalendar *g = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
Due to the wrong initialization, g = nil and thus dateOfBirth = nil.

Building Objective-C Command Line App?

I'm kinda new to Objective-C and I have a basic app I'm tinkering with in Xcode that simply reads all calendar events (using EventKit) and then reformats the data and dumps it as a json encoded string.
I can get the code to run and return the data correctly on my iMac (in Xcode), but my Macbook Air returns no results using the same calendars (synced through iCloud). It also runs and returns results on a friends machine (in Xcode). If I build the app and run it from the command line, I get no results, even on the machines that it does work properly in Xcode.
Is there something extra that I'm missing here? This is the code I currently have. Can someone give me some kind of pointer as to what to try next to get this to work? I just can't figure out why it works on one machine and not the other, and why it works in Xcode and not from the command line.
Thoughts?
#import <Foundation/Foundation.h>
#import <EventKit/EKEventStore.h>
#import <EventKit/EKEvent.h>
#import <EventKit/EKCalendarItem.h>
int main(int argc, const char * argv[])
{
#autoreleasepool {
EKEventStore *store = [[EKEventStore alloc] init];
NSCalendar *currCalendar = [NSCalendar currentCalendar];
NSDateComponents *oneDayAgoComponents = [[NSDateComponents alloc] init];
oneDayAgoComponents.day = -1;
NSDate *oneDayAgo = [currCalendar dateByAddingComponents:oneDayAgoComponents
toDate:[NSDate date]
options:0];
NSDateComponents *oneYearFromNowComponents = [[NSDateComponents alloc] init];
oneYearFromNowComponents.year = 1;
NSDate *oneYearFromNow = [currCalendar dateByAddingComponents:oneYearFromNowComponents
toDate:[NSDate date]
options:0];
NSPredicate *predicate = [store predicateForEventsWithStartDate:oneDayAgo
endDate:oneYearFromNow
calendars:nil];
NSArray *events = [store eventsMatchingPredicate:predicate];
int i;
int eventCount = (int)[events count];
NSMutableArray *formattedEvents = [[NSMutableArray alloc] init];
for (i=0; i<eventCount; i++) {
NSDictionary *dict = #{
#"title" : [[events objectAtIndex:i] title],
#"starts" : [[[events objectAtIndex:i] startDate] description],
#"ends" : [[[events objectAtIndex:i] endDate] description],
};
[formattedEvents addObject:dict];
}
NSArray *eventArray = [NSArray arrayWithArray:formattedEvents];
NSData *jsondata = [NSJSONSerialization dataWithJSONObject:eventArray options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsondata encoding:NSUTF8StringEncoding];
printf("%s", [jsonString UTF8String]);
return 0;
}
}
Ended up being a sandbox issue. I had to go check the EKAuthorizationStatus of EKEntityTypeEvent's to determine if the app had access to the events and if not, request it.
Seems odd that it requested access initially from within Xcode with no issues on my iMac but never did on my Macbook but, oh well. Fixed.

"NSDate not an Objective-C object" error shows when run the application in IOS 7 in real device

NSDate object is working for iPhone, iPad when i ran the application in real devices. But when I run the application in iPad real device than it gives <not an Objective-C object> error. I tried to sort out it. but couldn't.
- (NSString*)getDateFromJSONToStringSaveFormat:(NSString *)dateString
{
NSDate *_Date = [NSDate alloc] init];
NSDate *_Date = [self getDateFromJSON:dateString];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
return [dateFormatter stringFromDate:_Date];
}
- (NSDate*) getDateFromJSON:(NSString *)dateString
{
// Expect date in this format "/Date(1268123281843)/"
int startPos = [dateString rangeOfString:#"("].location+1;
int endPos = [dateString rangeOfString:#")"].location;
NSRange range = NSMakeRange(startPos,endPos-startPos);
unsigned long long milliseconds = [[dateString substringWithRange:range] longLongValue];
NSTimeInterval interval = milliseconds/1000;
return [NSDate dateWithTimeIntervalSince1970:interval];
}
because of this issue i initialize the NSDate object and saw the date value. (NSDate *_Date = [NSDate alloc] init];) in here also gives same error? why is that? anyone faced this error ??
First off you can just remove this line:
NSDate *_Date = [NSDate alloc] init];
Since the next line just redeclares it, also you in the line you should remove you are missing a [.
- (NSString*)getDateFromJSONToStringSaveFormat:(NSString *)dateString
{
// Not needed since the line after it also declares the variable.
//NSDate *_Date = [NSDate alloc] init];
NSDate *_Date = [self getDateFromJSON:dateString];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
return [dateFormatter stringFromDate:_Date];
}

NSString to NSDate is NOT working when called multiple times

I have written this function in a class:
- (NSDate *) convertDate : (NSString *) dateStr{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSDate *dateFrmStr = [[NSDate alloc] init];
dateFrmStr = [dateFormatter dateFromString:dateStr];
return dateFrmStr;
}
I am calling this function in another class like this:
NSString * dateStr1 =#"01-01-1977";
NSString * dateStr2 =#"22-12-1977";
NSString * dateStr3 =#"19-01-1978";
MyClass *data = [[MyClass alloc]init];
NSDate *dateObj1 = [data convertDate:dateStr1];
NSDate *dateObj2 = [data convertDate:dateStr2];
NSDate *dateObj3 = [data convertDate:dateStr3];
NSLog(#" >>> dateObj1 %#",dateObj1);
NSLog(#" >>> dateObj2 %#",dateObj2);
NSLog(#" >>> dateObj3 %#",dateObj3);
When I run this the only first date seems to get converted because the output I get is :
>>> dateObj1 1977-01-01 00:00:00 +0000
There is no error nothing but the programs just stops.
I've tried you're code and for me works very fine( with ARC ), probably you're issue is somewhere else in "MyClass"…
BTW! Why don't you make a "category" on NSDate?
Something like this :
NSDate + ConvertDate.h
#interface NSDate (ConvertDate)
+(NSDate *) convertDateFromString : (NSString *)dateString;
#end
NSDate + ConvertDate.m
#implementation NSDate (ConvertDate)
+(NSDate *)convertDateFromString:(NSString *)dateString{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
return [dateFormatter dateFromString:dateString];
}
#end
Yes it looks like your code, the only differences are that you don't need to allocate an instance of "MyClass" to use the
"convertDateFromString" method because you're using a class method.'
could it be
NSString * dateStr2 =#"22-12-1977";
that NSDate thinks 22 as the month??? maybe try 12-22-1977 instead?? i usually use NSDateFormatter to convert to string or date..

comparing Two NSDate objects not working

I'm learning about how to compare NSDate objects with the isEqualToDateDate method. I don't get why this simple test does not return true and print out the NSLog. Thanks in advance
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSDate *myDate = [[NSDate alloc]initWithTimeIntervalSinceNow:4000000];
NSDate *otherDate = [[NSDate alloc]initWithTimeIntervalSinceNow:4000000];
NSLog(#"myDate %#",myDate);
NSLog(#"otherDate %#",otherDate);
if ([myDate isEqualToDate:otherDate]) {
NSLog(#"The dates are the same");
};
[myDate release];
[otherDate release];
[pool drain];
return 0;
}
I believe, and this may be wrong, that since you are using initWithTimeIntervalSinceNow that the objects are being allocated at slightly different times, thus making them unequal.
Both dates are indeed slightly different. Quick example to show the difference:
NSDate *one = [[NSDate alloc]initWithTimeIntervalSinceNow:4000000];
NSDate *two = [[NSDate alloc]initWithTimeIntervalSinceNow:4000000];
NSComparisonResult difference = [two compare:one];
NSLog(#"Date one: %#",one);
NSLog(#"Date two: %#",two);
NSLog(#"Exact difference: %ld",difference);
Output:
Date one: 2012-01-03 07:47:40 +0000
Date two: 2012-01-03 07:47:40 +0000
Exact difference: 1
EDIT
isEqualToDate: returns true in the following example:
NSDate *one = [[NSDate alloc]initWithTimeIntervalSince1970:4000000];
NSDate *two = [[NSDate alloc]initWithTimeIntervalSince1970:4000000];
if ([one isEqualToDate:two]) NSLog(#"Equal");
Output:
Equal