我该如何正确执行此委托?

时间:2014-11-29 14:43:28

标签: ios objective-c iphone core-data nsfetchedresultscontroller

我有一个表视图控制器和一个视图控制器。

  • StackTableViewController - 字符串列表

  • HomeViewController - 带有标签的空视图控制器

HomeViewController标签应始终显示StackTableViewController的第一个sting。

我需要确保删除第一个字符串以显示新的第一个字符串。

这就是我遇到问题的地方......如果我删除了第一个字符串并返回到HomeViewController,标签仍然是我刚刚删除的字符串....如果我终止应用并再次打开它,标签中显示的正确字符串。

到目前为止我是这样做的:

这是我的StackTableViewController.h + .m中的相关方法:

@protocol StackTableViewControllerDelegate <NSObject>

@optional

-(void)didDeleteObject;

@end

@interface StackTableViewController : UITableViewController <UITableViewDataSource,UITableViewDelegate> 

@property (strong,nonatomic) id<StackTableViewControllerDelegate> delegate;
@property (strong, nonatomic) NSString *currentTarget;

@end



#import "StackTableViewController.h"
#import "Target.h"
#import "StackTableViewCell.h"
#import "HomeViewController.h"
#import "CoreDataStack.h"

@interface StackTableViewController () <NSFetchedResultsControllerDelegate>

@property (nonatomic, strong) NSFetchedResultsController *fetchedResultController;

@end

@implementation StackTableViewController

- (id)init {

    self = [super initWithNibName:@"StackTableViewController" bundle:nil];
    if (self) {
        // Do something
        [self.fetchedResultController performFetch:nil];
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:0];
        Target *current = [self.fetchedResultController objectAtIndexPath:indexPath];
        self.currentTarget = current.body;
    }
    return self;
}

- (void)viewDidLoad {

    [super viewDidLoad];
    self.navigationItem.rightBarButtonItem = self.editButtonItem;
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:0];
    Target *current = [self.fetchedResultController objectAtIndexPath:indexPath];
    self.currentTarget = current.body;
}

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

    Target *target = [self.fetchedResultController objectAtIndexPath:indexPath];
    CoreDataStack *stack = [CoreDataStack defaultStack];
    [[stack managedObjectContext] deleteObject:target];
    [stack saveContext];

    if ([_delegate respondsToSelector:@selector(didDeleteObject)]) {
        [_delegate didDeleteObject];
    }

}

这是HomeViewController.h + .m:

中的相关方法
#import <UIKit/UIKit.h>
#import "StackTableViewController.h"

@interface HomeViewController : UIViewController {

    StackTableViewController *stackTableViewController;
}

@property (strong, nonatomic) IBOutlet UILabel *homeLabel;

- (IBAction)goToStack:(id)sender;



#import "StackTableViewController.h"

@interface HomeViewController () <StackTableViewControllerDelegate>


@end

@implementation HomeViewController

- (id)init {
    self = [super initWithNibName:@"HomeViewController" bundle:nil];
    if (self) {
        // Do something
        stackTableViewController = [[StackTableViewController alloc] init];
        stackTableViewController.delegate = self;
    }
    return self;
}

- (void)viewDidLoad {

    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self.navigationController setNavigationBarHidden:YES];
    self.homeLabel.font = [UIFont fontWithName:@"Candara-Bold" size:40];

    self.homeLabel.text = stackTableViewController.currentTarget;
}

- (void)didDeleteObject {
    self.homeLabel.text = stackTableViewController.currentTarget;
}

- (IBAction)goToStack:(id)sender {
    StackTableViewController *vc = [[StackTableViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

CoreDataStack.h + .m:

#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>

@interface CoreDataStack : NSObject

@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;

+ (instancetype)defaultStack;
- (void)saveContext;
- (NSURL *)applicationDocumentsDirectory;


@end


#import "CoreDataStack.h"

@implementation CoreDataStack

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

+ (instancetype)defaultStack {

    static CoreDataStack *defaultStack;
    static dispatch_once_t onceTocken;
    dispatch_once (&onceTocken, ^{
        defaultStack = [[self alloc] init];
    });

    return defaultStack;
}


- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "digitalCrown.Treats" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Treats" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }

    // Create the coordinator and store

    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Treats.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return _persistentStoreCoordinator;
}


- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] init];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}


