我有一个名为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;
}如果在多个类中使用对象,但仅在一个类中使用initWithNibName。
在init方法的名为IGRouteController的类中,我使用_mapViewController = [IGMapViewController getInstance];,这发生在initWithNibName在另一个类中执行之前。
在IGRouteController中,我使用方法中有一个updateRouteList方法:
[_mapViewController drawSuggestedRoute:suggestedRoute];
这一切都在运行,但我看不到结果。
如果我使用:
IGMapViewController *wtf = [IGMapViewController getInstance];
[wtf drawSuggestedRoute:suggestedRoute];那么它确实工作得很好。
那么有没有可能获得一个实例,然后用nib初始化它呢?
发布于 2013-05-12 18:51:39
我相信我知道你想要实现什么。你想从一个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-13 16:16:22
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]];
}关于UIViewController的更多信息,我真的建议阅读@Ole Begemann的两篇有趣的帖子。
希望这能有所帮助。
https://stackoverflow.com/questions/16499882
复制相似问题