2014-03-07 73 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"]; 
     }]; 
    }]; 
}