简体   繁体   English

自定义initWithNibName

[英]customize initWithNibName

I want to have a custom initWithNibName , basically passing in another NSString as a type to determine some logic inside this UIViewController based on the type. 我想要一个自定义的initWithNibName ,基本上将另一个NSString作为类型传递,以根据类型确定此UIViewController内部的某些逻辑。 So I set is as follows: 所以我设置如下:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil andFeedType:(NSString *)feedType
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

Does this even make sense? 这有道理吗? As I don't see this type of init's quite often. 我不经常看到这种类型的初始化。 If not then what is the best way to do this? 如果不是,那么最好的方法是什么?

It makes perfectly sense to me. 这对我来说很有意义。 This is the way you would override an initializer to add some custom initialization in Objective-C. 这是您覆盖初始化程序以在Objective-C中添加一些自定义初始化的方法。 What do you think is wrong with it ? 您认为这有什么问题?

Yes it makes sense. 是的,这很有意义。 In addition, if you want to keep clean your init you could do the following: 此外,如果要保持初始化状态,可以执行以下操作:

- (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;
}

For further info see the post initWithNibName-bundle-breaks-encapsulation by Ole Begemann. 有关更多信息,请参阅Ole Begemann撰写的 initWithNibName-bundle-breaks-encapsulation

Hope that helps. 希望能有所帮助。

Edit 编辑

If that feed property cannot be accessed by external objects, create a class extension for your controller like the following: 如果外部对象无法访问该feed属性,请为您的控制器创建一个类扩展,如下所示:

//.m
@interface YourController ()

@property (nonatomic, copy) NSString* myFeedType;

@end

@implementation YourController

@synthesize myFeedType;

@end

It does make sense. 确实有道理。 You are creating you own initializer, tailored to your needs. 您将根据自己的需要创建自己的初始化程序。 Also, you are doing what you should, which is calling the designated initializer (in the case of UIViewController initWithNibName:bundle: ) inside your custom init method. 另外,您正在做您应该做的事情,这是在自定义init方法中调用指定的初始化程序(对于UIViewController initWithNibName:bundle: UIViewController

Wait! 等待! There is one reason why it may not be best: this method is not called when your view controller is loaded from a storyboard. 原因可能不是最好的一个原因是:从情节提要加载视图控制器时, 不会调用此方法。 For this reason I recommend using viewDidLoad: instead for the custom logic, and setting your custom string as a property. 因此,我建议使用viewDidLoad:代替自定义逻辑,并将自定义字符串设置为属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM