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

chen8002004

macrumors newbie
Original poster
May 22, 2011
26
0
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;
 
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.)
 
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.
 
Last edited:
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.