Mac Initializing a custom formatter

BadWolf13

macrumors 6502
Original poster
Dec 17, 2009
267
0
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

macrumors 68020
Aug 17, 2009
2,124
2,322
IOKWARDI
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

macrumors 6502
Original poster
Dec 17, 2009
267
0
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

macrumors 68020
Aug 17, 2009
2,124
2,322
IOKWARDI
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

Code:
-(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

macrumors 6502
Original poster
Dec 17, 2009
267
0
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:

Code:
-(void)encodeWithCoder:(NSCoder *)aCoder {
	[super encodeWithCoder:aCoder];
}
Seems kinda redundant, doesn't it?