Vaibhav Gautam
Vaibhav Gautam

Reputation: 43

Property without @synthesis is not iniatialized for custom objects

I am working on an app in which I have created some classes for model, view and for controllers.

There are few model classes namely

CellModel.h

#import <Foundation/Foundation.h>

@interface CellModel : NSObject{

}
@property(nonatomic, assign)BOOL isSelected;
@property(nonatomic, retain)NSString *headingText;
@property(nonatomic, retain)NSString *subHeadingText;

@end

CellModel.m

#import "CellModel.h"

@implementation CellModel

@end

Classes mentioned above will act as model object for each cell

TableModel.h

/*This is the model class navgation bar menu and will contain objects of "CellModel only"*/
#import <Foundation/Foundation.h>

@interface TableModel : NSObject{

}
@property(nonatomic, retain)NSMutableArray* menuOptionsArray;

@end

and

TableModel.m

#import "TableModel.h"

@implementation TableModel

@end

now in the view controller class i have created property of type TableModel named as *tableModelObj. and in a method I am adding different object of type CellModel in tableModelObj.menuOptionArray

but I don't know why but when I try to add objects in this array the object "tableModelObj" is always empty.

P.S. I dont want to synthesize my properties because in XCode 4.6 it is not necessary to do so.

Upvotes: 1

Views: 141

Answers (3)

micantox
micantox

Reputation: 5616

The getter and the setter are indeed generated for you, but all they do is to either set or return the value you stored in the iVar, no initialization is performed at any point.

The best practice is to create a custom lazy initializer getter. For example, the most basic option is to do:

-(NSMutableArray*)menuOptionsArray
{
   if(!_menuOptionsArray)
      _menuOptionsArray = [[NSMutableArray alloc] init];
   return _menuOptionsArray;
}

Upvotes: 0

trojanfoe
trojanfoe

Reputation: 122381

@synthesize will create the property getter/setter methods, but it won't allocate the object's instance variables and it won't release them. You need:

@implementation TableModel

- (id)init {
    self = [super init];
    if (self) {
        // NOTE! an autorelease object is used
        self.menuOptionsArray = [NSMutableArray array];
    }
    return self;
}

- (void)dealloc {
    self.menuOptionsArray = nil;
    [super dealloc];
}

@end

You need to do this for all your objects when using MRR.

Upvotes: 2

PakitoV
PakitoV

Reputation: 2498

I think is not the table model that is empty, is that probably you need to initialise the mutable (menuOptionsArray) array before adding elements...

Upvotes: 3

Related Questions