我正在尝试在应用程序委托(delegate)中添加自定义委托(delegate),我正在这样做:
AppDelegate.h
@protocol AppDelegateDelegate <NSObject>
- (void)finishSync:(BOOL)success;
@end
@interface AppDelegate : UIResponder <UIApplicationDelegate> {
@property (nonatomic, weak) id <AppDelegateDelegate> delegate;
@end
然后我尝试在 UITabViewController 连接的其他 View 中使用此委托(delegate),我这样做:
FirstView.h
#import "AppDelegate.h"
@interface FirstView : UIViewController <AppDelegateDelegate>
@end
FirstView.m
@implementation FirstView
...
- (void)viewDidLoad {
AppDelegate *appController = (AppDelegate *)[[UIApplication sharedApplication] delegate];
appController.customDelegate = self;
}
FirstView 工作完美,但是例如,如果我切换到具有相同代码来实现委托(delegate)的 SecondViewController,则委托(delegate)在 FirstView 中都不再工作......我错了什么?
编辑:
我已经尝试了 rdelmar 答案,但不起作用,现在我更好地解释我的情况,我在 UITabBarController 中有 4 个 View ,此 View 加载在应用程序委托(delegate)中的 didfinishloading 方法中,然后应用程序在中打开第一个 View ,这是登录 View ViewDidAppear 就像您在答案中所做的那样:
<FirstView: 0xae10280>
然后我切换到第二个 View ,这是委托(delegate)的 viewdidappear nslog:
<SecondView: 0x9f79b10>
然后我切换到第三个 View ,这是 nslog:
<ThirdView: 0xba86200>
最后一个是 FourthView:
<FourtView: 0xba875b0>
看来所有委托(delegate)都在所有 View 中工作,然后我尝试切换到第一个 View ,这是日志:
(null)
我切换第三个 View :
(null)
第二个:
(null)
第四个:
(null)
不再工作,所以我停止应用程序并再次运行它,并从第一个 View 开始:
<FirstView: 0xad28730>
切换到第二个 View :
<SecondView: 0x9f682e0>
返回第一个 View :
(null)
切换到第二个 View :
(null)
切换到第三个 View :
<ThirdView: 0xab297e0>
切换到第四 View :
<FourthView: 0xab28430>
然后再看第三个 View :
(null)
所以你可以看到问题是第一次有效,然后当返回 View 时委托(delegate)为空,知道吗?
编辑 2:
我还注意到,如果我在 NavigationController 之间切换 View ,委托(delegate)永远不会(null),而是像我一样在 UITabBarController 中切换 View ,我的代码给出 null...所以我认为这是 UITabBarController View 的问题。 .
最佳答案
一个对象一次只能有一个委托(delegate)。尝试在 FirstView 的 viewWillDisappear 方法中将委托(delegate)设置为 nil,看看是否有帮助。
这对我有用。我将委托(delegate)的设置移至第一个 Controller 中的 viewWillAppear 中,因此如果我从第二个 Controller 返回到它,它将重置。我的 Controller 位于导航 Controller 中,我使用推送和弹出来来回移动。两个 Controller 都有相同的代码(日志除外):
#import "ViewController.h"
#import "AppDelegate.h"
@interface ViewController ()
@property (strong,nonatomic) AppDelegate *appController;
@end
@implementation ViewController //This is the first controller
-(void)viewDidAppear:(BOOL)animated {
self.appController = (AppDelegate *)[[UIApplication sharedApplication] delegate];
self.appController.customDelegate = self;
[super viewDidAppear:animated];
NSLog(@"First says: %@",self.appController.customDelegate);
}
-(void)viewWillDisappear:(BOOL)animated {
NSLog(@"First viewWillDisappear");
[super viewWillDisappear:animated];
self.appController.customDelegate = nil;
}
- (void)finishSync:(BOOL)success {
}
关于iphone - 在 AppDelegate 中使用自定义委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13864539/