How to do Cocoa constructors properly

I recently decided to clean up some code that was Cocoa-specific to use Sugar, in case I want to make it cross-platform. I realized that I was also using the name-conventions for Cocoa constructors/initializers, as shown below, which could be called like:

 
var c := new Chemical;
var d := new Chemical withName('methane') formula('CH4');

I want to know what is the equivalent approach using the constructor keyword.

Is it something like immediately below? I.e., can we get rid of that awful stuff with the assignment of Self, etc?

constructor Chemical();
begin
   inherited constructor();
   //...extra stuff here...
end;

constructor Chemical.withName(aName: String) formula(aFormula: String);
begin
   constructor();
   //...extra stuff here...
end;
// Original Cocoa-convention constructors
method Chemical.init: id;
begin
  Self := inherited init;
  if assigned(Self) then begin 
    // Custom initialization
    ...blah...blah...
  end;
  result := Self;
end;

method Chemical.initWithName(aName: String) formula(aFormula: String): id;
begin
   Self := init;  // "Should that be inherited init"?
   if assigned(Self) 
      then begin
               FName := aName;
               FFormula := aFormula;
           end;
   result := Self;
end;

oke there are a few different things:

  self := init; // calls the 'init' in the same class, if it's there, else the base one.
  self := inherited init; // always calls the base.

Besides that Oxygene will always add a "self := " if you don’t, and do the if assigned(self) then check if you don’t, so you can write it like you’ve always done;

constructor MyConstructor;
begin
  inherited constructor(Parameters go Here);
  // code here
end;

and the compiler will turn it in the right thing.

So if I declare a constructor

constructor MyClass foo;
begin
   inherited constructor();
end;

what happens in Cocoa is that Oxygene just generates a method MyClass.initfoo to serve as the constructor and keep the Cocoa runtime happy? (Or, if I have implemented method MyClass.initfoo it just calls that?)

indeed.

Thanks, Carlo.

I see that the last platform-specific stuff I have in this unit is a bunch of calls to String.stringWithFormat. I see that Sugar.String has a Format class method, but the documentation says it ignores the format specifier, and it seems less capable than the Cocoa formatting. Is there any recommendation for cross-platform formatting, primarily of Double, Integer and String? It’s not crucial to me to have all of this stuff cross-platform for now, but I figured I’d do as much business code as possible in a platform-independent way so porting would be easier later if I decided to do it.

Help us improve there Sugar.String formatter to have the full capabilities of System.String on .NET :wink: