sorting - iOS coredata sort descriptor using part of a date? -
in app, have table view shows person's activities on time. want sort data day, first name. problem is, need store nsdate time included other reasons.
right now, have this:
august 18, 2014 11:02 bill b. august 18, 2014 10:20 john d. august 18, 2014 10:05 adam s. august 11, 2014 3:47 pm debbie b. august 11, 2014 2:13 pm adam s.
i sort ignore time , evaluate date. this:
august 18, 2014 adam s. august 18, 2014 bill b. august 18, 2014 john d. august 11, 2014 adam s. august 11, 2014 debbie b.
is possible construct sort descriptor looks @ month, day & year of core data date attribute?
i use additional attribute sortdate
. calculate attribute in setter of startdate
(or call date attribute) of object. that's fastest way if store more few objects in core data. use transient property , calculate value in getter, has quite impact on performance.
i use in 1 of apps:
- (void)setstartdate:(nsdate *)startdate { [self willchangevalueforkey:@"startdate"]; [self setprimitivestartdate:startdate]; [self didchangevalueforkey:@"startdate"]; if (startdate) { nscalendar *calendar = [[nscalendar alloc] initwithcalendaridentifier:nsgregoriancalendar]; // might want save sortdate in utc // calendar.timezone = [nstimezone timezoneforsecondsfromgmt:0]; nsdate *sortdate; if ([calendar rangeofunit:nsdaycalendarunit startdate:&sortdate interval:null fordate:startdate]) { self.sortdate = sortdate; } else { nslog(@"can't create sort date date %@", startdate); } } else { self.sortdate = nil; } }
the fetchrequest use sortdate
, startdate
sorting , sortdate
sectioning.
nsfetchrequest *request = [nsfetchrequest fetchrequestwithentityname:@"myentity"]; nssortdescriptor *sdsortdate = [nssortdescriptor sortdescriptorwithkey:@"sortdate" ascending:no]; nssortdescriptor *sdstartdate = [nssortdescriptor sortdescriptorwithkey:@"startdate" ascending:no]; request.sortdescriptors = @[sdsortdate, sdstartdate]; nsfetchedresultscontroller *frc = [[nsfetchedresultscontroller alloc] initwithfetchrequest:request managedobjectcontext:self.managedobjectcontext sectionnamekeypath:@"sortdate" cachename:@"myfancyviewcontrollercache"];
Comments
Post a Comment