Reputation: 261
What I trying to do is pretty simple.
However every time I am getting an empty array. FYI I am also checking is the record actually got saved or not, and even if it saved the result is empty set.
Method to Save the Record and Store Date as Interval
RequestInfo * newEntry = [NSEntityDescription insertNewObjectForEntityForName:@"RequestInfo"inManagedObjectContext:self.managedObjectContext];
newEntry.jukeboxPhoneNo = request.L;
newEntry.trackName = request.TN;
newEntry.trackNo = request.T;
newEntry.date = [NSDate date];
NSTimeInterval lastID = [newEntry.date timeIntervalSince1970];
NSUserDefaults* prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:[NSString stringWithFormat:@"%f", lastID] forKey:LAST_REQUEST_ID_KEY];
[prefs synchronize];
if (![self.managedObjectContext save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}
else {
NSLog(@"Object is saved");
}
Method to Retrive the Record
NSUserDefaults* prefs = [NSUserDefaults standardUserDefaults];
NSString* lastDateInterval = (NSString*)[prefs objectForKey:LAST_REQUEST_ID_KEY];
NSTimeInterval lastID = [lastDateInterval doubleValue];
NSLog(@"Last ID %f", lastID);
// Check it
if(lastID!=0) {
NSDate* soughtDate =[[NSDate alloc] initWithTimeIntervalSince1970:lastID];
NSEntityDescription *productEntity=[NSEntityDescription entityForName:@"RequestInfo" inManagedObjectContext:self.managedObjectContext];
NSFetchRequest *fetch=[[NSFetchRequest alloc] init];
[fetch setEntity:productEntity];
NSPredicate *p= [NSPredicate predicateWithFormat:@"(date >=%@) AND (date <= %@)", soughtDate, soughtDate];
[fetch setPredicate:p];
NSError *fetchError;
NSArray *fetchedProducts = [self.managedObjectContext executeFetchRequest:fetch error:&fetchError];
RequestInfo* request = [fetchedProducts objectAtIndex:0];
I have tried == to in the predicate but it didn't worked. It is returning me an empty array every time. I am started programming in the objective-c pretty recently so I could have made a silly mistake too.
Upvotes: 0
Views: 375
Reputation: 261
Better way to do this to have one more column and give it unique id using the variable and store this in user preferences. I found it pretty simple and useful.
Upvotes: 0
Reputation: 8988
Save the newEntry.objectID in user preferences and then get the ManagedObject using the objectID. That's definitely going to be a unique key for the entry.
Upvotes: 1