objective-c - 使类的实例在内存中保留更长时间(在 ARC 下)

标签 objective-c ios automatic-ref-counting

我有一个 NSObject 类的实例,它应该解析 XML 并保存 NSManagedObjects,它一切正常。但我需要在其中接收 NSManagedObjectContextDidSaveNotification 来合并 CoreData 上下文。

问题是,我的实例在我收到上述通知之前就被释放了。

如何防止我的实例被过早释放?

这是我调用实例的时间

// in my ViewController implementation

WSNoticia *wsNoticia = [WSNoticia new]; // __strong by default right?

这是 WSNoticia 的实现:

<前>- (id)init { self = [ super 初始化]; 如果( self ){ [ self 解析新闻]; } 返回 self ; } - (void)dealloc { //在 mergeChanges: 或 updateContext: 之前调用 } #pragma mark - 私有(private)方法 - (void)parseNews { //在另一个线程中保存上下文 AppDelegate *appDelegate = (AppDelegate *)[[UIApplication共享应用]委托(delegate)]; NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init]; [上下文 setUndoManager:nil];//性能优势 [context setPersistentStoreCoordinator:[appDelegate permanentStoreCoordinator]]; [[NSNotificationCenter defaultCenter] addObserver:self 选择器:@selector(mergeChanges:) 名称:NSManagedObjectContextDidSaveNotification 对象:context]; NSBlockOperation *blockOperation = [NSBlockOperation blockOperationWithBlock:^{ //获取东西 }]; [blockOperation setCompletionBlock:^{ //更新并保存内容 //这里调用 NSManagedObjectContextDidSaveNotification (通过执行 [context save:nil]; }]; //添加操作到队列 NSOperationQueue *operationQueue = [NSOperationQueue new]; [操作队列添加操作: block 操作]; } //没有被调用 - (void)updateContext:(NSNotification *)通知 { NSManagedObjectContext *mainContext = [self ManagedObjectContext]; [mainContext mergeChangesFromContextDidSaveNotification:通知]; [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationNameNoticiasParsed object:self]; } #pragma mark - NSNotificationCenter //没有被调用 - (void)mergeChanges:(NSNotification *)通知 { [[NSNotificationCenterdefaultCenter]removeObserver:self]; AppDelegate *appDelegate = (AppDelegate *)[[UIApplication共享应用]委托(delegate)]; NSManagedObjectContext *mainContext = [appDelegate ManagedObjectContext]; if ([通知对象] == mainContext) { //主上下文保存,无需执行合并 返回; } [self PerformSelectorOnMainThread:@selector(updateContext:) withObject:notification waitUntilDone:YES]; }

最佳答案

默认情况下会应用强生命周期限定符,但变量的生命周期仅适用于声明它的方法。

如果您将 wsNoticia 声明为实例变量,应该没问题。

关于objective-c - 使类的实例在内存中保留更长时间(在 ARC 下),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8509715/

相关文章:

iphone - 使用 colorWithPatternImage : 时如何保持图像透明度

iOS MapKit - 如何将 map 集中在从 View 中的文本字段获得的特定位置?

ios - 当服务器端添加新项目时如何加载 TableView ?

ios - 在 swift 项目中混淆字符串常量 secret

objective-c - Objective-C 中的weakSelf 和strongSelf

ios - 执行展开时应用程序崩溃

objective-c - 如何在 View 中居中 NSTextField

swift - 为什么类的 init 方法中不需要隐式可选?

objective-c - 发布如何在基于 ARC 的项目中工作

objective-c - 核心数据:NSPredicate,对象由实体对象组成