Search Results

Search found 240 results on 10 pages for 'nsdate'.

Page 4/10 | < Previous Page | 1 2 3 4 5 6 7 8 9 10  | Next Page >

  • Data Formatters temporarily unavailable

    - by Zac Altman
    Im trying to use Date Formatters (UIDateFormatter), but I keep getting this error: Program received signal: “EXC_BAD_ACCESS”. Data Formatters temporarily unavailable, will re-try after a 'continue'. (Unknown error loading shared library "/Developer/usr/lib/libXcodeDebuggerSupport.dylib")

    Read the article

  • Unable to Parse Date using NSDateFormatter

    - by Ansari
    Hi, I am fetching a RSS, in which i receive the following Date stamp: 2010-05-10T06:11:14.000Z Now i am using NSDateFormatter to parse this datetime stamp. [parseFormatter setDateFormat:@"yyyy-MM-dTH:m:s.z"]; But its not working fine if just remove the time stamp part it works for the date [parseFormatter setDateFormat:@"yyyy-MM-d"]; But if i add the rest of the stuff it returns nil. Any idea ? Thanks in Advance....

    Read the article

  • Singleton EXC_BAD_ACCESS

    - by lclaud
    Hi, so I have a class that I decleare as a singleton and in that class I have a NSMutableArray that contains some NSDictionaries with some key/value pairs in them. The trouble is it doesn't work and I dont't know why... I mean it crashes with EXC_BAD_ACCESS but i don't know where. I followed the code and it did create a new array on first add, made it to the end of the funtion ..and crashed ... @interface dataBase : NSObject { NSMutableArray *inregistrari; } @property (nonatomic,retain) NSMutableArray *inregistrari; -(void)adaugaInregistrareCuData:(NSDate *)data siValoare:(NSNumber *)suma caVenit:(BOOL)venit cuDetaliu:(NSString *)detaliu; -(NSDictionary *)raportIntreData:(NSDate *)dataInitiala siData:(NSDate *)dataFinala; -(NSArray *)luniDisponibileIntreData:(NSDate *)dataInitiala siData:(NSDate *)dataFinala; -(NSArray *)aniDisponibiliIntreData:(NSDate *)dataInitiala siData:(NSDate *)dataFinala; -(NSArray *)vectorDateIntreData:(NSDate *)dataI siData:(NSDate *)dataF; -(void)salveazaInFisier; -(void)incarcaDinFisier; + (dataBase *)shareddataBase; @end And here is the .m file #import "dataBase.h" #import "SynthesizeSingleton.h" @implementation dataBase @synthesize inregistrari; SYNTHESIZE_SINGLETON_FOR_CLASS(dataBase); -(void)adaugaInregistrareCuData:(NSDate *)data siValoare:(NSNumber *)suma caVenit:(BOOL)venit cuDetaliu:(NSString *)detaliu{ NSNumber *v=[NSNumber numberWithBool:venit]; NSArray *input=[NSArray arrayWithObjects:data,suma,v,detaliu,nil]; NSArray *keys=[NSArray arrayWithObjects:@"data",@"suma",@"venit",@"detaliu",nil]; NSDictionary *inreg=[NSDictionary dictionaryWithObjects:input forKeys:keys]; if(inregistrari == nil) { inregistrari=[[NSMutableArray alloc ] initWithObjects:inreg,nil]; }else { [inregistrari addObject:inreg]; } [inreg release]; [input release]; [keys release]; } It made it to the end of that adaugaInregistrareCuData ... ok . said the array had one object ... and then crashed

    Read the article

  • sigleton EXC_BAD_ACCESS

    - by lclaud
    Hi, so I have a class that I decleare as a singleton and in that class I have a NSMutableArray that contains some NSDictionaries with some key/value pairs in them. The trouble is it doesn't work and I dont't know why... I mean it crashes with EXC_BAD_ACCESS but i don't know where. I followed the code and it did create a new array on first add, made it to the end of the funtion ..and crashed ... @interface dataBase : NSObject { NSMutableArray *inregistrari; } @property (nonatomic,retain) NSMutableArray *inregistrari; -(void)adaugaInregistrareCuData:(NSDate *)data siValoare:(NSNumber *)suma caVenit:(BOOL)venit cuDetaliu:(NSString *)detaliu; -(NSDictionary *)raportIntreData:(NSDate *)dataInitiala siData:(NSDate *)dataFinala; -(NSArray *)luniDisponibileIntreData:(NSDate *)dataInitiala siData:(NSDate *)dataFinala; -(NSArray *)aniDisponibiliIntreData:(NSDate *)dataInitiala siData:(NSDate *)dataFinala; -(NSArray *)vectorDateIntreData:(NSDate *)dataI siData:(NSDate *)dataF; -(void)salveazaInFisier; -(void)incarcaDinFisier; + (dataBase *)shareddataBase; @end And here is the .m file #import "dataBase.h" #import "SynthesizeSingleton.h" @implementation dataBase @synthesize inregistrari; SYNTHESIZE_SINGLETON_FOR_CLASS(dataBase); -(void)adaugaInregistrareCuData:(NSDate *)data siValoare:(NSNumber *)suma caVenit:(BOOL)venit cuDetaliu:(NSString *)detaliu{ NSNumber *v=[NSNumber numberWithBool:venit]; NSArray *input=[NSArray arrayWithObjects:data,suma,v,detaliu,nil]; NSArray *keys=[NSArray arrayWithObjects:@"data",@"suma",@"venit",@"detaliu",nil]; NSDictionary *inreg=[NSDictionary dictionaryWithObjects:input forKeys:keys]; if(inregistrari == nil) { inregistrari=[[NSMutableArray alloc ] initWithObjects:inreg,nil]; }else { [inregistrari addObject:inreg]; } [inreg release]; [input release]; [keys release]; } It made it to the end of that adaugaInregistrareCuData ... ok . said the array had one object ... and then crashed

    Read the article

  • EKCalendar not added to iCal

    - by Alex75
    I have a strange behavior on my iPhone. I'm creating an application that uses calendar events (EventKit). The class that use is as follows: the .h one #import "GenericManager.h" #import <EventKit/EventKit.h> #define oneDay 60*60*24 #define oneHour 60*60 @protocol CalendarManagerDelegate; @interface CalendarManager : GenericManager /* * metodo che aggiunge un evento ad un calendario di nome Name nel giorno onDate. * L'evento da aggiungere viene recuperato tramite il dataSource che è quindi * OBBLIGATORIO (!= nil). * * Restituisce YES solo se il delegate è conforme al protocollo CalendarManagerDataSource. * NO altrimenti */ + (BOOL) addEventForCalendarWithName:(NSString *) name fromDate:(NSDate *)fromDate toDate: (NSDate *) toDate withDelegate:(id<CalendarManagerDelegate>) delegate; /* * metodo che aggiunge un evento per giorno compreso tra fromDate e toDate ad un * calendario di nome Name. L'evento da aggiungere viene recuperato tramite il dataSource * che è quindi OBBLIGATORIO (!= nil). * * Restituisce YES solo se il delegate è conforme al protocollo CalendarManagerDataSource. * NO altrimenti */ + (BOOL) addEventsForCalendarWithName:(NSString *) name fromDate:(NSDate *)fromDate toDate: (NSDate *) toDate withDelegate:(id<CalendarManagerDelegate>) delegate; @end @protocol CalendarManagerDelegate <NSObject> // viene inviato quando il calendario necessita informazioni sull' evento da aggiungere - (void) calendarManagerDidCreateEvent:(EKEvent *) event; @end the .m one // // CalendarManager.m // AppCampeggioSingolo // // Created by CreatiWeb Srl on 12/17/12. // Copyright (c) 2012 CreatiWeb Srl. All rights reserved. // #import "CalendarManager.h" #import "Commons.h" #import <objc/message.h> @interface CalendarManager () @end @implementation CalendarManager + (void)requestToEventStore:(EKEventStore *)eventStore delegate:(id)delegate fromDate:(NSDate *)fromDate toDate: (NSDate *) toDate name:(NSString *)name { if([eventStore respondsToSelector:@selector(requestAccessToEntityType:completion:)]) { // ios >= 6.0 [eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) { if (granted) { [self addEventForCalendarWithName:name fromDate: fromDate toDate: toDate inEventStore:eventStore withDelegate:delegate]; } else { } }]; } else if (class_getClassMethod([EKCalendar class], @selector(calendarIdentifier)) != nil) { // ios >= 5.0 && ios < 6.0 [self addEventForCalendarWithName:name fromDate:fromDate toDate:toDate inEventStore:eventStore withDelegate:delegate]; } else { // ios < 5.0 EKCalendar *myCalendar = [eventStore defaultCalendarForNewEvents]; EKEvent *event = [self generateEventForCalendar:myCalendar fromDate: fromDate toDate: toDate inEventStore:eventStore withDelegate:delegate]; [eventStore saveEvent:event span:EKSpanThisEvent error:nil]; } } /* * metodo che recupera l'identificativo del calendario associato all'app o nil se non è mai stato creato. */ + (NSString *) identifierForCalendarName: (NSString *) name { NSString * confFileName = [self pathForFile:kCurrentCalendarFileName]; NSDictionary *confCalendar = [NSDictionary dictionaryWithContentsOfFile:confFileName]; NSString *currentIdentifier = [confCalendar objectForKey:name]; return currentIdentifier; } /* * memorizza l'identifier del calendario */ + (void) saveCalendarIdentifier:(NSString *) identifier andName: (NSString *) name { if (identifier != nil) { NSString * confFileName = [self pathForFile:kCurrentCalendarFileName]; NSMutableDictionary *confCalendar = [NSMutableDictionary dictionaryWithContentsOfFile:confFileName]; if (confCalendar == nil) { confCalendar = [NSMutableDictionary dictionaryWithCapacity:1]; } [confCalendar setObject:identifier forKey:name]; [confCalendar writeToFile:confFileName atomically:YES]; } } + (EKCalendar *)getCalendarWithName:(NSString *)name inEventStore:(EKEventStore *)eventStore withLocalSource: (EKSource *)localSource forceCreation:(BOOL) force { EKCalendar *myCalendar; NSString *identifier = [self identifierForCalendarName:name]; if (force || identifier == nil) { NSLog(@"create new calendar"); if (class_getClassMethod([EKCalendar class], @selector(calendarForEntityType:eventStore:)) != nil) { // da ios 6.0 in avanti myCalendar = [EKCalendar calendarForEntityType:EKEntityTypeEvent eventStore:eventStore]; } else { myCalendar = [EKCalendar calendarWithEventStore:eventStore]; } myCalendar.title = name; myCalendar.source = localSource; NSError *error = nil; BOOL result = [eventStore saveCalendar:myCalendar commit:YES error:&error]; if (result) { NSLog(@"Saved calendar %@ to event store. %@",myCalendar,eventStore); } else { NSLog(@"Error saving calendar: %@.", error); } [self saveCalendarIdentifier:myCalendar.calendarIdentifier andName:name]; } // You can also configure properties like the calendar color etc. The important part is to store the identifier for later use. On the other hand if you already have the identifier, you can just fetch the calendar: else { myCalendar = [eventStore calendarWithIdentifier:identifier]; NSLog(@"fetch an old-one = %@",myCalendar); } return myCalendar; } + (EKCalendar *)addEventForCalendarWithName: (NSString *) name fromDate:(NSDate *)fromDate toDate: (NSDate *) toDate inEventStore:(EKEventStore *)eventStore withDelegate: (id<CalendarManagerDelegate>) delegate { // da ios 5.0 in avanti EKCalendar *myCalendar; EKSource *localSource = nil; for (EKSource *source in eventStore.sources) { if (source.sourceType == EKSourceTypeLocal) { localSource = source; break; } } @synchronized(self) { myCalendar = [self getCalendarWithName:name inEventStore:eventStore withLocalSource:localSource forceCreation:NO]; if (myCalendar == nil) myCalendar = [self getCalendarWithName:name inEventStore:eventStore withLocalSource:localSource forceCreation:YES]; NSLog(@"End synchronized block %@",myCalendar); } EKEvent *event = [self generateEventForCalendar:myCalendar fromDate:fromDate toDate:toDate inEventStore:eventStore withDelegate:delegate]; [eventStore saveEvent:event span:EKSpanThisEvent error:nil]; return myCalendar; } + (EKEvent *) generateEventForCalendar: (EKCalendar *) calendar fromDate:(NSDate *)fromDate toDate: (NSDate *) toDate inEventStore:(EKEventStore *) eventStore withDelegate:(id<CalendarManagerDelegate>) delegate { EKEvent *event = [EKEvent eventWithEventStore:eventStore]; event.startDate=fromDate; event.endDate=toDate; [delegate calendarManagerDidCreateEvent:event]; [event setCalendar:calendar]; // ricerca dell'evento nel calendario, se ne trovo uno uguale non lo inserisco NSPredicate *predicate = [eventStore predicateForEventsWithStartDate:fromDate endDate:toDate calendars:[NSArray arrayWithObject:calendar]]; NSArray *matchEvents = [eventStore eventsMatchingPredicate:predicate]; if ([matchEvents count] > 0) { // ne ho trovati di gia' presenti, vediamo se uno e' quello che vogliamo inserire BOOL found = NO; for (EKEvent *fetchEvent in matchEvents) { if ([fetchEvent.title isEqualToString:event.title] && [fetchEvent.notes isEqualToString:event.notes]) { found = YES; break; } } if (found) { // esiste già e quindi non lo inserisco NSLog(@"OH NOOOOOO!!"); event = nil; } } return event; } #pragma mark - Public Methods + (BOOL) addEventForCalendarWithName:(NSString *) name fromDate:(NSDate *)fromDate toDate: (NSDate *) toDate withDelegate:(id<CalendarManagerDelegate>) delegate { BOOL retVal = YES; EKEventStore *eventStore=[[EKEventStore alloc] init]; if ([delegate conformsToProtocol:@protocol(CalendarManagerDelegate)]) { [self requestToEventStore:eventStore delegate:delegate fromDate:fromDate toDate: toDate name:name]; } else { retVal = NO; } return retVal; } + (BOOL) addEventsForCalendarWithName:(NSString *) name fromDate:(NSDate *)fromDate toDate: (NSDate *) toDate withDelegate:(id<CalendarManagerDelegate>) delegate { BOOL retVal = YES; NSDate *dateCursor = fromDate; EKEventStore *eventStore=[[EKEventStore alloc] init]; if ([delegate conformsToProtocol:@protocol(CalendarManagerDelegate)]) { while (retVal && ([dateCursor compare:toDate] == NSOrderedAscending)) { NSDate *finish = [dateCursor dateByAddingTimeInterval:oneDay]; [self requestToEventStore:eventStore delegate:delegate fromDate: dateCursor toDate: finish name:name]; dateCursor = [dateCursor dateByAddingTimeInterval:oneDay]; } } else { retVal = NO; } return retVal; } @end In practice, on my iphone I get the log: fetch an old-one = (null) 19/12/2012 11:33:09.520 AppCampeggioSingolo [730:8 b1b] create new calendar 19/12/2012 11:33:09.558 AppCampeggioSingolo [730:8 b1b] Saved calendar EKCalendar every time I add an event, then I look and I can not find it on iCal calendar event he added. On the iPhone of a friend of mine, however, everything is working correctly. I doubt that the problem stems from the code, but just do not understand what it could be. I searched all day yesterday and part of today on google but have not found anything yet. Any help will be greatly appreciated EDIT: I forgot the call wich is [CalendarManager addEventForCalendarWithName: @"myCalendar" fromDate:fromDate toDate: toDate withDelegate:self]; in the delegate method simply set title and notes of the event like this - (void) calendarManagerDidCreateEvent:(EKEvent *) event { event.title = @"the title"; event.notes = @"some notes"; }

    Read the article

  • Easiest way to get an NSDate representation of "the next 7am that will occur" in Cocoa?

    - by Drarok
    I figure I can achieve what I want by using NSCalendar and NSDateComponents, but that would run something like the following: Get "now" Create an NSDateComponents from "now". If "now" is pre-7am, then use today's date. If "now" is post-7am, use tomorrow's date. If today is the last day of the month, increase month, set day to 1. If it was December, increase year by 1 also. Set hour, minute, second. Create a new NSDate. It all seems very long-winded, but that appears to be what other answers on here suggest, and the documentation doesn't offer any clues. I'm going back and forth between all the date and calendar classes I can find. Is there a simple way to ask for the "next occurring 7am" ? Thanks.

    Read the article

  • Simple CalendarStore query puts application into infinite loop!?

    - by Frank R.
    Hi, I've been looking at adding iCal support to my new application and everything seemed just fine and worked on my Mac OS X 10.6 Snow Leopard development machine without a hitch. Now it looks like depending on what is in your calendar the very simple query below: - (NSArray*) fetchCalendarEventsForNext50Minutes { NSLog(@"fetchCalendarEventsForNext50Minutes"); NSTimeInterval start = [NSDate timeIntervalSinceReferenceDate]; NSDate* startDate = [[NSDate alloc] init]; NSDate* endDate = [startDate addTimeInterval: 50.0 * 60.0]; NSPredicate *eventsForTheNext50Minutes = [CalCalendarStore eventPredicateWithStartDate:startDate endDate:endDate calendars:[[CalCalendarStore defaultCalendarStore] calendars]]; // Fetch all events for this year NSArray *events = [[CalCalendarStore defaultCalendarStore] eventsWithPredicate: eventsForTheNext50Minutes]; NSLog( @"fetch took: %f seconds", [NSDate timeIntervalSinceReferenceDate] - start ); return events; } produces a beachball thrash even with quite limited events in the calendar store. Am I missing something crucial here? The code snippet is pretty much exactly from the documentation at: // Create a predicate to fetch all events for this year NSInteger year = [[NSCalendarDate date] yearOfCommonEra]; NSDate *startDate = [[NSCalendarDate dateWithYear:year month:1 day:1 hour:0 minute:0 second:0 timeZone:nil] retain]; NSDate *endDate = [[NSCalendarDate dateWithYear:year month:12 day:31 hour:23 minute:59 second:59 timeZone:nil] retain]; NSPredicate *eventsForThisYear = [CalCalendarStore eventPredicateWithStartDate:startDate endDate:endDate calendars:[[CalCalendarStore defaultCalendarStore] calendars]]; // Fetch all events for this year NSArray *events = [[CalCalendarStore defaultCalendarStore] eventsWithPredicate:eventsForThisYear]; It looks like it has something to do with the recurrence rules, but as far as I can see there are no other ways of fetching events from the calendar store anyway. Has anybody else come across this? Best regards, Frank

    Read the article

  • Cannot read values from [NSUserDefaults standardUserDefaults] after synchronize

    - by Nonlinearsound
    In the Application Delegate didFinishLaunching method, I am using the following code to build up a new NSDictionary to be used as the new settings bundle for the user: NSNumber *testValue = (NSNumber*)[[NSUserDefaults standardUserDefaults] objectForKey:@"settingsversion"]; if (testValue == nil) { NSNumber *numNewDB = [NSNumber numberWithBool:NO]; NSNumber *numFirstUse = [NSNumber numberWithBool:YES]; NSDate *dateLastStatic = [NSDate date]; NSDate *dateLastMobile = [NSDate date]; NSNumber *numSettingsversion = [NSNumber numberWithFloat:1.0]; NSDictionary *appDefaults = [NSDictionary dictionaryWithObjectsAndKeys: numNewDB, @"newdb", numFirstUse, @"firstuse", numSettingsversion, @"settingsversion", dateLastStatic, @"laststaticupdate", dateLastMobile, @"lastmobileupdate", nil]; [[NSUserDefaults standardUserDefaults] registerDefaults:appDefaults]; [[NSUserDefaults standardUserDefaults] synchronize]; } Later in another ViewController I am trying to read back a value from that same Dictionary, saved as the NSUserDefaults - well at least I thought it would, but I don't get any valid object pointer for the desired member lastUpdate back there: in .h file: NSDate *lastUpdate; in the .m file in a member function: lastUpdate = (NSDate *)[[NSUserDefaults standardUserDefaults] objectForKey:@"laststaticupdate"]; Even, if I print out the content of [NSUserDefaults standardUserDefaults] I only get this: 2010-04-29 15:13:22.322 myApp[4136:207] Content of UserDefaults: <NSUserDefaults: 0x11d340> This leads me to the conclusion that there is no standardUserDefaults dictionary somewhere in memory or it cannot be determined as such a structure. Edit: Every time, I restart the app ión the device, the check for testValue is Nil and I am building up the dictionary again but after one run it should be persistent on the Phone, right? Am I doing something wrong somewhere in between? I have the feeling that I yet didn't really understand how to load and save settings persistent for a certain application on the iPhone. Is there anything I have to do additionally to this? Integrating a settings.bundle in XCode or saving the dictionary manually to the Documents folder? Can someone help me out here? Thanks a lot!

    Read the article

  • Performance issue finding weekdays over a given period

    - by Oysio
    I have some methods that return the number of weekdays between two given dates. Since calling these methods become very expensive to call when the two dates lie years apart, I'm wondering how these methods could be refactored in a more efficient way. The returned result is correct but I feel that the iphone processor is struggling to keep up and consequently freezes up the application when I would call these methods over a period of say 10years. Any suggestions ? //daysList contains all weekdays that need to be found between the two dates -(NSInteger) numberOfWeekdaysFromDaysList:(NSMutableArray*) daysList startingFromDate:(NSDate*)startDate toDate:(NSDate*)endDate { NSInteger retNumdays = 0; for (Day *dayObject in [daysList objectEnumerator]) { if ([dayObject isChecked]) { retNumdays += [self numberOfWeekday:[dayObject weekdayNr] startingFromDate:startDate toDate:endDate]; } } return retNumdays; } -(NSInteger) numberOfWeekday:(NSInteger)day startingFromDate:(NSDate*)startDate toDate:(NSDate*)endDate { NSInteger numWeekdays = 0; NSDate *nextDate = startDate; NSComparisonResult result = [endDate compare:nextDate]; //Do while nextDate is in the past while (result == NSOrderedDescending || result == NSOrderedSame) { if ([NSDate weekdayFromDate:nextDate] == day) { numWeekdays++; } nextDate = [nextDate dateByAddingDays:1]; result = [endDate compare:nextDate]; } return numWeekdays; }

    Read the article

  • How do I break down an NSTimeInterval into year, months, days, hours, minutes and seconds on iPhone?

    - by willc2
    I have a time interval that spans years and I want all the time components from year down to seconds. My first thought is to integer divide the time interval by seconds in a year, subtract that from a running total of seconds, divide that by seconds in a month, subtract that from the running total and so on. That just seems convoluted and I've read that whenever you are doing something that looks convoluted, there is probably a built-in method. Is there? I integrated Alex's 2nd method into my code. It's in a method called by a UIDatePicker in my interface. NSDate *now = [NSDate date]; NSDate *then = self.datePicker.date; NSTimeInterval howLong = [now timeIntervalSinceDate:then]; NSDate *date = [NSDate dateWithTimeIntervalSince1970:howLong]; NSString *dateStr = [date description]; const char *dateStrPtr = [dateStr UTF8String]; int year, month, day, hour, minute, sec; sscanf(dateStrPtr, "%d-%d-%d %d:%d:%d", &year, &month, &day, &hour, &minute, &sec); year -= 1970; NSLog(@"%d years\n%d months\n%d days\n%d hours\n%d minutes\n%d seconds", year, month, day, hour, minute, sec); When I set the date picker to a date 1 year and 1 day in the past, I get: 1 years 1 months 1 days 16 hours 0 minutes 20 seconds which is 1 month and 16 hours off. If I set the date picker to 1 day in the past, I am off by the same amount. Update: I have an app that calculates your age in years, given your birthday (set from a UIDatePicker), yet it was often off. This proves there was an inaccuracy, but I can't figure out where it comes from, can you?

    Read the article

  • How do I break down an NSTimeInterval into year, months, days, hours, minutes and seconds on iPhone?

    - by willc2
    I have a time interval that spans years and I want all the time components from year down to seconds. My first thought is to integer divide the time interval by seconds in a year, subtract that from a running total of seconds, divide that by seconds in a month, subtract that from the running total and so on. That just seems convoluted and I've read that whenever you are doing something that looks convoluted, there is probably a built-in method. Is there? I integrated Alex's 2nd method into my code. It's in a method called by a UIDatePicker in my interface. NSDate *now = [NSDate date]; NSDate *then = self.datePicker.date; NSTimeInterval howLong = [now timeIntervalSinceDate:then]; NSDate *date = [NSDate dateWithTimeIntervalSince1970:howLong]; NSString *dateStr = [date description]; const char *dateStrPtr = [dateStr UTF8String]; int year, month, day, hour, minute, sec; sscanf(dateStrPtr, "%d-%d-%d %d:%d:%d", &year, &month, &day, &hour, &minute, &sec); year -= 1970; NSLog(@"%d years\n%d months\n%d days\n%d hours\n%d minutes\n%d seconds", year, month, day, hour, minute, sec); When I set the date picker to a date 1 year and 1 day in the past, I get: 1 years 1 months 1 days 16 hours 0 minutes 20 seconds which is 1 month and 16 hours off. If I set the date picker to 1 day in the past, I am off by the same amount. Update: I have an app that calculates your age in years, given your birthday (set from a UIDatePicker), yet it was often off. This proves there was an inaccuracy, but I can't figure out where it comes from, can you?

    Read the article

  • Picker view wont rotate- iPhone

    - by lotuseater
    hi, I am making a booking page. I have included 3 pickers in it. I have included all the delegates required for the pickers to work but it wont rotate. I have enabled user interaction and multitouch in the nib file. Here is my code. Please help me. :( @interface ChooseContactsFrom : UIViewController { IBOutlet UIPickerView *statePickup; IBOutlet UIPickerView *paymentMethodPickup; IBOutlet UIDatePicker *expiryDatePickup; IBOutlet UIView *statePickupView; IBOutlet UIView *paymentMethodPickupView; IBOutlet UIView *expiryDatePickupView; } (void)viewDidLoad { self.title = @"Choose Contacts"; //Fill in the states name/ stateArray = [[NSArray alloc]initWithObjects:@"",nil]; paymentModeArray = [[NSArray alloc] initWithObjects:@"Credit Card", @"Cash",@"Account",@"Voucher",@"Debit Card", nil]; paymentMethodPickup.frame = CGRectMake(0.0, 44.0, paymentMethodPickup.frame.size.width, paymentMethodPickup.frame.size.height); paymentMethodPickup.userInteractionEnabled = YES; paymentMethodPickup.multipleTouchEnabled = YES; paymentMethodPickupView.frame = CGRectMake(0.0, 210.0, paymentMethodPickupView.frame.size.width, paymentMethodPickupView.frame.size.height); statePickup.frame = CGRectMake(0.0, 44.0,statePickup.frame.size.width, statePickup.frame.size.height); statePickupView.frame = CGRectMake(0.0, 210.0, statePickupView.frame.size.width, statePickupView.frame.size.height); stateArray = [[NSArray alloc] initWithObjects:@"state1", @"state2", @"state3", @"state4", @"state5", @"state6", @"state7", @"state8", @"state9", @"state10", nil]; expiryDatePickup.frame = CGRectMake(0.0, 44.0, expiryDatePickup.frame.size.width, expiryDatePickup.frame.size.height); expiryDatePickupView.frame = CGRectMake(0.0, 210.0, expiryDatePickupView.frame.size.width, expiryDatePickupView.frame.size.height); [super viewDidLoad]; } -(IBAction)back:(id)sender { [self dismissModalViewControllerAnimated:YES]; } pragma mark pickerView delegates (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView { return 1; } (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component { if( thePickerView == statePickup) { return [stateArray count]; } else if(thePickerView == paymentMethodPickup) { return [paymentModeArray count]; } else { return 0; } } (NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component { if(thePickerView == statePickup) { return [stateArray objectAtIndex:row]; } else if(thePickerView == paymentMethodPickup) { return [paymentModeArray objectAtIndex:row]; } else { return @" "; } } (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{ return 50; } (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component { return 250; } (void)pickerView:(UIPickerView *)thepickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component { if(thepickerView == statePickup) { state.text=[stateArray objectAtIndex:row]; } if(thepickerView == paymentMethodPickup) { payment.text=[paymentModeArray objectAtIndex:row]; } } (void)ClearSubviews { //[firstName resignFirstResponder]; // [lastName resignFirstResponder]; // [email resignFirstResponder]; // [address1 resignFirstResponder]; // [address2 resignFirstResponder]; // [city resignFirstResponder]; // //[state resignFirstResponder]; // [payment resignFirstResponder]; // [creditCard resignFirstResponder]; // [expirydate removeFromSuperview]; // [statePickup removeFromSuperview]; // [paymentMethodPickup removeFromSuperview]; } (BOOL)textFieldShouldBeginEditing:(UITextField *)textField { // [self showPicker:textField]; //[self setViewMovedUp]; if(textField == firstName || textField == lastName || textField == email || textField == address1 || textField == address2 ||textField == city) { [self ClearSubviews]; //pickerToolbar.hidden = TRUE; return YES; } else if(textField == payment) { [self ClearSubviews]; [self setViewMovedUp]; [payment setText:[paymentModeArray objectAtIndex:0]]; [self.view insertSubview:paymentMethodPickupView aboveSubview:self.view]; return NO; } else if(textField == state) { [self ClearSubviews]; [self setViewMovedUp]; [state setText:[stateArray objectAtIndex:0]]; [self.view insertSubview:statePickupView aboveSubview:self.view]; return NO; } else if(textField == expirydate) { [self setViewMovedUp]; expiryDatePickup.date = [NSDate date]; NSDate *date1 = [NSDate date]; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateStyle:NSDateFormatterMediumStyle]; NSString *strDate=[dateFormatter stringFromDate:date1]; NSString *str=[[NSString alloc] initWithString: strDate]; [expirydate setText:str]; [self.view insertSubview:expiryDatePickupView aboveSubview:self.view]; return NO; } else if(textField == creditCard) { [self ClearSubviews]; [self setViewMovedUp]; return YES; } else { [self ClearSubviews]; return YES; } } -(BOOL)textFieldShouldEndEditing:(UITextField *)textField { return YES; } (void)textFieldDidEndEditing:(UITextField *)textField { if(textField == creditCard) { [self moveDown]; } } (BOOL)textFieldShouldReturn:(UITextField *)textField { [firstName resignFirstResponder]; [lastName resignFirstResponder]; [email resignFirstResponder]; [address1 resignFirstResponder]; [address2 resignFirstResponder]; [city resignFirstResponder]; [creditCard resignFirstResponder]; return YES; } -(IBAction)textFieldDoneEditing:(id)sender { [sender resignFirstResponder]; } ////////----------------------------------------------------------------------- pragma mark move screen (void)setViewMovedUp { [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:0.3]; // Make changes to the view's frame inside the animation block. They will be animated instead // of taking place immediately. CGRect rect = [self.view frame]; // If moving up, not only decrease the origin but increase the height so the view // covers the entire screen behind the keyboard. rect.origin.y -= 50.0f; rect.size.height -= 80.0f; [self.view setFrame:rect]; [UIView commitAnimations]; } -(void)moveDown { [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:0.3]; // Make changes to the view's frame inside the animation block. They will be animated instead // of taking place immediately. CGRect rect = [self.view frame]; rect.origin.y += 50.0f; rect.size.height += 80.0f; [self.view setFrame:rect]; // [UIView setBackgroundColor:[UIColor darkGrayColor]]; [UIView commitAnimations]; } pragma mark Method to show pickers -(void)showPicker:(UITextField *)textField { if(textField == expirydate) { expiryDatePickup .date = [NSDate date]; NSDate *date1 = [NSDate date]; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateStyle:NSDateFormatterMediumStyle]; NSString *strDate=[dateFormatter stringFromDate:date1]; NSString *str=[[NSString alloc] initWithString: strDate]; [expirydate setText:str]; [self.view insertSubview:expiryDatePickup aboveSubview:self.view]; } else if(textField == payment) { [payment setText:[paymentModeArray objectAtIndex:0]]; [self.view insertSubview:paymentMethodPickupView aboveSubview:self.view]; } else if(textField == state) { [state setText:[stateArray objectAtIndex:0]]; [self.view insertSubview:statePickupView aboveSubview:self.view]; } } (IBAction)datePickerChanged:(id)sender { NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateStyle:NSDateFormatterMediumStyle]; NSDate *date=expiryDatePickup.date; formattedDateString1 = [dateFormatter stringFromDate:date]; [expirydate setText:formattedDateString1]; NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; unsigned int unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit; components = [gregorian components:unitFlags fromDate:date]; [gregorian release]; } pragma mark done and cancel methods -(IBAction) btnCancelExpiryDate:(id)sender { [self moveDown]; [expirydate setText:@" "]; [expiryDatePickupView removeFromSuperview]; } -(IBAction) btnDoneExpiryDate:(id)sender { [self moveDown]; [expiryDatePickupView removeFromSuperview]; expiryDatePickup .date = [NSDate date]; } -(IBAction)cancelPaymentType:(id)sender { [self moveDown]; [payment setText:@" "]; [paymentMethodPickupView removeFromSuperview]; } -(IBAction)donePaymentType:(id)sender { [self moveDown]; [paymentMethodPickupView removeFromSuperview]; } -(IBAction)doneState:(id)sender { [self moveDown]; [statePickupView removeFromSuperview]; } (IBAction)cancelState:(id)sender; { [self moveDown]; [state setText:@" "]; [statePickupView removeFromSuperview]; }

    Read the article

  • unrecognized selector sent to instance while trying to add an object to a mutable array

    - by madpoet
    I'm following the "Your Second iOS App" and I decided to play with the code to understand Objective C well... What I'm trying to do is simply adding an object to a mutable array in a class. Here are the classes: BirdSighting.h #import <Foundation/Foundation.h> @interface BirdSighting : NSObject @property (nonatomic, copy) NSString *name; @property (nonatomic, copy) NSString *location; @property (nonatomic, copy) NSDate *date; -(id) initWithName: (NSString *) name location:(NSString *) location date:(NSDate *) date; @end BirdSighting.m #import "BirdSighting.h" @implementation BirdSighting -(id) initWithName:(NSString *)name location:(NSString *)location date:(NSDate *)date { self = [super init]; if(self) { _name = name; _location = location; _date = date; return self; } return nil; } @end BirdSightingDataController.h #import <Foundation/Foundation.h> @class BirdSighting; @interface BirdSightingDataController : NSObject @property (nonatomic, copy) NSMutableArray *masterBirdSightingList; - (NSUInteger) countOfList; - (BirdSighting *) objectInListAtIndex: (NSUInteger) theIndex; - (void) addBirdSightingWithSighting: (BirdSighting *) sighting; @end BirdSightingDataController.m #import "BirdSightingDataController.h" @implementation BirdSightingDataController - (id) init { if(self = [super init]) { NSMutableArray *sightingList = [[NSMutableArray alloc] init]; self.masterBirdSightingList = sightingList; return self; } return nil; } -(NSUInteger) countOfList { return [self.masterBirdSightingList count]; } - (BirdSighting *) objectInListAtIndex: (NSUInteger) theIndex { return [self.masterBirdSightingList objectAtIndex:theIndex]; } - (void) addBirdSightingWithSighting: (BirdSighting *) sighting { [self.masterBirdSightingList addObject:sighting]; } @end And this is where I'm trying to add a BirdSighting instance to the mutable array: #import "BirdsMasterViewController.h" #import "BirdsDetailViewController.h" #import "BirdSightingDataController.h" #import "BirdSighting.h" @implementation BirdsMasterViewController - (void)awakeFromNib { [super awakeFromNib]; BirdSightingDataController *dataController = [[BirdSightingDataController alloc] init]; NSDate *date = [NSDate date]; BirdSighting *sighting = [[[BirdSighting alloc] init] initWithName:@"Ebabil" location:@"Ankara" date: date]; [dataController addBirdSightingWithSighting: sighting]; NSLog(@"dataController: %@", dataController.masterBirdSightingList); self.dataController = dataController; } .......... @end It throws NSInvalidArgumentException in BirdSightingDataController addBirdSightingWithSighting method... What am I doing wrong?

    Read the article

  • Date from String using NSDateFormatter regardless 12h-24h setting

    - by maxf99
    Hello everybody, Today my question is about date formats and strings. My application downloads some strings representing dates from the internet. The date format is always like this: "2010-05-24 at 20:45" I need to convert this string into an NSDate object in order to perform some date manipulations. I tried this code: NSString * dateString = @"2010-05-24 at 20:45" // actually downloaded from the internet NSDateFormatter * myDateFormatter = [[NSDateFormatter alloc] init]; [myDateFormatter setDateFormat:@"yyyy-MM-dd 'at' HH:mm"]; NSDate * dateFromString = [myDateFormatter dateFromString:dateString]; This seems to work perfectly fine as long as the iPhone is set to 24h clock. As long as I switch to 12h clock in the general settings the NSDate object is not created (and the application happily crashes) I have read others having similar problems but I don't seem to find a solution. Now the questions: It doesn't make sense to me that the NSDateFormatter is sensible to user settings as long as I am specifying which format it is supposed to use to parse the string (which is not modifiable because it comes from the web), what's the use of checking user settings? More important, how can I get my task performed (to get an NSDate object from the string regardless the user settings)?

    Read the article

  • Displaying timecode using NSTimer and NSDateFormatter

    - by Chris B
    Hi. I am very close to completing my first iphone app and it has been a joy. I am trying to add running timecode using the current time via an NSTimer displaying the current time (NSDate) on a UILabel. NSDate is working fine for me, showing hour, minute, second, milliseconds. But instead of milliseconds, I need to show 24 frames per second. The problem is that I need the frames per second to be synced 100% with the hour, minute and second, so I can't add the frames in a separate timer. I tried that and had it working but the frame timer was not running in sync with the date timer. Can anyone help me out with this? Is there a way to customize NSDateFormatter so that I can have a date timer formatted with 24 frames per second? Right now I'm limited to formatting just hours, minutes, seconds, and milliseconds. Here's the code I'm using right now -(void)runTimer { // This starts the timer which fires the displayCount method every 0.01 seconds runTimer = [NSTimer scheduledTimerWithTimeInterval: .01 target: self selector: @selector(displayCount) userInfo: nil repeats: YES]; } //This formats the timer using the current date and sets text on UILabels - (void)displayCount; { NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease]; NSDate *date = [NSDate date]; // This will produce a time that looks like "12:15:07:75" using 4 separate labels // I could also have this on just one label but for now they are separated // This sets the Hour Label and formats it in hours [formatter setDateFormat:@"HH"]; [timecodeHourLabel setText:[formatter stringFromDate:date]]; // This sets the Minute Label and formats it in minutes [formatter setDateFormat:@"mm"]; [timecodeMinuteLabel setText:[formatter stringFromDate:date]]; // This sets the Second Label and formats it in seconds [formatter setDateFormat:@"ss"]; [timecodeSecondLabel setText:[formatter stringFromDate:date]]; //This sets the Frame Label and formats it in milliseconds //I need this to be 24 frames per second [formatter setDateFormat:@"SS"]; [timecodeFrameLabel setText:[formatter stringFromDate:date]]; }

    Read the article

  • Return a Const Char* by reading an @property NSString in separate class

    - by Andrew
    I'm probably being an idiot here, but I cannot for the life of me find the answer that I'm looking for. I have an array of CalEvents returned from a CalendarStore query, and for other reasons I am finding the first location of any upcoming event for today that is not an all-day or multi-day event. +(const char*) suggestFirstiCalLocation{ CalCalendarStore *store = [CalCalendarStore defaultCalendarStore]; NSPredicate *allEventsPredicate = [CalCalendarStore eventPredicateWithStartDate:[NSDate date] endDate:[[NSDate date] initWithTimeIntervalSinceNow:3600] calendars:[store calendars]]; NSArray *currentEventCalendarArray = [store eventsWithPredicate:allEventsPredicate]; for (int i = 0; i< [currentEventCalendarArray count]; i++){ if (![[currentEventCalendarArray objectAtIndex:i] isAllDay]){ //Now that other events are cleared, check for multi-day NSDate *startOnDate = [[currentEventCalendarArray objectAtIndex:i] startDate]; NSDate *endOnDate = [[currentEventCalendarArray objectAtIndex:i] endDate]; if ([endOnDate timeIntervalSinceDate:startOnDate ] < 86400.0){ NSString * iCalLocation = [[currentEventCalendarArray objectAtIndex:i] location]; return [iCalLocation UTF8String]; } } } return ""; } For other reasons, I am returning a const char with the value of the location that is found. However, I cannot seem to return "iCalLocation" at all. The compiler fails on the line where I am initializing the "iCalLocation" variable: "Cannot convert to pointer type" Being frank: I am new to Objective-C, and I am still trying to figure points, properties, and such out.

    Read the article

  • Asynchronous URL connection objective C

    - by tweety
    I created an asynchronous URL connection to call a web service using HTTP POST method. after I am pinging the web i set an NSTimerInterval in the completion handler. my problem is when I'm trying to display the time on the view controller it is not doing promptly. I know block is stored in the heap and gets executed later on anytime and probably that's why i'm not getting prompt answer. I was wondering is there any other way to do this? Thanks in advance. my code: __block NSDate *start= [NSDate date]; __block NSDate *end; __block double miliseconds; __block NSTimeInterval time; [NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { if([data length]==0 && error==nil){ end=[NSDate date]; time=[end timeIntervalSinceDate:start]; NSLog(@"Successfully Pinged"); miliseconds = time; // calling a method to display ping time [self label:miliseconds]; } -(void) label:(double) mili{ double miliseconds=mili*1000; self.timeDisplay.text=[NSString stringWithFormat:@"Time: %.3f ms", miliseconds];

    Read the article

  • Incorrect value for sum of two NSIntegers

    - by Antonio
    Hi everybody: I'm sure I'm missing something and the answer is very simple, but I can't seem to understand why this is happening. I'm trying to make an average of dates: NSInteger runningSum =0; NSInteger count=0; for (EventoData *event in self.events) { NSDate *dateFromString = [[NSDate alloc] init]; if (event.date != nil) { dateFromString = [dateFormatter dateFromString:event.date]; runningSum += (NSInteger)[dateFromString timeIntervalSince1970]; count += 1; } } if (count>0) { NSLog(@"average is: %@",[NSDate dateWithTimeIntervalSince1970:(NSInteger)((CGFloat)runningAverage/count)]); } Everything seems to work OK, except for runningSum += (NSInteger)[dateFromString timeIntervalSince1970], which gives an incorrect result. If I put a breakpoint when taking the average of two equal dates (2009-10-10, for example, which is a timeInterval of 1255125600), runningSum is -1784716096, instead of the expected 2510251200. I've tried using NSNumber and I get the same result. Can anybody point me in the right direction? Thanks! Antonio

    Read the article

  • Problem in dateFormatter in Iphone sdk?

    - by user133611
    Hi Guys, Actually My code is: else if(isExpense == YES) { NSDate *strDate; strDate = [NSDate date]; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; [dateFormatter setDateFormat:@"dd-MM-yyyy"]; if([expense.date length] > 0) { NSDate *date = [dateFormatter dateFromString:expense.date]; datePicker.date = date; //Here date value is passing nil and Im getting Exception } else { datePicker.date = strDate; } } Guys can anyone help to get out of this problem????? Anyone's help will be much appreciated. Thank You, Kiran.

    Read the article

  • UIDatePicker hours are disabled

    - by user112175
    I have a UIDatePicker object and I am setting it up as follows but for some reason my hours field is disabled on the current date but minutes are not. Not exactly sure what I am missing, any help would be appreciated. UIDatePicker *picker = [[UIDatePicker alloc] init]; picker.date = [NSDate dateWithTimeIntervalSinceNow:DATE_MIN_SECONDS_OFFSET]; picker.minimumDate = [NSDate dateWithTimeIntervalSinceNow:DATE_MIN_SECONDS_OFFSET]; This is what My datepicker looks like http://img.skitch.com/20100417-d75gq78pjwjb9d37ku9msmcduc.png

    Read the article

  • NSDateFormatter problem

    - by jeeva
    I am trying to get NSDate from string but its returning nil. I tried this: NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"yyyy-mm-dd'T'HH:mm:ss'Z'"]; NSDate *date = [dateFormatter dateFromString:@"2010-05-07T10:12:32UTC"]; NSLog(@"Success date=%@",[date description]); Thanks

    Read the article

  • How do those bitmasks actually work?

    - by mystify
    For example, this method from NSCalendar takes a bitmask: - (NSDate *)dateByAddingComponents:(NSDateComponents *)comps toDate:(NSDate *)date options:(NSUInteger)opts So options can be like: NSUInteger options = kCFCalendarUnitYear; or like: NSUInteger options = kCFCalendarUnitYear | kCFCalendarUnitMonth | kCFCalendarUnitDay; What I don't get is, how is this actually done? I mean: How can they pull out those values which are merged into options? If I wanted to program something like this, that can take a bitmask, how would that look?

    Read the article

  • How do I add a custom view to iPhone app's UI?

    - by Dr Dork
    I'm diving into iPad development and I'm still learning how everything works together. I understand how to add standard view (i.e. buttons, tableviews, datepicker, etc.) to my UI using both Xcode and Interface Builder, but now I'm trying to add a custom calendar control (TapkuLibrary) to the left window in my UISplitView application. My question is, if I have a custom view (in this case, the TKCalendarMonthView), how do I programmatically add it to one of the views in my UI (in this case, the RootViewController)? Below are some relevant code snippets from my project... RootViewController interface @interface RootViewController : UITableViewController <NSFetchedResultsControllerDelegate> { DetailViewController *detailViewController; NSFetchedResultsController *fetchedResultsController; NSManagedObjectContext *managedObjectContext; } @property (nonatomic, retain) IBOutlet DetailViewController *detailViewController; @property (nonatomic, retain) NSFetchedResultsController *fetchedResultsController; @property (nonatomic, retain) NSManagedObjectContext *managedObjectContext; - (void)insertNewObject:(id)sender; TKCalendarMonthView interface @class TKMonthGridView,TKCalendarDayView; @protocol TKCalendarMonthViewDelegate, TKCalendarMonthViewDataSource; @interface TKCalendarMonthView : UIView { id <TKCalendarMonthViewDelegate> delegate; id <TKCalendarMonthViewDataSource> dataSource; NSDate *currentMonth; NSDate *selectedMonth; NSMutableArray *deck; UIButton *left; NSString *monthYear; UIButton *right; UIImageView *shadow; UIScrollView *scrollView; } @property (readonly,nonatomic) NSString *monthYear; @property (readonly,nonatomic) NSDate *monthDate; @property (assign,nonatomic) id <TKCalendarMonthViewDataSource> dataSource; @property (assign,nonatomic) id <TKCalendarMonthViewDelegate> delegate; - (id) init; - (void) reload; - (void) selectDate:(NSDate *)date; Thanks in advance for all your help! I still have a ton to learn, so I apologize if the question is absurd in any way. I'm going to continue researching this question right now!

    Read the article

  • UIDatePicker Not storing time in core data

    - by Derek
    Hi, I am using a UIDatepicker with only "Time", I save the time in a NSDate object type, however when I try to store the Object in core data I get an error saying its not a NSDate type... *tt = [pickerTime date]; [myObject setValue:tt forKey:@"time"]; Thanks,

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10  | Next Page >