0

我有一个名为IGMapViewController

在那我有

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在一个类中使用。

IGRouteController在以 init 方法命名的类中,我使用_mapViewController = [IGMapViewController getInstance];这发生initWithNibName在另一个类中执行之前。

IGRouteController我使用的那个方法中有一个方法updateRouteList

[_mapViewController drawSuggestedRoute:suggestedRoute];

这一切都运行了,但我看不到结果。

如果我使用:

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

然后它确实工作得很好。

那么是否有可能获得一个实例并稍后使用 nib 进行初始化?

4

2 回答 2

0

我相信我看到了你想要完成的事情。您想从 nib 初始化您的类的单例实例。正确的?

当您初始化实例时,您使用[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;
}
于 2013-05-12T10:51:38.950 回答
0

clankill3r,

您应该避免创建单例UIViewController(请参阅本讨论UIViewController as a singleton中的评论)。@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]];
}

有关UIViewControllers 的更多信息,我真的建议阅读@Ole Begemann的两篇有趣的帖子。

希望有帮助。

于 2013-05-13T08:16:22.093 回答