我将创建一个类(下面的 MyDataController)来管理数据,并使用共享实例从我的应用程序中的任何位置访问它。
接口(MyDataController.h)
@interface MyDataController : NSObject {
NSMutableArray *myData; // this would be the collection that you need to share
}
+ (MyDataController*)sharedDataController;
// ... add functions here to read / write your data
@end
实现(MyDataController.m)
static MyDataController* sharedDataController; // this will be unique and contain your data
@implementation MyDataController
+ (MyDataController*)sharedDataController
{
if (!sharedDataController)
sharedDataController = [[[MyDataController alloc] init] autorelease]; // no autorelease if ARC
return sharedDataController;
}
// ... implement your functions to read/write data
@end
最后,从任何地方访问这个静态对象:
MyDataController *dataController = [MyDataController sharedDataController]; // this will create or return the existing controller;