【发布时间】:2012-06-18 15:43:04
【问题描述】:
我的代码中有一个奇怪的行为,我真的不知道如何解决它。
我有一个具有此定义的 Singleton 类:
AppModelLocator.h>
#import <Foundation/Foundation.h>
@interface AppModelManager : NSObject
+ (AppModelManager *)sharedManager;
@end
AppModelLocator.m
#import "AppModelManager.h"
static AppModelManager *instance = nil;
@implementation AppModelManager
#pragma mark - Singletone
#pragma mark
+ (AppModelManager *)sharedManager
{
@synchronized ([AppModelManager class]) {
if (instance == nil) {
instance = [AppModelManager new];
}
}
return instance;
}
+ (id)alloc
{
@synchronized ([AppModelManager class]) {
NSAssert(instance == nil, @"Attempted to allocate the second instance of AppModelManager.");
instance = [super alloc];
return instance;
}
return nil;
}
@end
当我在代码中的某处调用[AppModelLocator sharedManager]时,一切都很好。但是,当我在特定代码行之后调用单例类时,它会抛出 EXC_BAD_ACCESS (code=1, address=0xfffffeec) 并在单例类的 sharedManager 定义中引用 return instance。
该特定代码正在初始化一个创建 HTTP 请求并开始发送请求的类,但在该类中没有任何 AppModelLocator 的引用或一些特殊的东西。它是NSURLConnection 及其委托方法的简单创建。
我在其他应用程序中使用了类似的类和方法,它们运行良好,我想知道这个类有什么问题。我尝试了十几种其他创建单例类的方法,但都没有用。
【问题讨论】:
-
你没有覆盖
retain、release和autorelease- 你是在你的应用程序的某个地方释放你的单例吗(如果你不使用 ARC,这只是一个有效的评论:) -
PS 如果您正在使用 ARC,此链接 lukeredpath.co.uk/blog/a-note-on-objective-c-singletons.html 将为您提供更好的方法:)
-
我正在使用 ARC,因此无需覆盖
retain、release和autorelease。我还测试了链接中描述的方法。结果没有变化。 -
发生此异常的具体代码行是什么?如果您已经尝试了所有这些事情,那么问题可能不是访问您的单例 :)
-
这是调用方式:
AppModelManager *m = [AppModelManager sharedManager];引发异常,它是前面的行:KeyExchangeRequest *request = [[KeyExchangeRequest alloc] initWithIdentifier:@"keyexchange" delegate:self options:options]; [request start];
标签: objective-c singleton exc-bad-access