PDA

View Full Version : Initializing a custom formatter




BadWolf13
Mar 12, 2012, 11:03 PM
Hi guys,

I'm creating a custom formatter, as a subclass of NSNumberFormatter. I am trying to use the init method to set some defaults, like the suffix, and maximum digits and so forth. However, weird thing is happeneing, that it's not going through that method. Doesn't everything in Objective-C pass through the init method?



Sydde
Mar 12, 2012, 11:42 PM
Hi guys,

I'm creating a custom formatter, as a subclass of NSNumberFormatter. I am trying to use the init method to set some defaults, like the suffix, and maximum digits and so forth. However, weird thing is happeneing, that it's not going through that method. Doesn't everything in Objective-C pass through the init method?

I would guess you have this object in a nib? If that is the case, I suggest you try putting your default settings in an -awakeFromNib method and see if that works.

The method called after +alloc is usually some method that starts with "init...", but if one of the alternate forms is called, that will replace plain -init. Nib loading calls -initWithCoder: when instantiating objects, so that may be the "init..." form that is getting called.

BadWolf13
Mar 13, 2012, 11:17 PM
I plan on reusing this class in a few different apps. Is there any reason why I shouldn't declare initWithCoder: in my subclass, and put the code I need there?

Sydde
Mar 14, 2012, 10:44 AM
No reason, really, but it should be balanced with the -encodeWithCoder: method so that you can declare the class as conforming with NSCoding protocol. Make sure both methods call super, as in

-(id)initWithCoder:(NSCoder *)decoder {
if ( ( self = [super initWithCoder:decoder] ) ) {
// do your custom initialization
}
return self;
}

Bear in mind that you probably should also include a regular -init method as well if you ever think you might create this object programmatically.

BadWolf13
Mar 14, 2012, 08:10 PM
I've used encodeWithCoder before, but always with something that I was going to archive. Since the internals of this formatter aren't going to change, it seems a bit pointless here. I mean, all I would write would be:

-(void)encodeWithCoder:(NSCoder *)aCoder {
[super encodeWithCoder:aCoder];
}


Seems kinda redundant, doesn't it?