gpt4 book ai didi

objective-c - UITABViewController中两个UIViewControllers之间的KVO机制

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:06:51 24 4
gpt4 key购买 nike

我是 iPhone 新手。我正在尝试实现 KVO 机制。

我有什么?

两个TabController有两个UIViewController,FirstViewController有一个按钮,SecondViewController 有一个 UITextView

我想要什么?

当在 firstViewController 中按下按钮时,它会更新成员变量,这应该被 secondViewController 观察到,并且它应该附加到 UITextView。

我做了什么?

FirstViewController.h

@interface FirstViewController : UIViewController
{
IBOutlet UIButton *submitButton;

}

-(IBAction)submitButtonPressed;

@property (retain) NSString* logString;
@end

FirstViewController.m

-(IBAction)submitButtonPressed
{
NSLog (@" Submit Button PRessed ");
self.logString = @"... BUtton PRessed and passing this information ";
}

SecondViewController.h

@interface SecondViewController : UIViewController
{
IBOutlet UITextView *logView;
}

@property (nonatomic, strong) UITextView *logView;
@end

SecondViewController.m

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
......

NSArray *vControllers = [self.tabBarController viewControllers];
FirstViewController *fvc = [vControllers objectAtIndex:0];
[fvc addObserver:self forKeyPath:@"logString" options:NSKeyValueObservingOptionNew context:NULL];

return self;
}


-(void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
NSLog (@".... OBSERVE VALUE FOR KEY PATH...");
}

我期望得到什么输出?

每次我按下 FirstViewController 中的按钮时,都应打印字符串“.... OBSERVE VALUE FOR KEY PATH...”。

我得到了什么?

无输出。

我做错了什么?请帮助我

最佳答案

将您的“成员变量”放入一个单独的类文件中……即模型/ View / Controller 。创建一个保存数据的单例模型对象,然后您可以从任何 View Controller 对该模型对象进行 KVO。

这是粗略的伪代码:

    @interface MyDataModel: NSObject
{
NSString *logString;
}
@property (nonatomic,retain) NSString *logString;
@end

@implementation MyDataModel

@synthesize logString;

+ (MyDataModel *) modelObject
{
static MyDataModel *instance = nil;
static dispatch_once_t once;
dispatch_once(&once, ^{
if (instance == nil)
{
instance = [[self alloc] init];
}
});

return (instance);
}

@end

在你的 VC1 中

MyDataModel *model = [MyDataModel modelObject];
[model setLogString:@"test"];

在你的 VC2 中

[model addObserver:self forKeyPath:@"logString" options:0 context:NULL]; 

一种更复杂的方法是使用核心数据作为持久存储并充当您的数据模型。

关于objective-c - UITABViewController中两个UIViewControllers之间的KVO机制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11883818/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com