gpt4 book ai didi

objective-c - 使用委托(delegate)将数据传递回导航堆栈

转载 作者:技术小花猫 更新时间:2023-10-29 10:14:06 26 4
gpt4 key购买 nike

几天来,我一直在为在两个 View Controller 之间传递数据而苦苦挣扎,并且感到非常困惑。我是 Objective-C 的新手,发现有些部分很难让我头脑清醒。

我有一个导航 Controller ,FirstView 是一个表单,在这个表单上我有一个按钮加载 SecondView,其中包含一个 TableView 供用户选择一些选项。然后我想将选择传递回 FirstView Controller 并显示数据等...

我已经阅读了很多相关内容(stackoverflow、iphonedevsdk、CS 193P 资源),我看到的选项是,

1) app delegate 中的ivar(不推荐)2)创建单例3)创建数据模型类4)使用协议(protocol)和委托(delegate)(苹果推荐)

我想做正确的事并想使用选项 4 - 在我的程序中委托(delegate)

问题是,我不了解委托(delegate)以及如何设置和实现它们。

谁能提供一个基本示例,说明如何使用委托(delegate)和 2 个 View Controller 设置和传递 NSArray。

提前致谢马特

最佳答案

委托(delegate)是在这种情况下使用的正确模式,但您的描述看起来不太像委托(delegate),因为它使用的是全局变量。也许您正在将全局变量存储在您的 App Delegate 中,您应该始终尽量避免这种情况。

下面是代码的大致轮廓:

SecondViewController.h:

@protocol SecondViewControllerDelegate;

@interface SecondViewController;

SecondViewController : UIViewController
{
id<SecondViewControllerDelegate> delegate;

NSArray* someArray;
}

@property (nonatomic, assign) id<SecondViewControllerDelegate> delegate;
@property (nonatomic, retain) NSArray* someArray;

@end

@protocol SecondViewControllerDelegate
- (void)secondViewControllerDidFinish:(SecondViewController*)secondViewController;
@end

SecondViewController.m:

@implementation SecondViewController

@synthesize delegate;
@synthesize someArray;

- (void)dealloc
{
[someArray release];
[super dealloc];
}

- (void)someMethodCalledWhenUserIsDone
{
[delegate secondViewControllerDidFinish:self];
}

FirstViewController.h:

#import SecondViewController

@interface FirstViewController : UIViewController <SecondViewControllerDelegate>
{
...
}

@end

FirstViewController.m:

@implementation FirstViewController

- (void)secondViewControllerDidFinish:(SecondViewController*)secondViewController
{
NSArray* someArray = secondViewController.someArray
// Do something with the array
}

@end

关于objective-c - 使用委托(delegate)将数据传递回导航堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5244830/

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