I am learning Objective-C. In my first non-trivial project, I came across the question of how to better handle the resources passed to the initializer compared to the default initializer. My class has a saved resource enginethat can be set manually after creation either during initialization explicitly or during default initialization:
- (id)init {
if ((self = [super init])) {
id e = [[XorShiftEngine alloc] init];
[self setEngine: e];
[e release];
}
return self;
}
- (id)initWithEngine:(NSObject <RandEngine> *)e {
if ((self = [super init]))
[self setEngine: e];
return self;
}
- (id)setEngine:(NSObject <RandEngine> *)newEngine {
[newEngine retain];
[engine release];
engine = newEngine;
return engine;
}
The default initializer, in particular, seems very ugly to me, alternating the code related to itself, then the member, then I again, then the member again and calling the object only to release it later. It also violates the designated idiom of the initializer.
, ?
user79758