memyselfandmyiphone
memyselfandmyiphone

Reputation: 1110

Retrieving NSDate from Core Data

I am attempting to retrieve the latest NSdate entry from core data. The way I am attempting to do so is to sort by date and get the objectAtIndex. I am however struggling to retrieve the result and am getting it returned as nil. I presuming my issue is around NSDate *obj = [results objectAtIndex:0]; though I am not sure how to fix it. Any suggestions will be welcomed. I could be well off the mark so excuse me if I am.

- (void)viewDidLoad
{
    [super viewDidLoad];
    //Get Reference to App Delegate
    SSAppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
    NSManagedObjectContext *context = [appDelegate managedObjectContext];
    //Fetch Entity
    NSFetchRequest *request = [[NSFetchRequest alloc]
                              initWithEntityName:@"RecentDetails"];
    //Sort By Date
    NSSortDescriptor *sort = [[NSSortDescriptor alloc]initWithKey:@"date" ascending:NO];
    [request setSortDescriptors:[NSArray arrayWithObject:sort]];
    //Store In Array
     NSArray *results = [context executeFetchRequest:request error:NULL];

/////////////NEEDS EXTRA HERE ACCORDING TO COMMENTS


    //Find Object at Index 0
    NSDate *obj = [results objectAtIndex:0];
    //Set Batch Size
    [request setFetchBatchSize:1];

    //NSDate Formatter
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"ddMMyyyy"];

    //Convert to string
    NSString *stringFromDate = [dateFormatter stringFromDate:obj];

    //Test Log
    NSLog(@"Latest Date! %@", stringFromDate);

}

Upvotes: 0

Views: 685

Answers (1)

Arseniy
Arseniy

Reputation: 304

  • When inserting, change:

    NSManagedObjectContext *recentDetails = [NSEntityDescription insertNewObjectForEntityForName:@"RecentDetails"inManagedObjectContext:context];
    

    to:

    NSManagedObject *recentDetails = [NSEntityDescription insertNewObjectForEntityForName:@"RecentDetails"inManagedObjectContext:context];`
    
  • When retrieving, like pointed out by Stakenborg, you should be getting your date property from an entity object of "RecentDetails".

  • [request setFetchBatchSize:1] should be set prior to [context executeFetchRequest:request...], otherwise it has no effect on amount of RecentDetails objects fetched.

Upvotes: 1

Related Questions