Imagine my class has following ivars/properties:
@property (nonatomic, copy) NSString *itemName;
@property (nonatomic, copy) NSString *serialNumber;
@property (nonatomic) int valueInDollars;
@property NSDate *dateCreated;
1) One way to initialize ivars of this class is like this:
// Designated initializer of this class
-(id) initWithItemName: (NSString*) name
valueInDollars:(int)value
serialNumber:(NSString *)sNumber
{
// Call the superclass's designated initializer
self = [super init];
if(self)
{
// Init properties
self.itemName = name;
self.serialNumber = sNumber;
self.valueInDollars = value;
dateCreated = [[NSDate alloc] init];
}
// Return the address of the newly initialized object
return self;
}
2) Another way I am thinking go initialize this class is for example is to write:
-(id) init
{
self = [super init];
if(self)
{
// basically do nothing
}
return self;
}
And then leave it up to the user who will be using the class to do initialization as he needs it, e.g.,
MyClass *object = [[MyClass alloc] init];
object.dateCreated = [[NSDate alloc] init];
[object.dateCreated someMethod];
object.itemName = "Hello";
object.someProperty = [[SomeClass alloc] init];
The thing with above I think is that some properties (as above) must be called a alloc/init
before they can be used isn't it? And if user forgets to do so, then at most the app won't work as expected right? (It won't crash as we can send message to nil). What I wrote here seems to be the only problem with this way of initialization. What is your opinion?
ps. it is permitted as here too: http://developer.apple.com/library/ios/#documentation/general/conceptual/CocoaEncyclopedia/Initialization/Initialization.html
pps. Assuming ARC is used.
thanks for many replies, but basically I was interested in what are the possible problems with solution 2?