Javier Roberto
Javier Roberto

Reputation: 1293

Generate custom init method automatically

Is it possible to generate custom init method automatically from Xcode, as Android Studio does for android? I mean, if I declare some properties in .h, for example: int a; int b;

So, I would like to create automatically a init method as:

- (id)initWithA:(int) aInner andB:(int) bInner
{
     a = aInner;
     b = bInner;
}

Upvotes: 17

Views: 10259

Answers (5)

Wu Yuan Chun
Wu Yuan Chun

Reputation: 1184

New Xcode (after Xcode 10) support this issue for class (not for struct).

Steps:

  1. right click on class name
  2. click "refactor"
  3. click "Generate Memberwise Initializer"

enter image description here

As for struct. You can make it class first, and change it back to struct after you get auto-gen init.

Upvotes: 25

Mark
Mark

Reputation: 6957

While there's still no way to do this automatically (without installing a plugin), there's a neat trick to convert a list of property declarations to assignments using multiple cursors:

  • Copy the list of properties and paste it into your constructor
  • Use Shift+Ctrl + click to insert multiple cursors (Shift+Ctrl+/ work as well)
  • Edit with multiple cursors to assign values

multi cursor

Credits go to Paul Hudson: Xcode in 20 Seconds: Multiple cursors

Upvotes: 8

Matthew Cawley
Matthew Cawley

Reputation: 2998

There is no native way of doing this, however you can install XCode extensions that will add support for this.

See this following extension as this will provide the feature you are after (Swift version).

https://github.com/Bouke/SwiftInitializerGenerator

Upvotes: 2

Gajendra Rawat
Gajendra Rawat

Reputation: 3663

Yes you can initialise an class by custom init method or you can pass parameter when you want to initialise class with custom init method

look

Define in your class.h file

 @interface CustomView : UIView 
   - (id)initWithA:(int) aInner andB:(int) bInner

In .m file implement initWithStringMethod.

 - (id)initWithA:(int) aInner andB:(int) bInner
       {
        if((self = [super init]))


        return self;
        }

initialised class from other class or viewController

 CustomView *cv = [[CustomView alloc] initWithA:5 andB:10 ];

Upvotes: -3

Earl Grey
Earl Grey

Reputation: 7466

Yo can create a snippet. You need to play with it a bit, create nice blue placeholders where relevant but most importantly, attach a keyboard shortcut to it. For example "initx"

Then you just start to type the shortcut in line where you want the initialiser to be and voila, you have your custom init.

Upvotes: -2

Related Questions