我想要有一个自定义的initWithNibName,基本上是传入另一个NSString作为类型,以基于该类型确定此UIViewController中的某些逻辑。所以我设置如下:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil andFeedType:(NSString *)feedType
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}这有什么意义吗?因为我不经常看到这种类型的初始化。如果不是,那么最好的方法是什么?
发布于 2012-06-20 04:16:41
这对我来说非常有意义。这是在Objective-C中重写初始化器以添加一些自定义初始化的方法。你认为它有什么问题?
发布于 2012-06-20 04:21:17
是的,这是有道理的。此外,如果你想保持你的init干净,你可以做以下事情:
- (id)initWithFeedType:(NSString *)feedType
{
self = [super initWithNibName:@"YourNibName" bundle:nil]; // nil is ok if the nib is included in the main bundle
if (self) {
// Set your feed here (copy it since you are using a string)
// see the edit
myFeedType = [feedType copy];
}
return self;
}有关更多信息,请参阅Ole Begemann发布的initWithNibName-bundle-breaks-encapsulation。
希望这能有所帮助。
编辑
如果外部对象无法访问提要属性,请为控制器创建一个类扩展,如下所示:
//.m
@interface YourController ()
@property (nonatomic, copy) NSString* myFeedType;
@end
@implementation YourController
@synthesize myFeedType;
@end发布于 2012-06-20 04:16:12
这是有道理的。您正在创建自己的初始化器,为您的需求量身定做。此外,您正在做您应该做的事情,即在自定义初始化方法中调用指定的初始化器(在UIViewController initWithNibName:bundle:的情况下)。
https://stackoverflow.com/questions/11108637
复制相似问题