[英]How can I access data that's stored in my App Delegate from my various view controllers?
This question is similar to this other post , but I'm new to iPhone development and I'm getting used to the good practices for organizing my data throughout my app. 这个问题与其他文章类似,但是我是iPhone开发的新手,我已经习惯了在整个应用程序中组织数据的良好做法。 I understand the ApplicationDelegate object to be the best place to manage data that is global to my app, correct?
我知道ApplicationDelegate对象是管理应用程序全局数据的最佳位置,对吗? If so, how can I access data that's stored in my App Delegate from various view controllers?
如果是这样,如何从各种视图控制器访问存储在我的App Delegate中的数据? For example, my array is created in the app delegate as such...
例如,我的数组就是这样在应用程序委托中创建的...
appdelegate.m appdelegate.m
sectionTitles = [[NSArray alloc] initWithObjects: @"Title1", @"Title2", @"Title3", nil];
rootViewController.appDelegate = self;
and I need to access it throughout the different views of my app, like my root table view controller... 而且我需要在我的应用程序的所有不同视图中访问它,例如我的根表视图控制器...
rootviewcontroller.m rootviewcontroller.m
NSUInteger numTableSections = [self.appDelegate.sectionTitles count];
Is this the best way to do it or are there any reasons I should organize my data a better way? 这是最好的方法吗?还是有任何理由应该以更好的方式组织数据? I ask because I can never really get too comfortable with using global variables (I blame my college professors), though I'm not sure if this can be considered a global variable.
我问,是因为我永远不会对使用全局变量感到非常自满(我怪我的大学教授),尽管我不确定是否可以将其视为全局变量。
Thanks so much in advance for your help! 在此先感谢您的帮助!
I understand the ApplicationDelegate object to be the best place to manage data that is global to my app, correct?
我知道ApplicationDelegate对象是管理应用程序全局数据的最佳位置,对吗?
Not really (your college professors had a point). 不完全是(您的大学教授有道理)。 It's tempting to start putting a lot of stuff into the app delegate, but it's not a very sustainable practice.
吸引人的是开始将很多东西放到应用程序委托中,但这不是一个非常可持续的做法。 See my answer here .
在这里查看我的答案 。
And read this good post by Matt Gallagher for more depth. 并阅读Matt Gallagher撰写的这篇好文章,以获取更多深度。
That said, I often put something like this in my app delegate header: 也就是说,我经常在我的应用程序委托标头中输入以下内容:
#define APP_DELEGATE (MyAppDelegate*) [[UIApplication sharedApplication] delegate]
so I can easily do things like: 这样我就可以轻松地执行以下操作:
int n = [[APP_DELEGATE sectionTitles]count];
这应该工作:
self.appDelegate = ( YourApplicationDelegate *) [[UIApplication sharedApplication] delegate];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.