【问题标题】:weak reference delegate not restored弱引用委托未恢复
【发布时间】:2016-03-27 19:37:43
【问题描述】:

AddCityViewController 与其对应的文本字段一起恢复。 “取消”和“保存”按钮包含对代表的调用。模态视图控制器正在恢复,但“保存”和“取消”按钮未激活委托方法。所有视图控制器都在情节提要中创建。

//  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

...

除了状态恢复之外,下面的委托方法运行良好。在状态恢复期间,从不调用此方法。

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

【问题讨论】:

  • 将委托存档为存档对象图的一部分是很奇怪的。通常,当 UI 可用时您会重新创建一些东西。一般。
  • 我不知道如何在视图控制器恢复时重新创建委托。通过状态恢复,视图控制器返回其文本字段文本,但 self.delegate = (null)。

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


【解决方案1】:

您正在尝试再次对您的委托进行编码而不是对其进行解码。

将您的代码更改为:

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

【讨论】:

    猜你喜欢
    • 2013-06-30
    • 2018-11-08
    • 2016-04-09
    • 2017-12-23
    • 1970-01-01
    • 2015-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多