弱参考代表未恢复

时间:2016-03-27 19:37:43

标签: ios objective-c delegates weak-references state-restoration

AddCityViewController将恢复其相应的文本字段。 '取消'并且'保存'按钮包含对委托的调用。正在恢复模态视图控制器,但是" Save"和"取消"按钮未激活委托方法。所有视图控制器都是在故事板中创建的。

//  AddCityViewController.h

@class City;

#import <UIKit/UIKit.h>
@protocol addCityDelegate;

@interface AddCityViewController : UIViewController
@property(nonatomic, weak) id <addCityDelegate> delegate;
@property(nonatomic,strong)NSManagedObjectContext *context;
@end

@protocol addCityDelegate
- (void)save: (City *)controller withBool:(BOOL )saveStatus;;
@end

取消按钮仅在未执行状态恢复时调用委托方法。

我希望代表在需要进行状态恢复时也被调用

// AddCityViewController.m

- (IBAction)cancelButton:(UIBarButtonItem *)sender {
   [self.delegate save:nil withBool:false];
}

#pragma mark - encodeRestorable and decodeRestorable

- (void)encodeRestorableStateWithCoder:(NSCoder *)coder
{
   [super encodeRestorableStateWithCoder:coder];
   [coder encodeObject:self.delegate forKey:@"restoreDelegate"];
   [coder encodeObject:self.cityNameLabel.text          
                forKey:@"restoreCountyLabelText"];    
}

-(void)decodeRestorableStateWithCoder:(NSCoder *)coder
{
    [coder encodeObject:self.delegate forKey:@"restoreDelegate"];
    _cityNameLabel.text = [coder decodeObjectForKey:@"restoreCountyLabelText"];

    [super decodeRestorableStateWithCoder:coder];
}

CityTableViewControllerAddCityTableView

的代表
// CityTableViewController.m

  #import "CityTableViewController.h"
  #import "AddCityViewController.h"

  #import "City.h"
  #import "County.h"

  @interface CityTableViewController ()<addCityDelegate>
  @property(nonatomic,strong)NSFetchedResultsController *fetchedResultsController;
  @end
  #pragma mark - AddConjugations Delete

...

除了STATE RESTORATION之外,下面的委托方法功能完美。在状态恢复期间,永远不会调用此方法。

 - (void)save: (AddCityViewController *)saveNewCity withBool:(BOOL )saveStatus
 {
    if (saveStatus) {
   ...
 }

1 个答案:

答案 0 :(得分:0)

您正在尝试再次对代理进行编码,而不是对其进行解码。

将您的代码更改为:

-(void)decodeRestorableStateWithCoder:(NSCoder *)coder
{
    self.delegate = [coder decodeObjectForKey:@"restoreDelegate"];
    _cityNameLabel.text = [coder decodeObjectForKey:@"restoreCountyLabelText"];

    [super decodeRestorableStateWithCoder:coder];
}