Init a ViewController with a value
I just created a new view controller for my iphone app.
The view controller is triggered when user tap down a button.
The designated initializer for view controller is the default (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
.
I would an initializer like initWithID:(NSInteger)id
but how to call the des开发者_如何学运维ignated initializer?
I don't like the portability provided by constructing a view controller using
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil;
So I often only use it internally anyway but it may look something like this
- (id)initWithId:(NSString *)identification
{
self = [super initWithNibName:@"nibName" bundle:nil];
if (self) {
_identification = identification;
}
return self;
}
Note you shouldn't use id
as a name as it is a type and therefore is confusing
If view controller A
is constructing view controller B
I like to think that if my code is loosely coupled enough then B
should have a better idea than A
as to what nib B
should load.
Make a method in the .h file called:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil ID:(NSInteger)idNumber;
And then in the .m file, implement the method as:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil ID:(NSInteger)idNumber; {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if(self != nil){
// use the idNumber here!
}
return self;
}
Edit: I used id
for the NSInteger
as he used it in his question. I changed it to idNumber
now, as people didn't seems to like it.
Hope that helps!
You can do it like so:
.h file
-(id)initWithID:(NSInteger)id;
.m file
-(id)initWithID:(NSInteger)id{
self = [super initWithNibName:@"nib name" bundle:nil];
if(self){
//do what you want with the id
}
return self;
}
The standard way to do this is to use a property (at least that is how it is done in most of Apple's sample code).
In .h:
@interface MyViewController {
NSInteger viewID;
}
@property (assign) NSInteger viewID;
@end
In .m:
@synthesize viewID;
In the View Controller that pushes it:
MyViewController *controller = [[MyViewController alloc] init];
controller.viewID = integerValue;
// and push the view controller
BTW, if the nib name is the same as the class name, just alloc-init will have the same effect.
精彩评论