Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

BadWolf13

macrumors 6502
Original poster
Dec 17, 2009
271
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?
 
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.
 
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?
 
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.
 
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?
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.