gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:51:35 30 4
gpt4 key购买 nike

我在 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

最佳答案

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

关于ios - 如何在应用程序退出之前将变量保留在内存中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8774602/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com