如何在应用程序退出之前将变量保留在内存中

时间:2012-01-08 01:17:58

标签: ios memory-management singleton global-variables automatic-ref-counting

我在iOS中有一个单例对象,在实例化时解析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

2 个答案:

答案 0 :(得分:4)

+(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];

答案 1 :(得分:0)

一个简单的单身人士就像......在.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