LoginSignup
2
2

More than 5 years have passed since last update.

[Objective-C] 文字列からインスタンスの生成とメソッド呼び出し(プロパティの設定)をやってみる

Last updated at Posted at 2015-09-22

以下のようにして実装してみた。

params
// 文字列として必要クラスなどのデータを保持している想定
NSDictionary *paramInfo = @{ @"className": @"AnyClass",
                             @"paramName": @"setFloat:",
                             @"type": @"float",
                             @"value": @(0.5),};

実装

NSMethodSignatureNSInvocation を利用する。

- (id)createInstanceWithDictionary:(NSDictionary *)paramInfo
{
    Class class = NSClassFromString(paramInfo[@"className"]);
    __autoreleasing __typeof(class) instance = [[class alloc] init];

    SEL sel = NSSelectorFromString(paramInfo[@"paramName"]);
    CGFloat val = [paramInfo[@"value"] doubleValue];

    NSMethodSignature *signature = [class instanceMethodSignatureForSelector:sel];
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
    invocation.selector = sel;
    invocation.target = instance;
    [invocation setArgument:&val atIndex:2];
    [invocation invoke];

    return instance;
}

文字列で実行することの是非はあると思うけど、とりあえず動かすことができた。

2
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2