Initializing a custom formatter

Discussion in 'Mac Programming' started by BadWolf13, Mar 12, 2012.

  1. macrumors 6502

    Joined:
    Dec 17, 2009
    #1
    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?
     
  2. macrumors 68000

    Sydde

    Joined:
    Aug 17, 2009
    #2
    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.
     
  3. thread starter macrumors 6502

    Joined:
    Dec 17, 2009
    #3
    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?
     
  4. macrumors 68000

    Sydde

    Joined:
    Aug 17, 2009
    #4
    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.
     
  5. thread starter macrumors 6502

    Joined:
    Dec 17, 2009
    #5
    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?
     

Share This Page