0

我有 5 个视图控制器,可以说 A、B、C、D 和 E,所有这些视图控制器都将作为 A->B->C->D->E 推送到导航控制器。

我在 A 中有一个数组,我需要将它传递给数组 E。在 A 中,我不应该为 E 创建对象,反之亦然。

根据我的要求,在视图控制器之间传递数据的方法是什么?

4

3 回答 3

1

您可以使用通知中心方法。在您的视图控制器的 viewdidload 方法中编写以下代码..

[[NSNotificationCenter defaultCenter] addObserver: self
                                     selector: @selector(anymethod:) 
                                         name: anyname 
                                       object: nil];

和方法..

- (void)anymethod:(NSNotification *)notification 
{
  NSLog(@"%@", notification.userInfo);  
}

并从其他视图控制器传递数据,例如,

[[NSNotificationCenter defaultCenter] postNotificationName:@"anyname" object:self userInfo:anydata];
于 2013-10-26T05:13:31.037 回答
1

(1)您可以使用NSNotification:

NSNotification 有一个名为 userInfo 的属性,它是一个 NSDictionary。该对象是发布 NSNotification 的 NSObject。所以通常我在设置 NSNotification 时使用 self 作为对象,因为 self 是发送 NSNotification 的 NSObject。如果您希望使用 NSNotification 传递 NSArray,我将执行以下操作:

NSArray *myArray = ....;
NSDictionary *theInfo = [NSDictionary dictionaryWithObjectsAndKeys:myArray,@"myArray", nil];
[[NSNotificationCenter defaultCenter] postNotificationName:@"reloadData" object:self userInfo:theInfo];

然后使用以下命令捕获它:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doTheReload:) name:@"reloadData" object:sendingObject];

其中 sendObject 是发送 NSNotification 的对象。

最后,使用 doTheReload: 解码数组:

 NSArray  *theArray = [[notification userInfo] objectForKey:@"myArray"];

这总是对我有用。祝你好运!

(2) 应用委托:

您还可以在 Application delegate 中声明 NSMutableArray 并在 A 视图控制器中将对象分配给该数组,您可以在视图控制器 E 中自动获取该数组。

于 2013-10-26T05:22:36.327 回答
-1

许多人建议AppDelegate并确保它确实有效,因为AppDelegate它本身是一个单例,但是,您知道,您不应该将一段数据放入它不属于的类中(这就是人们所说的面向对象编程)。无论如何,它确实有效,如果你想节省一点时间,创建一个新类的一些麻烦,并且对违反一些旧的面向对象原则感到高兴,那么它可能会很好。

通知中心应该只用于通知:一些事件发生在一个地方,另一个对象想要得到通知,可能还有一些关于该事件的数据。不是纯数据共享的最佳选择。性能不是问题,因为它与函数调用有关(假设您只传递指针,而不是复制一些大数据)。

恕我直言,您有两个选择(至少):

创建一个专用于包含数据的单例类。很多资源告诉你如何做到这一点,但基本上 Objective-C 中的单例类看起来像这样

@interface S 

+(S*)singleton;

@end

@implementation S
+(S*)singleton { // iOS sometimes use 'sharedInstance' instead of 'singleton'
    static S* o = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        o = [[self alloc] init];
    });

    return o;
}

@end

并且无论何时您需要访问它

[S singleton] ...

第二个选项适用于在整个应用程序生命周期中只有一个 A 实例(如果 A 是根视图控制器,这种情况经常发生)。在这种情况下,您可以将 A 变成单例。您的应用委托中的代码将如下所示

A* a = [A singleton];

UINavigationController* nav = [[UINavigationController alloc] initWithRootViewController:a];

E 可以访问所有 A 的数据[A singleton]

于 2013-10-26T07:27:02.160 回答