2014-03-07 49 views
1

我是DI和台风的新手。我想知道是否有可能用init方法和属性以外的方法初始化一个对象。 我有一个名为ObjectMapper的类,一个ObjectMapper可以有N个ObjectMaps。利用台风之前,我创建的地图,像这样:在台风中使用非属性方法初始化对象

ObjectMap *map1 = [ObjectMap new]; [map1 mapProperty:@"prop1" toName:@"name1"]; [map1 mapProperty:@"prop2" toName:@"name2"]; ObjectMap *map2 = [ObjectMap new]; [map2 mapProperty:@"prop3" toName:@"name3"]; mapper.maps = @[map1, map2];

的地图和整个应用程序的生命周期的映射对象永远不会改变。我想在Typhoon中创建ObjectMapper和ObjectMaps。 更新:似乎TyphoonFactoryProvider可能会帮助,但我不知道如何将工厂创建的对象放置到'地图'数组。

回答

1

TyphoonFactoryProvider在这里不会帮助你 - 这个(高级)类只是提供一种干净的方式来获得一个实例,其中一些初始化参数或属性在运行时间之前是未知的。 。通常在这里你会之一:

  • 获取实例,然后与运行在两个单独的步骤
  • 配置它称为ARGS创建自定义工厂

TyphoonFactoryProvider只是写工厂定制代码你,以及处理一些内存管理的细节。 (懒惰依赖)。它用于例如:从一个视图控制器转换到另一个视图控制器。

如果我了解你,你试图做的事情不是直接可能与台风。但是,您总是可以注入一个对象实例(配置信息)以及afterPropertyInjection回调完成。例如:

-(id) mappedComponent 
{ 
    return [TyphoonDefinition withClass:[MyType class] properties:^(TyphoonDefinition* definition) 
    { 
     // Any object. This time an NSDictionary using Objc literals shorthand 
     [definition injectProperty:@selector(mappings) withObjectInstance:@{ 
      @"prop1" : @"name1", 
      @"prop2" : @"name2", 
      @"prop3" : @"name3" 
     }]; 
     //This can be a category method if you don't "own" the class in question. The method puts the object in the required state, using the config data provided. 
     definition.afterPropertyInject = @selector(myConfigMethod)]; 
     }]; 
} 
+1

很高兴知道我不会错过任何东西。我可以将ObjectMap子类化,并在它自己的init方法中配置它们。 – Tylerc230

2

如果您准备好承担风险,可以尝试支持方法注入的开发版Typhoon。 (仍然没有记录,但似乎工作)

-(id) mappedComponent 
{ 
    return [TyphoonDefinition withClass:[ObjectMap class] injections:^(TyphoonDefinition *definition) { 
     [definition injectMethod:@selector(mapProperty:toName:) withParameters:^(TyphoonMethod *method) { 
      [method injectParameterWith:@"property"]; 
      [method injectParameterWith:@"name"]; 
     }]; 
    }]; 
} 
相关问题