iphone - 获取属于父对象的子对象并将它们放入 tableView 中(核心数据、关系)

标签 iphone ios objective-c uitableview core-data

我有两个tableView,主要的一个添加了父对象,当您单击tableView中的父对象时,它会将您带到子tableView,我成功地完成了第一部分,但是当涉及到获取“正确的”子对象我很困惑,我这样做的方法是获取所有子对象,使用枚举选择正确的子对象然后放入 NSSet 中,但这不起作用,这是子对象 TableView .m:

 #import "MinorGoalsTableViewController.h"

 @interface MinorGoalsTableViewController ()

 @end

 @implementation MinorGoalsTableViewController
 @synthesize selectedGoal = _selectedGoal;
 @synthesize fetchedResultsController = _fetchedResultsController;
 @synthesize minorGoalsSet;

 // init with goal (for GTVC)
 - (id) initWithGoal:(Goal *)goal {
if (self = [super init]) {

    _selectedGoal = goal;

}

return self;
 }

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

 - (void)viewDidLoad
 {
[super viewDidLoad];
NSError *error = nil;

// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;

// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;




NSLog(@"Minor Goals in %@ are: %lu", self.selectedGoal.title , (unsigned long)[self.selectedGoal.minorGoal count]);


 //    self.minorGoalsSet = nil;

// initializing minorGoalsSet
self.minorGoalsSet = [[NSMutableSet alloc] init];

// performing fetch
if (![self.fetchedResultsController performFetch:&error]) {
    NSLog(@"Error fetching all minor goals: %@", error);
    abort();
}


// creating NSSet that will carry all selectedGoal minor goals
NSSet *minorGoals = self.selectedGoal.minorGoal;


// creating a loop to add minor goals in minorGoalsSet
// add existing minor goals in selected goal to minorGoalsSet
for (MinorGoal *minor in minorGoals) {
    [minorGoalsSet addObject:minor];
}

NSLog(@"minor goals in set: %lu", (unsigned long) [minorGoalsSet count]);
NSLog(@"minor goals in set2: %lu", (unsigned long) [minorGoals count]);

// setting nav title to selected goal title
self.navigationItem.title = _selectedGoal.title;

// adding "add" button to nav
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addNewMinorGoal)];


 }

 - (void) viewWillDisappear:(BOOL)animated {
self.selectedGoal = nil;
 }


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

pragma mark - 表格 View 数据源

   - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  {
return [self.selectedGoal.minorGoal count];
//    id <NSFetchedResultsSectionInfo> secInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
//    return [secInfo numberOfObjects];
  }

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

cell.accessoryType = UITableViewCellAccessoryNone;

// Configure the cell...
MinorGoal *minor = [self.fetchedResultsController objectAtIndexPath:indexPath];

// well see about that later
if ([minorGoalsSet containsObject:minor]) {
    cell.textLabel.text = minor.title;
}

// setting cell's title to minor goal's title
 //    cell.textLabel.text = minor.title;

return cell;
 }

pragma mark - 获取结果 Controller 方法

 - (NSFetchedResultsController*) fetchedResultsController {
if (_fetchedResultsController != nil) {
    return _fetchedResultsController;
}

// creating fetch request
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
     NSEntityDescription *entity = [NSEntityDescription entityForName:@"MinorGoal"
                                             inManagedObjectContext:self.selectedGoal.managedObjectContext];
[fetchRequest setEntity:entity];

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"title"
                                                               ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];


// setting _fetchedResultsController
   _fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.selectedGoal.managedObjectContext sectionNameKeyPath:nil cacheName:nil];

// performing fetch
NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error]) {
    NSLog(@"Error fetching minors: %@", error);
}

// returning
return _fetchedResultsController;

    }

pragma mark - TableView 委托(delegate)

   - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
 {

 }

 - (void) addNewMinorGoal {

// code to show UIAlertView that will add new minor goal
// creating UIAlertView
    UIAlertView *addMinorGoalAlert = [[UIAlertView alloc] initWithTitle:@"Add Minor Goal" message:@"Minor Goal Title" delegate:self cancelButtonTitle:@"Cancel"      otherButtonTitles:@"Save", nil];

// Adding plain textfield for minor goal title
addMinorGoalAlert.alertViewStyle = UIAlertViewStylePlainTextInput;

// showing UIAlertView
[addMinorGoalAlert show];
}

pragma mark - UIAlertView 用于添加新的次要委派

  - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {



      if (buttonIndex == 0) {
          NSLog(@"Adding Minor Goal Canceled!");
     }

      else

     {



    // creating string will carry textField value
    NSString *minorTitle = [[alertView textFieldAtIndex:0]text];





    // creating new minor goal
    MinorGoal *newMinorGoal = [NSEntityDescription
                               insertNewObjectForEntityForName:@"MinorGoal"
                                  inManagedObjectContext:self.selectedGoal.managedObjectContext];




    // setting title of new minor goal
    newMinorGoal.title = minorTitle;




    [self.selectedGoal addMinorGoalObject:newMinorGoal];



    // saving
    NSError *error = nil;
    if (![self.selectedGoal.managedObjectContext save:&error]) {
        NSLog(@"Error saving new minor goal: %@", error);
    }
    NSLog(@"we save %@ to %@ and theres %lu in it", newMinorGoal.title,      self.selectedGoal.title, (unsigned long) [self.selectedGoal.minorGoal count]);


    // fetching
    [self.fetchedResultsController performFetch:&error];


    // reloading tableView data
    [self.tableView reloadData];

   }
  }












 @end

只要告诉我获取正确子对象的正确方法,我应该将它们放入 NSSet 中吗?

最佳答案

看起来您正在使用 NSFetchedResultsController 来获取所有 MinorGoal 实例,但您只想显示子 MinorGoals。如果你想使用 NSFetchedResultsController 那么你需要添加一个 predicate 到 fetch 以便它只返回作为所选目标的子级的 MinorGoals。假设您已经在 MinorGoal 和 Goal 之间创建了一个名为“parentGoal”的关系:

fetchRequest.predicate = [NSPredicate predicateWithFormat:@"self.parentGoal = %@", self.selectedGoal];

或者,不要使用 NSFetchedResultsController 而是使用关系。您需要将 NSSet 转换为数组并将其排序为先前的答案。

关于iphone - 获取属于父对象的子对象并将它们放入 tableView 中(核心数据、关系),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18862744/

相关文章:

ios - 解析 iOS 问题关闭登录 View

ios - XIB View 未显示正确的布局 [iOS Swift]

ios - 如何使用 NSPredicate 通过多文本查询搜索文本?

iphone - UISegmentedControl 设置为瞬时处理程序

iphone - 当单选按钮选择检查

ios - 点击时使 UIButton 文本变暗

ios - 如何正确使用 AVPlayer 使其在播放视频前不显示白屏?

iphone - 如何解析下面的XML?

ios - 标签栏的 iPhone 应用程序

ios - 如何在邮件应用程序地址中制作带标签的 UITextField?