使用NSFetchedResultsController进行排序



使用XCode 4.6、iOS6、CoreData、UITableViewController、NSFetchesResultsController

我想出了如何将以下日期输入NSDate变量:

todayDate
yesterdayDate
thisWeek
lastWeek
thisMonth
lastMonth
lastYear

现在,我想使用NSFetchedResultsController将数据放入基于上述变量中的数据的部分中。我想我将不得不做一些日期比较:

if ([date1 compare:date2] == NSOrderedDescending) {
NSLog(@"date1 is later than date2");        
} else if ([date1 compare:date2] == NSOrderedAscending) {
    NSLog(@"date1 is earlier than date2");
} else {
    NSLog(@"dates are the same");
}

有些用户可能没有某些部分因此,我需要帮助在以下方法中放入什么来确定基于fetchRequest的节数:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

我还需要知道如何将数据划分为numberOfRowsInSection:单元格,并将其显示为cellforRowAtIndexPath:单元格

一些代码示例会很好!谢谢

编辑

我还没有集成控制器,但下面是要获取的代码:

- (void) refreshTable {
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Meeting" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"lastmoddate" ascending:NO];
    NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor, nil];
    [fetchRequest setSortDescriptors:sortDescriptors];
    [self.managedObjectContext executeFetchRequest:fetchRequest onSuccess:^(NSArray *results) {
        [self.refreshControl endRefreshing];
        self.objects = results;
        [self.tableView reloadData];
    } onFailure:^(NSError *error) {
        [self.refreshControl endRefreshing];
        NSLog(@"An error %@, %@", error, [error userInfo]);
    }];

以下是我获取日期的方法:

   NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *components = [cal components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit ) fromDate:[[NSDate alloc] init]];
    [components setHour:-[components hour]];
    [components setMinute:-[components minute]];
    [components setSecond:-[components second]];
    NSDate *today = [cal dateByAddingComponents:components toDate:[[NSDate alloc] init] options:0]; //This variable should now be pointing at a date object that is the start of today (midnight);
    [components setHour:-24];
    [components setMinute:0];
    [components setSecond:0];
    NSDate *yesterday = [cal dateByAddingComponents:components toDate: today options:0];
    components = [cal components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:[[NSDate alloc] init]];
    [components setDay:([components day] - ([components weekday] - 1))];
    NSDate *thisWeek  = [cal dateFromComponents:components];
    [components setDay:([components day] - 7)];
    NSDate *lastWeek  = [cal dateFromComponents:components];
    [components setDay:([components day] - ([components day] -1))];
    NSDate *thisMonth = [cal dateFromComponents:components];
    [components setMonth:([components month] - 1)];
    NSDate *lastMonth = [cal dateFromComponents:components];

这就是我要做的。在该模型中创建一个核心数据模型和"用户"实体。我想你知道怎么做,但如果你不只是评论和解释。然后,只需像对待任何其他实体一样为您的实体创建一个自定义类,并为其提供lastmoddate NSDate属性,再加上我将添加一个creationDate属性,该属性将等于创建实体的确切日期和时间,这样您就可以将其用作每个UserEntity的标识符。对于要在UITableView中创建的每个部分,您还必须有一个单独的数组数组。当你向模型中添加一个用户实体时,设置属性,然后因为你说有些用户可能没有每个变量,所以把用户实体不需要的任何变量都设置为零。初始化数组时,只需将具有相应属性的用户实体添加到值中。最后,当您实现-(NSInteger)numberOfSectionsInTableView:(UITableView*)tableView时,您所要做的就是对数组进行计数。

以下是它应该是什么样子:

我将把代表每个用户的实体称为"UserEntity"(它的NSManagedObject类将具有相同的名称)。

以下代码位于您将用于创建和获取实体的任何类的中——它可能与您用于显示UITableView的类相同。

@interface Class : UITableViewController {
    NSManagedObjectContext *managedObjectContext;
    NSMutableArray *arrayOfArrays;
}
@property (retain, nonatomic) NSManagedObjectContext   *managedObjectContext;
@property (retain, nonatomic) NSMutableArray   *arrayOfArrays;

