在CoreData中保存多个选定的单元格

时间:2013-12-21 05:17:37

标签: uitableview core-data

因此,在应用程序中,我正在处理一个事件ViewController,它要求用户在事件中选择有记录的人。我正在努力实现它。我的代码如下。

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.devices.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [scoutsSelectedTableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    NSManagedObject *device = [self.devices objectAtIndex:indexPath.row];
    [cell.textLabel setText:[NSString stringWithFormat:@"%@", [device valueForKey:@"name"]]];
    if([arSelectedRows containsObject:indexPath]) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [scoutsSelectedTableView cellForRowAtIndexPath:indexPath];

    //[cell setAccessoryType:UITableViewCellAccessoryCheckmark];

    if (cell.accessoryType == UITableViewCellAccessoryNone) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        [arSelectedRows addObject:indexPath];
    }
    else {
        cell.accessoryType = UITableViewCellAccessoryNone;
        [arSelectedRows removeObject:indexPath];
    }

    [scoutsSelectedTableView deselectRowAtIndexPath:indexPath animated:YES];
}

-(NSArray *)getSelections {
    NSMutableArray *selections = [[NSMutableArray alloc] init];
    for(NSIndexPath *indexPath in arSelectedRows) {
        [selections addObject:[self.devices objectAtIndex:indexPath.row]];
    }

    return selections;
}

RootViewController的

- (NSManagedObjectContext *)managedObjectContext
{
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if ([delegate performSelector:@selector(managedObjectContext)]) {
    context = [delegate managedObjectContext];
}
return context;
}

- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
    // Custom initialization
}
return self;
}

- (void)viewDidLoad
{
[super viewDidLoad];

}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];

// Fetch the devices from persistent data store
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Event"];
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"SelectingScouts"];
self.devices = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
self.scout = [[managedObjectContext executeFetchRequest:request error:nil] mutableCopy];

[self.tableView reloadData];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return self.devices.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

// Configure the cell...
NSManagedObject *device = [self.devices objectAtIndex:indexPath.row];
NSManagedObject *scoutDevice = [self.scout objectAtIndex:indexPath.row];
[cell.textLabel setText:[NSString stringWithFormat:@"%@", [device valueForKey:@"eventname"]]];
[cell.detailTextLabel setText:[NSString stringWithFormat:@"Scouts: %@", [scoutDevice valueForKey:@"scoutNames"]]];

return cell;
}



- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}


- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath

{
NSManagedObjectContext *context = [self managedObjectContext];
if (editingStyle == UITableViewCellEditingStyleDelete) {
withRowAnimation:UITableViewRowAnimationFade];
    [context deleteObject:[self.devices objectAtIndex:indexPath.row]];
    NSError *error = nil;
    if (![context save:&error]) {
        NSLog(@"Can't Delete! %@ %@", error, [error localizedDescription]);
        UIAlertView *error = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Draft Journal can not delete this event at this time. Please try again later." delegate:self cancelButtonTitle:@"Okay" otherButtonTitles:nil, nil];
        [error show];
        return;
    }
    [self.devices removeObjectAtIndex:indexPath.row];
    [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

}   

}



- (IBAction)done:(id)sender {
[self dismissViewControllerAnimated:YES completion:nil];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:@"UpdateDevice"]) {
    NSManagedObject *selectedDevice = [self.devices objectAtIndex:[[self.tableView indexPathForSelectedRow] row]];
    NewEventTwoViewController *destViewController = segue.destinationViewController;
    destViewController.device = selectedDevice;
}
}

希望这有助于让我知道我是否可以添加任何内容。

修改

正在发生的问题是,当我按下一行时,它显示我已按下并且所有代码都在该ViewController上工作但是当我在RootViewController上按“Save”时显示Scouts: (null)

2 个答案:

答案 0 :(得分:1)

您如何填充您正在使用的这些阵列?

你确定他们正在填充吗?

您是否设置了断点,以查看您已实施的每个UITableViewDataSource方法返回的内容?

  

当用户有机会在活动中选择人员时,将填充TableViewCell。当用户按下保存时,数据不会传输到Root View Controller并给我NULL

下一个问题:您的arSelectedRows iVar是否在任何地方初始化?它没有显示在您提供的代码示例中。

按下保存时,如何传递arSelectedRows的值?

  

我正在实现MutableArrays。

@interface NewEventViewController : UIViewController <UITableViewDataSource, UITableViewDelegate> { 
  NSMutableArray *arOptions; 
  NSMutableArray *arSelectedRows; 
} 
@property (strong, nonatomic) NSMutableArray *devices; 
@property (strong, nonatomic) NSMutableArray *scoutsArray;

这是iVar的定义,但你如何初始化 arSelectedRows数组?如果您没有对其进行初始化,那么它将为nil,您对[{1}}的调用将针对-addObject:进行调用,并且不执行任何操作。

答案 1 :(得分:0)

您的RootController tableView数据源是您从CoreData查询的数据,而不是用户从EventController中选择的数据。因此您无法看到更改。您可以在用户选择单元格时保存实体的选择状态。并更改获取请求以查看更改。

修改

  1. 我假设你有一个名为Device的实体,为它添加一个新属性:

     @property (nonatomic, strong) NSNumber *selected;
     @dynamic selected;
    
  2. 在用户选择单元格时设置实体:

    Device *device = [self.devices objectAtIndex:indexPath.row];
    if (cell.accessoryType == UITableViewCellAccessoryNone) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        device.selected = @(YES);
        [arSelectedRows addObject:indexPath];
    }
    else {
         cell.accessoryType = UITableViewCellAccessoryNone;
        device.selected = @(NO);
        [arSelectedRows removeObject:indexPath];
    } 
    
  3. 更改您的获取请求以获取所选对象

    NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Event"];
    fetchRequest.predicate = [NSPredicate predicateWithFormat:@"selected == 1"];
    self.devices = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
    
  4. 我不确定你发布的代码你真正想要的是什么,但我认为如果我想分离实体的选定状态,我会这样做。

    希望这会对你有所帮助。