从每个视图控制器访问一个NSArray

我有一个很大的NSArray ,我必须在几个视图控制器中使用。 我从服务器获取数据,当用户打开新视图时,我不想总是下载它。

那么我怎样才能把它定义为一个“全局variables”呢?

我可以用segues来做,但是没有他们就不行。 我试图在DestinationViewController声明一个名为dataToDestinationView的数组,然后将其导入到self.arrayToExport所在的视图中,并添加上面的行,但不起作用。 我错过了什么?

 DestinationViewController *dataToNew = [DestinationViewController alloc]init]; dataToNew.dataToDestinationView = self.arrayToExport; 

更新与我在AppDelegate的尝试:

AppDelegate.h

 @property (nonatomic, strong) PNChannel *myChannel; 

AppDelegate.m

 [PubNub requestHistoryForChannel:self.myChannel from:nil to:nil limit:100 reverseHistory:NO withCompletionBlock:^(NSArray *contentArray, PNChannel *channel, PNDate *fromDate, PNDate *toDate, PNError *error) { + (NSArray *)mySharedArray { static NSArray *sharedArray = nil; if (sharedArray) return sharedArray; sharedArray = contentArray; return sharedArray; } }]; 

在这种情况下,我得到了两个错误: Use of undeclared identifier 'self'Expected identifier or '(' 。我不明白这一点,因为self.myChannel在.h中声明,我在其他地方使用相同的块标识符问题。

第二次更新

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // [self.window makeKeyAndVisible]; [PubNub setDelegate:self]; PFUser *currentChannel = [PFUser currentUser]; self.myChannel = [PNChannel channelWithName:currentChannel.username shouldObservePresence:YES]; } - (void)getMessage { [PubNub requestFullHistoryForChannel:self.myChannel withCompletionBlock:^(NSArray *contentArray, PNChannel *channel, PNDate *fromDate, PNDate *toDate, PNError *error) { + (NSArray *)mySharedArray { static NSArray *sharedArray = nil; if (sharedArray) return sharedArray; sharedArray = contentArray; return sharedArray; } NSLog(@"mokus katona %@", contactArray); }]; } 

在您的应用程序委托中,声明一个静态variables和一个读取它的方法:

 static NSArray *_message = nil; @implementation AppDelegate + (NSArray *)message { if (_message) return _message; AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; [appDelegate getMessage]; return nil; } - (void)getMessage { [PubNub requestFullHistoryForChannel:self.myChannel withCompletionBlock:^(NSArray *contentArray, PNChannel *channel, PNDate *fromDate, PNDate *toDate, PNError *error) { NSLog(@"mokus katona %@", contactArray); _message = contactArray; }]; } @end 

也许这可以帮助你。

在您的pch文件( #project -Prefix.pch)中,您可以创build您的全局variables,可从所有空格中获取 。 往下看

 #ifdef __OBJC__ NSArray *myArray; #endif 

并在你的应用程序委托中,在你的- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions ,你可以用这样的服务器数据填充你的数组

 [PubNub requestFullHistoryForChannel:self.myChannel withCompletionBlock:^(NSArray *contentArray, PNChannel *channel, PNDate *fromDate, PNDate *toDate, PNError *error) { NSLog(@"mokus katona %@", contactArray); myArray = contactArray; }]; 

现在这只是一次加载和myArray将可用于所有的控制器,模型,视图等

让我知道这是否有帮助。