kaz*_*chi 4 iphone cocoa cocoa-touch objective-c ios
我想创建一个从plist中检索数据的数据管理器类,我想知道是否应该使用所有类方法创建一个类,每次调用方法并返回请求的值时读取plist,或者创建一个初始化的类初始化器带有plist数据的数组(实例变量)和所有方法都是从数组中获取数据的实例方法.
我想知道哪个更贵:阅读plist多次(如50次)或实例化一个对象,或者简单哪个更好.
提前谢谢你的帮助.
这是编程中经典的权衡之一 - 速度与内存使用.读取一次并将其存储在更快的介质(在本例中,在内存中)的技术称为缓存.它非常受欢迎,而且有充分的理由.大容量存储设备仍然比RAM慢,并且网络访问速度比本地大容量存储慢.
如果您假设经常会询问经理的数据,并且假设plist不会改变(或者您可以检测到更改),那么在第一次访问getter时读取plist,将其存储在iVar中,并且只要plist没有改变,只回答iVar.这会占用更多内存,但后续访问速度要快得多.
注意:此方法对非常非常大的文件有害.如果您担心内存使用情况,请- (void)didReceiveMemoryWarning在viewControllers中实现该方法,并在内存不足时刷新缓存(删除它).
getter方法可能如下所示:
- (NSArray *)data
{
if (!cacheArray) {
//what we do now is called "lazy initialization": we initialize our array only when we first need the data.
//This is elegant, because it ensures the data will always be there when you ask for it,
//but we don't need to initialize for data that might never be needed, and we automatically re-fill the array in case it has been deleted (for instance because of low memory)
cacheArray = ... //read array from plist here; be sure to retain or copy it
}
return cacheArray;
}
Run Code Online (Sandbox Code Playgroud)