intellij-ideaappcodexcode-template

How can I custom getter templates in AppCode


AppCode can generate getter code like this:

- (UIView *)leftAnchorView {
    return _leftAnchorView;
}    

In the Preferences -> Editor -> File and Code Templates -> Code Tab, I found the getter templates is

#if ($IVAR_IS_AVAILABLE == "true")
return $IVAR;#else
return $DEFAULT_RETURN_VALUE;#end

So,I modify the templates like this:

#if ($IVAR_IS_AVAILABLE == "true")
if(!$IVAR){
    $CUSTOM_CODE
}
return $IVAR;#else
return $DEFAULT_RETURN_VALUE;#end

The result is

- (UIView *)leftAnchorView {
    if(!_leftAnchorView){
    }
    return _leftAnchorView;
}

Now, my target is

 - (UIView *)leftAnchorView {
     if(!_leftAnchorView){
         _leftAnchorView = [UIView new];
     }
     return _leftAnchorView;
 }

Can anyone tell my how modify the code templates to achive my target? Thanks!


Solution

  • There is a description of various variables in the specific template on the bottom-right side of File and Code templates window. So, you need to use a $RETURN_TYPE variable, which holds the type. But the type contains * which you do not need. In Velocity templates you can use Java String functions, so the final template will be

    #if ($IVAR_IS_AVAILABLE == "true")
    if(!$IVAR){
        $IVAR = [$RETURN_TYPE.replace("*"," ") new];
    }
    return $IVAR;#else
    return $DEFAULT_RETURN_VALUE;#end