下面的代码在实现中,您将使用哪个类来创建和获取实体——它可能与您用于显示UITableView的类相同。

//用于将UserEntity添加到模型(核心数据数据库)并设置其属性

- (UserEntity *)addUserEntityToModel {
     UserEntity *myEnt = (UserEntity *)[NSEntityDescription insertNewObjectForEntityForName:@"UserEntity" inManagedObjectContext:self.managedObjectContext];
   myEnt.creationDate = [NSDate date];
   myEnt. lastmoddate = ...; //replace the '...' with however you get your date
   //add any other values to the appropriate attributes here, any attributes that do not //pertain to the UserEntity simply ignore - they are automatically set to default when they //are created.
    NSError *error = nil;
    if(!managedObjectContext) 
        NSLog(@"managedObejctContext problem at ...");
    else if (![managedObjectContext save:&error]) {
        NSLog(@"context not saved!");;
    } else 
    NSLog(@"context successfully saved.");      
}

//用于获取用户实体的

- (NSMutableArray *)getFetchArray {
        NSFetchRequest *request = [[NSFetchRequest alloc] init];
        if(!managedObjectContext) {
            NSLog(@"There is no managedObjectContext at getFetchArray");
        }
           NSEntityDescription *entity = [NSEntityDescription entityForName:@"UserEntity" inManagedObjectContext:managedObjectContext];
        [request setEntity:entity];
        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"creationDate" ascending:NO];
        NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
        [request setSortDescriptors:sortDescriptors];
        [sortDescriptors release];
        [sortDescriptor release];
        NSError *error = nil;
        NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
        if (mutableFetchResults == nil) {
            NSLog(@"mutableFetchResults array is nil");
        } 
        [request release];
        return mutableFetchResults;
    }

//设置阵列阵列

-(void)createArrayOfArrays {
 NSMutableArray *fetchArray = [self getFetchArray];
  NSMutableArray *todayDateArray = [[NSMutableArray alloc] init];
  NSMutableArray *yesterdayDateArray = [[NSMutableArray alloc] init];
  NSMutableArray *thisWeekArray = [[NSMutableArray alloc] init];
        //... create an array for each section you want
for (UserEntity *ue in fetchArray) {
       if(ue.lastmoddate) { //if the attribute is not nil
        if(ue.lastmoddate isEqual todayDate)
       [todayDateArray insertObject:ue atIndex:0];
     else if (ue.lastmoddate isEqual yesterdayDate)
       [yesterdayDateArray insertObject:ue atIndex:0];
        // ... do this for every section array 
        }
    }
 arrayOfArrays = [[NSMutableArray alloc] initWithObjects:todayDateArray,yesterdayDateArray,...(the rest of the arrays created for each attribute), nil]

  [todayDateArray release];
    [yesterdayDateArray release];
  //  ... release all the arrays except arrayOfArrays and fetchArray     
 }

//设置managedObjectContext

- (id)init {
    self = [super init];
    if (self) {
    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];//what ever //the name of your appDel is.
        NSManagedObjectContext *context = [appDelegate managedObjectContext];
        self.managedObjectContext = context;
       [self createArrayofArrays];//this first creates the arrayOfArrays and will set it //equal to anything that's saved in the database. If you add an entity you will need to update //it.
    }
    return self;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return arrayOfArrays.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [[arrayOfArrays objectAtIndex:section] count];
}

//然后在表格视图中显示单元格

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *CellIdentifier = @"Cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (!cell) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
        }

        UserEntity *ent = (UserEntity *)[[arrayOfArrays objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
        cell.accessoryType = UITableViewCellAccessoryBasic;
        if(ent.lastmoddate) { //if lastmoddate is not nil
        cell.textLabel.text = ent. lastmoddate;
        } else {
            NSLog(@"lastmoddate is nil at tableView: cellForRowAtIndexPath");
        }
        NSLog(@"tableView: cellForRowAtIndexPath called.");
        return cell;
    }

相关内容

  • 没有找到相关文章