您将全局应用程序数据放在iPhone应用程序中的哪个位置? [英] Where do you put global application data in an iPhone app?

查看:106
本文介绍了您将全局应用程序数据放在iPhone应用程序中的哪个位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,允许用户查看,操作和管理Schedule对象的集合。应用程序的不同部分需要访问此数据。我已经尝试过将这个集合变成一个单例,但我发现它并不是很干净。

I have an app that allows the user to view, manipulate and manage a collection of Schedule objects. Different parts of the app need access to this data. I've experimented with making the collection a singleton, but I didn't find that very clean.

我最近更改为将全局数据存储在AppDelegate类中并使用:

I recently changed to storing the global data in the AppDelegate class and using:

MyAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
[delegate.myGlobalData doSomething];

这消除了我的全局数据成为单身人士的需要,但实际上只是利用了UIApplication singleton。

Which eliminates the need for my global data to be a singleton, but is really just taking advantage of the UIApplication singleton.

真的不只有一个主视图控制器,在我的情况下存储它是有意义的。所以我想知道人们用什么不同的策略来解决这个问题。

There really isn't just one primary view controller where it makes sense to store it in my case. So I was wondering what different strategies people use to address this.

推荐答案

如果你有一个需要的中央数据模型对于多个控制器是可访问的,使用单例来管理数据没有任何问题 - sharedManager正是场景所需要的。这基本上是Apple用他们的地址簿API来处理联系人的行为。它们使用C风格的API,但它涉及获取对共享地址簿数据库的引用,然后在将来的调用中使用它。

If you've got a central data model that needs to be accessible to multiple controllers, there's nothing wrong with using a singleton to manage the data-- a "sharedManager" is exactly what the scenario demands. This is essentially what Apple does with their address book API for manipulating contacts. They use a C-style API but it involves getting a reference to the shared address book database and then using that in future calls.

使用app delegate也可以,但是你注意到它真的是一样的。您将app delegate singleton指定为数据模型的所有者,这也没关系。

Using the app delegate works too, but as you note it's really the same thing. You're designating the app delegate singleton as the owner of the data model, which is OK too.

NSUserDefaults可能会以这种方式被滥用,但这实际上不是它的目的。除了有点丑陋外,它还限制了您可以存储的数据类型。您自己的模型可以存储您喜欢的任何数据,但NSUserDefaults不是那么灵活。

NSUserDefaults can be abused in this way but that's really not its purpose. Aside from being kind of ugly, it also puts restrictions on the type of data you can store. Your own model can store whatever data you like, but NSUserDefaults is not quite so flexible.

使用SQLite或属性列表或任何将数据存储到文件中的确是与如何管理它的问题正交。根据您的描述,单例方法听起来很合理,单例可以以对您正在使用的数据有意义的任何方式写入文件。

Using SQLite or a property list or whatever to store the data to a file is really orthogonal to the question of how to manage it. From your description a singleton approach sounds reasonable, and that singleton can write to files in whatever way makes sense for the data you're working with.

这篇关于您将全局应用程序数据放在iPhone应用程序中的哪个位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