@end

请帮助我解决这个问题,我正在尝试各种各样的方式,但可能我错过了与视图控制器生命周期有关的东西。

(CoreDataStack是单身人士)

TNX !!

5 个答案:

答案 0 :(得分:1)

您可以做的是使用一个操作来检查发件人和segue以了解它的来源:

  - (void)unwindFromModal:(UIStoryboardSegue *)unwindSegue {
        if unwindSegue.identifier == @"createModal" {
             NSLog(@"Got home from create page");
        }

        if unwindSegue.identifier == @"stackModal" {
           NSLog(@"Got home from stack page");
        }
    }


    - (IBAction)presentModal:(UIButton*)sender {
       if sender.tag == 0 {
            [self performSegueWithIdentifier:@"createModal" sender:self];
       } 
       if sender.tag == 1 {
            [self performSegueWithIdentifier:@"stackModal" sender:self];
        }

    }

如果您愿意,可以在标签中使用字符串常量来提高可读性和切换性

答案 1 :(得分:1)

这里可能有两个问题需要解决。

  1. 根本没有调用委托方法didDeleteObject。在goToStack方法中,您创建了一个新的StackTableViewController,但忘记设置其委托,同时还有一个全局变量stackTableViewController实例。我认为你的意思是把全局的一个推到堆栈上。

  2. commitEditingStyle tableview委托方法中,您忘记更新用于更新标签文本的currentTarget属性,您可以尝试更新该属性,看看会发生什么。< / p>

  3. 对于1,您可以像这样更改goToStack函数:

    [self.navigationController pushViewController:stackTableViewController animated:YES];
    

    这意味着应删除StackTableViewController *vc = [[StackTableViewController alloc] init];

    对于2,在commitEditingStyle方法中,[stack saveContext]之后。

    [stack saveContext];
    
    //Please add the following code.
    NSIndexPath *theIndexPath = [NSIndexPath indexPathForItem:0 inSection:0];
    Target *current = [self.fetchedResultController objectAtIndexPath:theIndexPath];
    self.currentTarget = current.body;
    

答案 2 :(得分:1)

您的问题是您没有更新StackTableViewController中的currentTarget媒体资源commitEditingStyle。只需更新StackTableViewController.m中的代码:

即可

此外,如果您使用相同的代码超过2次 - 最好将其移动到单独的功能

- (id)init {

    self = [super initWithNibName:@"StackTableViewController" bundle:nil];
    if (self) {
        // Do something
        [self.fetchedResultController performFetch:nil];
        [self updateCurrentTarget];
    }
    return self;
}

- (void)viewDidLoad {

    [super viewDidLoad];
    self.navigationItem.rightBarButtonItem = self.editButtonItem;
    [self updateCurrentTarget];
}

- (void)updateCurrentTarget
{
    if (self.fetchedResultsController.sections.count == 0 && [self.fetchedResultsController.sections.firstObject count] == 0) {
        self.currentTarget = nil;
    } else {
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:0];
        Target *current = [self.fetchedResultController objectAtIndexPath:indexPath];
        self.currentTarget = current.body;
    }
}

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

    Target *target = [self.fetchedResultController objectAtIndexPath:indexPath];
    CoreDataStack *stack = [CoreDataStack defaultStack];
    [[stack managedObjectContext] deleteObject:target];
    [stack saveContext];
    [self updateCurrentTarget];

    if ([_delegate respondsToSelector:@selector(didDeleteObject)]) {
        [_delegate didDeleteObject];
    }
}

答案 3 :(得分:1)

- (IBAction)goToStack:(id)sender {
    StackTableViewController *vc = [[StackTableViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

此方法应如下所示:

- (IBAction)goToStack:(id)sender {
    StackTableViewController *vc = [[StackTableViewController alloc] init];
    vc.delegate = self.
    [self.navigationController pushViewController:vc animated:YES];
}

原因是您在init方法中将HomeVC设置为StackTable的委托,但您没有使用相同的StackTable实例并初始化新实例。

答案 4 :(得分:1)

您需要进行2次更改:

  • goToStack:
  • 之前vc.delegate = self添加pushViewController:
  • 在调用StackTableViewController tableView: commitEditingStyle:
  • 之前的currentTarget更新[_delegate didDeleteObject]