我在iOS中有一个singleton对象,当实例化时,它解析CSV文件,然后保存结果。我想让这个对象可以普遍访问,我希望在应用程序退出之前不要从内存中释放它。我正在运行ARC,所以我不能进行手动保留。
有没有一种方法我可以做到这一点,这样它将与ARC一起工作?
头文件:
#import <Foundation/Foundation.h>
#import "CHCSV.h"
#import "RCParserObject.h"
@interface ParserStore : NSObject <CHCSVParserDelegate>
{
// CSV Variables
RCParserObject *item;
NSMutableArray *data;
NSMutableArray *parsedData;
int fields;
bool open;
}
@property (atomic, retain) RCParserObject *item;
@property (atomic, retain) NSMutableArray *data;
@property (atomic, retain) NSMutableArray *parsedData;
@property (atomic) int fields;
@property (atomic) bool open;
+ (ParserStore *) defaultStore;
- (void) parseCSVFile:(NSString*)file;
- (void) categorizeData;
实现文件
#import "ParserStore.h"
#import "RCParserObject.h"
#import "RCDetailItem.h"
static ParserStore *defaultStore;
@implementation ParserStore
@synthesize item, data, parsedData, fields, open;
# pragma mark -
# pragma mark Singleton Methods
+ (ParserStore *) defaultStore
{
if (!defaultStore)
{
defaultStore = [[super allocWithZone:NULL] init];
}
return defaultStore;
}
+ (id) allocWithZone:(NSZone *)zone
{
return [self defaultStore];
}
- (id) init
{
NSLog(@"Running init on parser store");
if (defaultStore)
{
NSLog(@"Self data count is %d, right before return", self.parsedData.count);
return defaultStore;
}
// NSLog(@"This better only happen once");
self = [super init];
[self setParsedData:[[NSMutableArray alloc] init]];
[self parseCSVFile:@"ContentNoPathFileExt2ASCII"];
[self categorizeData];
// NSLog(@"Self data count is %d when first created", self.parsedData.count);
return self;
}
@property (atomic, retain) RCParserObject *item;
@property (atomic, retain) NSMutableArray *data;
@property (atomic, retain) NSMutableArray *parsedData;
@property (atomic) int fields;
@property (atomic) bool open;
+ (ParserStore *) defaultStore;
- (void) parseCSVFile:(NSString*)file;
- (void) categorizeData;
@end
+(MySingleton *)singleton {
static dispatch_once_t pred;
static MySingleton *shared = nil;
dispatch_once(&pred, ^{
shared = [[MySingleton alloc] init];
shared.someVar = someValue; // if you want to initialize an ivar
});
return shared;
}
从任何地方:
NSLog(@"%@",[MySingleton singleton].someVar);
请注意,您的iOS应用程序已经有了一个可以在任何地方访问的单例:
AppDelegate *delegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
一个简单的单例应该是。。。在.h:中
@interface Foo : NSObject
+ (Foo *)sharedInstance;
@end
并且在.m:中
static Foo *_foo = nil;
@implementation Foo
+ (Foo *)sharedInstance {
if (!_foo)
_foo = [[Foo alloc] init];
return _foo;
}
@end