使用委托将数据传回备份导航堆栈

Mat*_*ice 14 delegates objective-c uinavigationcontroller ios

我一直在与两个视图控制器之间的数据传递斗争几天,并且变得非常困惑.我是Objective-C的新手,并且发现一些棘手的部分让我头脑发热.

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

我已经阅读了很多关于这个(stackoverflow,iphonedevsdk,CS 193P资源)和我见过的选项,

1)应用程序委托中的ivar(脏而不推荐)2)创建单例3)创建数据模型类4)使用协议和委托(由apple推荐)

我想做正确的事情,并希望在我的计划中使用选项4 - 代表

问题是,我不了解代表以及如何设置和实现它们.

任何人都可以提供有关如何使用委托和2个视图控制器设置和传递NSArray的基本示例.

在此先感谢马特

小智 30

委托是在这种情况下使用的正确模式,但是您的描述看起来不像委托,因为它使用全局变量.也许您将全局变量存储在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
Run Code Online (Sandbox Code Playgroud)

SecondViewController.m:

@implementation SecondViewController

@synthesize delegate;
@synthesize someArray;

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

- (void)someMethodCalledWhenUserIsDone
{
    [delegate secondViewControllerDidFinish:self];
}
Run Code Online (Sandbox Code Playgroud)

FirstViewController.h:

#import SecondViewController

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

@end
Run Code Online (Sandbox Code Playgroud)

FirstViewController.m:

@implementation FirstViewController

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

@end
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢您的回复,对其他人的好参考.我还问了另一个与此类似的问题,然后对其进行了全面的回答.http://stackoverflow.com/questions/5210535/passing-data-between-view-controllers (2认同)