在视图之间共享nsarray(3.1M大小)的正确方法

时间:2011-02-23 14:34:32

标签: iphone cocoa-touch

我正在从AppDelegate读取不小的数组。

NSArray *mycountryspecific = [[NSArray alloc] initWithContentsOfURL:[[NSBundle mainBundle] URLForResource:@"nextTwoWeekEvents" withExtension:@"ary"]];
self.myCountrySpecificCodesList = mycountryspecific;
[mycountryspecific release],mycountryspecific = nil;

为了将它保存在内存中,我声明了属性

@property (nonatomic, retain) NSArray *myCountrySpecificCodesList;

但是从主视图开始我必须走2步,而我将使用它,在事件控制器下我将有事件详细视图控制器,它将是这个数组的必要部分(基于谓词)。

我当前的设计是一个不是来自AppDelegate的读取数组,而是在必要时从事件详细视图控制器。

你可以分享一下经验吗?如果更好的是从appdelegate加载数组并保留在内存中,请建议一种正确的方法来在类之间发送访问属性而不会发生内存泄漏。

EventsTableViewController *events = [[EventsTableViewController alloc] initWithNibName:@"EventsTableViewController" bundle:nil];
self.eventListController = events;

PromoView *promo = [[PromoView alloc] initWithNibName:@"PromoView" bundle:nil];

UINavigationController *navigationController = [[UINavigationController alloc] init];
[navigationController pushViewController:events animated:NO];

UITabBarController *tabBar = [[UITabBarController alloc] init];
self.tabBarController = tabBar;

[tabBar setViewControllers:[NSArray arrayWithObjects:navigationController,promo,nil]];

eventListController.managedObjectContext = self.managedObjectContext;

[self.window addSubview:tabBarController.view];

在玩了一些我的控制器后,我找到了解决方案。 每当我显示一个详细的页面时,我仍然从文件中读取数组,但现在这是一个字典,其中一个键是第一个找到的世界,这个cay的数组是我需要的结果。 数组转换为34k,代码在密钥中进行大小写密集搜索:

NSDictionary *mycountryspecific = [[NSDictionary alloc] initWithContentsOfURL:[[NSBundle mainBundle] URLForResource:@"countryspecific" withExtension:@"dict"]];
NSSet * mySet = [mycountryspecific keysOfEntriesPassingTest:^(id key, id obj, BOOL *stop) {
    if([key compare:countryName options:NSCaseInsensitiveSearch] == NSOrderedSame) {
        return YES;
    }
        else
        return NO;
    }];

NSArray *result = [mycountryspecific valueForKey:[mySet anyObject]];

这种方式在iphone 3G上运行良好:)当然,在模拟器上要好得多; - )

3 个答案:

答案 0 :(得分:2)

我建议不要使用一个完全存放在内存中的大型数组,而是建议将国家/地区特定代码列表存储在Core Data数据库中。

通过这样做,您可以使用批量提取和NSFetchedResultsController仅加载您在该给定时刻向用户呈现所需的任何信息,仅此而已。这将显着降低应用程序的总体内存使用量,并可能导致更快的启动和加载时间。

然后,每个视图控制器都可以拥有自己的NSFetchedResultsController实例来访问数据库,从而为数据提供不同的视角。

答案 1 :(得分:1)

我使用singleton类来存储共享数据。这非常方便。看一下这个模板http://blog.mugunthkumar.com/coding/xcode-tip-singleton-class-template/

答案 2 :(得分:1)

如果正确保留和释放内存,则初始化对象的位置无关紧要。只需确保您的所有媒体资源均为retain,并在release为每个保留的课程强制执行dealloc来电。

相关问题