首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >initWithNibName之前的getInstance:

initWithNibName之前的getInstance:
EN

Stack Overflow用户
提问于 2013-05-12 01:29:28
回答 2查看 387关注 0票数 0

我有一个名为IGMapViewController的类

因为我有

代码语言:javascript
复制
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;
}

如果在多个类中使用对象,但仅在一个类中使用initWithNibName

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

IGRouteController中,我使用方法中有一个updateRouteList方法:

[_mapViewController drawSuggestedRoute:suggestedRoute];

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

如果我使用:

代码语言:javascript
复制
IGMapViewController *wtf = [IGMapViewController getInstance];
[wtf drawSuggestedRoute:suggestedRoute];

那么它确实工作得很好。

那么有没有可能获得一个实例,然后用nib初始化它呢?

EN

回答 2

Stack Overflow用户

发布于 2013-05-12 18:51:39

我相信我知道你想要实现什么。你想从一个nib初始化类的一个单例实例。对,是这样?

初始化实例时,您使用的是[IGMapViewController new],这可能不是预期的行为。这个(未经测试的……)怎么样?

代码语言:javascript
复制
+ (id)sharedController
{
    static dispatch_once_t pred;
    static IGMapViewController *cSharedInstance = nil;

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

Stack Overflow用户

发布于 2013-05-13 16:16:22

clankill3r,

您应该避免创建单独的UIViewController(请参阅本讨论UIViewController as a singleton中的注释)。@CarlVeazey也强调了这一点。

我想,你应该在每次需要的时候创建一个UIViewController。在这种情况下,视图控制器将是一个可重用的组件。当您创建控制器的实例时,只需注入(通过属性或在初始化器中注入您感兴趣的数据,在本例中为suggestedRoute )。

下面是一个简单的例子:

代码语言:javascript
复制
// 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的更多信息,我真的建议阅读@Ole Begemann的两篇有趣的帖子。

  • Passing Data Between View Controllers
  • initWithNibName:bundle: Breaks Encapsulation

希望这能有所帮助。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16499882

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档