Reputation: 8977
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. 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?
Upvotes: 2
Views: 1402
Reputation: 33428
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.
Hope that helps.
Edit
If that feed property cannot be accessed by external objects, create a class extension for your controller like the following:
//.m
@interface YourController ()
@property (nonatomic, copy) NSString* myFeedType;
@end
@implementation YourController
@synthesize myFeedType;
@end
Upvotes: 2
Reputation: 18290
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.
Upvotes: 0
Reputation: 164341
It makes perfectly sense to me. This is the way you would override an initializer to add some custom initialization in Objective-C. What do you think is wrong with it ?
Upvotes: 2
Reputation: 25011
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.
Upvotes: 1