从弹出的视图控制器传递数据

Mic*_*ael 3 objective-c uinavigationcontroller ios

我有两个视图控制器.我是第一个,当我按下按钮时,第二个视图控制器被推到导航控制器的堆栈上.这里,在第二个视图控制器中我有一个表视图,当我点击某些行时,它们被选中(如复选框),并且与这些行相关的一些数据被添加到数组中.现在,当我完成选择时,我想回到第一个视图控制器并使用该数组.怎么做?现在我的应用程序是这样的:我有一个委托协议,然后我有属性数组的对象,我可以从整个应用程序访问该对象及其数组...但我真的不喜欢这样.这是正确/最好/最简单的方法吗?

Sha*_*rog 6

我有一个委托协议,然后我有属性数组的对象,我可以从整个应用程序访问该对象及其数组...但我真的不喜欢这样.这是正确/最好/最简单的方法吗?

委托是在这里使用的正确模式,但是您描述的并不是委托,而是使用全局变量.也许你将全局变量存储在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)

  • 我不得不设置secondViewController.delegate = self; 在我推它之前...现在它有效:)再次感谢 (2认同)