Triz
Triz

Reputation: 767

Trouble with Core Data dates

I've got a Core Data model set up, with two entities in a one-to-many relationship (Items, and for each item, there can be multiple ResetDates). I'm pretty confident the model is set up correctly.

I can add new Items, and when doing so, add a new ResetDate (using the current date, with [NSDate date]). I can retrieve and display Items. What I'm having trouble with is retrieving and displaying the ResetDates.

Updated: It works now, thanks very much to the answerers below. Here's the code in question:

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"resetDate" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:&sortDescriptor count:1];

NSMutableArray *sortedResets = [[NSMutableArray alloc] initWithArray:[item.resets allObjects]];
[sortedResets sortUsingDescriptors:sortDescriptors];

NSDate *oldDate = [[sortedResets lastObject] resetDate];
if ( !oldDate ) {
    oldDate = [NSDate date];
}

NSInteger numberOfDays = [self timeIntervalWithStartDate:oldDate withEndDate:currentDate];  // This function works fine, when given two NSDate objects

daysSinceLabel.text = [NSString stringWithFormat:@"%d days", numberOfDays];

Upvotes: 0

Views: 1964

Answers (2)

Brian
Brian

Reputation: 56

First, NSArray -objectAtIndex: is not returning nil if you pass it an index that is out of the bounds, it will raise an NSRangeException, when you're not sure about the index, and need to use -objectAtIndex:, you have to call the -count method before to check.

More importantly, an NSArray can't contain a nil value, as nil is not an object.

Then, no, it's not an NSDate object, when you ask item for it's resets relationship (item.resets), you get an NSSet that contain Reset managed objects in return, not NSDate objects, what you want is the resetDate attribute of the returned Reset managed objects, maybe something like this :

// NSArray -lastObject method return nil if the array is empty
// Sending messages to nil is Ok there, so we can call resetDate directly

NSDate *oldDate = [[sortedResets lastObject] resetDate];
if ( !oldDate ) {
    oldDate = [NSDate date];
}

Hope that help, and that my English is understandable...

Upvotes: 3

Brian
Brian

Reputation: 56

Maybe replacing :

NSDate *oldDate = sortedResets[0];

with :

NSDate *oldDate = [sortedResets objectAtIndex:0];

will help. sortedResets is an NSArray object, not a C array ;)

Upvotes: 1

Related Questions