How to construct with parameters

Discussion in 'iOS Programming' started by chen8002004, Jun 15, 2011.

  1. chen8002004 macrumors newbie

    Joined:
    May 22, 2011
    #1
    In C++, it is possible to use constructor with parameters to create an object. For example, Car myCar(10); But how to do similar thing in Objective-C? Is the following code correct?
    Code:
    -(id) init: (classname *) aClass;
     
  2. jnoxx macrumors 65816

    jnoxx

    Joined:
    Dec 29, 2010
    Location:
    Aartselaar // Antwerp // Belgium
    #2
    U can make those methods, (i just looked at the code).

    For example. i made something like this.


    Code:
    + (id)buttonwithCoordinates:(CGFloat)x andY:(CGFloat)y andSize:(CGFloat)width andHeight:(CGFloat)height target:(id)aTarget selector:(SEL)aSelector;
    And I assign it to an UIButton *button;

    Since it's a id, u can assign anything to it, but u have a return method, and what u are returning, u are assigning to your pointer. So in my case, an UIButton.
    (i'm sure my theory isn't 100% waterpoof, and robbieduncan or somewhat will bash it hard, but this will set you on your way.)
     
  3. PhoneyDeveloper, Jun 16, 2011
    Last edited: Jun 16, 2011

    PhoneyDeveloper macrumors 68030

    PhoneyDeveloper

    Joined:
    Sep 2, 2008
    #3
    By convention methods with init in their names are constructors. So you create init methods with multiple parameters. The class methods beginning with + are factory methods that return autoreleased objects created with the same init methods with multiple parameters. See the various Foundation container classes for many examples. NSString, NSDictionary and the others all have multiple init methods. Search the headers for "initWith" to find more examples in UIKit.

    Also, if you're going to have multiple init methods you should understand the concept of the designated initializer, which you can read about in the Objective C 2.0 language guide.
     

Share This Page