Search code examples
objective-ciosglobal-variablesfactoryfactory-pattern

EXC_BAD_ACCESS when synthesizing a 'global' object


this is a follow-up question to my last one here: iOS: Initialise object at start of application for all controllers to use .

I have set my application up as follows (ignore the DB Prefix):

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

i will go step by step through the application, and will then in the end post the error message i get when building.

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

DBFactoryClass.m

#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

when i build it, i get the following error: EXC_BAD_ACCESS in this line:

@synthesize DATAMODEL;

of DBFactoryClass.m


Solution

  • What @synthesize does is to automatically generate implementations of the accessors for a property. EXC_BAD_ACCESS there means that you're accessing garbage when one of the accessors is executed.

    That's probably happening here:

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

    Make sure that DBDataModel's implementation of init actually returns a legitimate object.