2013-05-11 21 views
0

我有一個類名爲IGMapViewController的getInstance initWithNibName前:

在我有

static IGMapViewController *instance =nil; 

+(IGMapViewController *)getInstance { 
    @synchronized(self) { 
     if (instance==nil) { 
      instance= [IGMapViewController new]; 
     } 
    } 
    return instance; 
} 

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{ 
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
    if (self) { 
    // more code 
     instance = self; 
    } 

    return self; 
} 

如果使用對象多則1類,但只在一個類中使用initWithNibName

在init方法中名爲IGRouteController的類中,我使用_mapViewController = [IGMapViewController getInstance];這發生在initWithNibName在另一個類中執行之前發生。

IGRouteController我在那個方法我用的方法updateRouteList

[_mapViewController drawSuggestedRoute:suggestedRoute];

這一切都沒有運行,但我看不到結果。

如果我使用:

IGMapViewController *wtf = [IGMapViewController getInstance]; 
[wtf drawSuggestedRoute:suggestedRoute]; 

然後它的工作很大。

那麼是否有可能獲得一個實例和init以後用一個筆尖?

+3

你想達到什麼目的? – 2013-05-11 17:44:14

+0

獲得某個地方的實例。initWithNib並讓我得到的實例與使用initWithNib創建的實例相同。 – clankill3r 2013-05-11 21:22:18

+0

我曾與試圖有這樣的視圖控制器單身人士的應用程序,這是不愉快的,你想要做什麼? – 2013-05-12 11:10:42

回答

0

我相信我明白你在努力完成什麼。你想從一個筆尖初始化你的類的單例實例。正確?

初始化您的實例時,您使用的是[IGMapViewController new],這可能不是預期的行爲。這個怎麼樣(未經測試...)?

+ (id)sharedController 
{ 
    static dispatch_once_t pred; 
    static IGMapViewController *cSharedInstance = nil; 

    dispatch_once(&pred, ^{ 
     cSharedInstance = [[self alloc] initWithNibName:@"YourNibName" bundle:nil]; 
    }); 
    return cSharedInstance; 
} 
0

clankill3r,

你應該避免(在這個討論中UIViewController as a singleton見註釋)創造單UIViewController秒。這也被@CarlVeazey所強調。

恕我直言,你應該創建一個UIViewController每次你需要它。在這種情況下,你的視圖控制器將是一個可重用的組件。當你創建一個控制器的新的實例時,只需注入(雖然屬性或初始值設定項中您感興趣的數據,在這種情況下爲suggestedRoute)。

一個簡單的例子可能是以下幾點:

// YourViewController.h 
- (id)initWithSuggestedRoute:(id)theSuggestedRoute; 

// YourViewController.m 
- (id)initWithSuggestedRoute:(id)theSuggestedRoute 
{ 
    self = [super initWithNibName:@"YourViewController" bundle:nil]; 
    if (self) { 
     // set the internal suggested route, e.g. 
     _suggestedRoute = theSuggestedRoute; // without ARC enabled _suggestedRoute = [theSuggestedRoute retain]; 
    } 
    return self; 
} 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    [self drawSuggestedRoute:[self suggestedRoute]]; 
} 

如需進一步信息關於UIViewController S,我真的建議由@Ole Begemann閱讀兩個有趣的帖子。

希望有所幫助。