合成'global'对象时EXC_BAD_ACCESS



这是我最后一个问题的后续问题:iOS:在应用程序启动时初始化对象,供所有控制器使用。

我已经将我的应用程序设置如下(忽略DB前缀):

DBFactoryClass     // Built a DataManaging Object for later use in the app
DBDataModel        // Is created by the factory, holds all data & access methods
DBViewControllerA  // Will show some of the data that DBDataModel holds
moreViewControllers that will need access to the same DBDataModel Object

我将一步一步地完成应用程序,然后在最后发布构建时收到的错误消息。

AppDelegate.h

#import "DBFactoryClass.h"

AppDelegate.m

- (BOOL)...didFinishLaunching...
{
    DBFactoryClass *FACTORY = [[DBFactoryClass alloc ]init ];
    return YES;
}

DBFactoryClass.h

#import <Foundation/Foundation.h>
#import "DBDataModel.h"
@interface DBFactoryClass : NSObject
@property (strong) DBDataModel *DATAMODEL;
@end

DBFactoryM类

#import "DBFactoryClass.h"
@implementation DBFactoryClass
@synthesize DATAMODEL;
-(id)init{
    self = [super init];
    [self setDATAMODEL:[[DBDataModel alloc]init ]];
    return self;
}
@end

ViewControllerA.h

#import <UIKit/UIKit.h>
#import "DBDataModel.h"
@class DBDataModel;
@interface todayViewController : UIViewController
@property (strong)DBDataModel *DATAMODEL;
@property (weak, nonatomic) IBOutlet UILabel *testLabel;
@end

ViewControllerA.m

#import "todayViewController.h"
@implementation todayViewController 
@synthesize testLabel;
@synthesize DATAMODEL;
- (void)viewDidLoad
{
    todaySpentLabel.text = [[DATAMODEL test]stringValue];
}
@end

DBDataModel.h

#import <Foundation/Foundation.h>
@interface DBDataModel : NSObject
@property (nonatomic, retain) NSNumber* test;
@end

DBDataModel.m

#import "DBDataModel.h"
@implementation DBDataModel
@synthesize test;
-(id)init{
    test = [[NSNumber alloc]initWithInt:4];
    return self;
}
@end

当我构建它时,我得到以下错误:此行中的EXC_BAD_ACCESS

@synthesize DATAMODEL;

DBFactoryClass.m

@synthesize所做的是自动生成属性的访问器的实现。EXC_BAD_ACCESS意味着当执行其中一个访问器时,您正在访问垃圾。

这可能发生在这里:

[self setDATAMODEL:[[DBDataModel alloc]init ]]; 

确保DBDataModelinit的实现实际上返回了一个合法的对象。

据我所知,您的DBFactoryClass类从未存储在任何地方,因此如果您使用ARC,则会在分配后立即释放(由于您使用了strong关键字,我认为您使用了)。

- (BOOL)...didFinishLaunching... {
  DBFactoryClass *FACTORY = [[DBFactoryClass alloc ]init ];
  // If you use ARC this might be released right afterwards
  return YES;
}

如果你想让工厂成为一个单独的工厂,可以使用类似于的东西

+ (id)sharedInstance {
  static dispatch_once_t once;
  static MyFoo *instance;
  dispatch_once(&once, ^{
    instance = [[self alloc] init];
  });
  return instance;
}

最新更新