How can I pass a parameter when initializing a UIViewController? - objective-c

I have two controllers, First- and SecondViewController. I want to share some methods of FirstViewController to use them in my SecondViewController.
This is how I create SecondViewController in FirstViewController:
sms = [[SecondViewController alloc] init];
UINavigationController *navController = [[UINavigationController alloc]
initWithRootViewController:sms];
[self presentModalViewController:navController animated:YES];
I thought of passing the current instance of the FirstViewController to the SecondViewController which extends UIViewController. By default the initWithNibName method of SecondViewController is called.
How do I achieve this in objective-c?

Im not completely sure I understand the problem... as part of the issue has to do with how you are instantiating SecondViewController... posting that code could help.
but to answer your question as you have asked it.... "how to pass FirstViewController into SecondViewController"...
in your SecondViewController.h create your own init method
-(id) initWithFirstViewController:(UIViewController *)theFirstViewController;
and in the .m file...
-(id) initWithFirstViewController:(UIViewController *)theFirstViewController
{
self = [super initWithNibName:#"myNibName" bundle:nil];
self.firstViewController = theFirstViewController; //this assumes you have created this property. Also, do NOT retain the first view controller or you will get circular reference and will secondviewcontroller will leak.
return self;
}
then.. and here is the key.. make sure you are calling the correct init method to instantiate SecondViewContoller
SecondViewController *svc = [[SecondViewController alloc]initWithFirstViewController:self];
now.. having said that.. looking at your SO rating, I have a feeling you already knew this.. and the real question may be... why is the initWithNibName being called when you are not actually calling it explicitly?

Not 100% sure what you are after. The content of your question about sharing methods doesn't seemt o match the question of passing in a parameter at init.
With regard to methods, you can call a method from your parentViewController
if ([self.parentViewController respondsToSelector:#selector(someMethod)]) {
[self.parentViewController someMethod];
}
If you want to pass a parameter in on any class at init, you will want to write a custom init method with any additional parameters you want. That custom method should begin with the appropriate [self init] call. You can even have multiple custom init methods which can be handy.
Here is an example for class that downloads json or xml feeds.
- (id)initWithID:(NSString *)useID delegate:(id)setDelegate urlString:(NSString *)urlString feedIsJSON:(BOOL)feedIsJSON failedRetrySecondsOrNegative:(float)failedRetrySecondsOrNegative refreshSecondsOrNegative:(float)refreshSecondsOrNegative {
if ((self = [super init])) {
// Custom initialization
processing = NO;
self.delegate = setDelegate;
self.feedID = [NSString stringWithFormat:#"%#", useID];
self.feedURLString = [NSString stringWithFormat:#"%#", urlString];
self.isJSON = feedIsJSON;
if (failedRetrySecondsOrNegative>=0.0f) {
retryFailedSeconds = failedRetrySecondsOrNegative;
} else {
retryFailedSeconds = kFailedRefresh;
}
if (refreshSecondsOrNegative>=0.0f) {
refreshSeconds = refreshSecondsOrNegative;
} else {
refreshSeconds = kSuccededRefresh;
}
}
return self;
}
Hope this helps.

Related

How to get Class object without instance?

Is there any way to get the result of:
NSObject *a = [[NSObject alloc] init];
[a class];
Without instantiating?
I wish to pass Class object to function as argument, and check it then. Like this:
- (void) pushControllerOfClass: (Class) aClass
{
if([aClass isSubclassOfClass: *what should I write here?*]) {
...
}
}
Intuitively, I've tried to write
if([aClass isSubclassOfClass: UIViewController]) {
But it doesn't work.
Thx for future response.
Update:
Is such a function considered bad in ObjectiveC?
I've refactored code from Nahavandipoor's book iOS 5 Programming Cookbook.
It was like that:
- (void) pushSecondController{
SecondViewController *secondController = [[SecondViewController alloc]
initWithNibName:nil
bundle:NULL];
[self.navigationController pushViewController:secondController animated:YES];
}
As for me, this is kind of bad function:
It doesn't parametrized when it should be.
Try with:
if([aClass isSubclassOfClass:[UIViewController class]])
In answer to your question, you don't need an instance of an object to get its class. You can get it directly from the class like:
[NSString class];
[YourClass class];
However, if all you are wanting is a method that can push any view controller you give it, then you can just use UIViewController as the parameter type:
- (void)pushAnyViewController:(UIViewController *)viewController
{
[self.navigationController pushViewController:viewController animated:YES];
}
This will take any view controller that is a subclass of UIViewController and push it onto the navigation stack.
If you really want the method to handle the allocations as well you can do:
- (void)pushViewControllerClass:(Class)viewControllerClass
{
if ([viewControllerClass isSubclassOfClass:[UIViewController class]])
{
id viewController = [[viewControllerClass alloc] initWithNibName:nil bundle:nil];
[self.navigationController pushViewController:viewController animated:YES];
}
}
And call it like this:
Class viewControllerClass = [MyViewController class];
[self pushViewControllerClass:viewControllerClass];
Just make sure that the nib is named the same as the class if you are using one.
You can write [UIViewController class] to get the class object.
There should be a class method on most classes to get the class.
If you find yourself doing this often, perhaps revisit your design?

Custom NSObject class, instantiate like [CustomObj customObjWithData:data] [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Class methods which create new instances
I am wondering how to emulate the instantiation of classes like NSString, NSArray and such like this: [NSArray arrayWithObject:object]... in hope of eliminating inits and allocs.
I may not be familiar with what that actually does. According the the Documentation, [NSSArray array] creates and returns an empty array. What does that really mean, any allocations?
I want to be able to have a custom NSObject class and do: [CustomObj customObjWithData:data]
Thanks!
First write a corresponding custom init... method:
- (id)initWithFoo:(Foo *)aFoo
{
// Do init stuff.
}
Then add a custom factory method that calls alloc and your custom init... method:
+ (id)customObjWithFoo:(Foo *)aFoo
{
return [[[self alloc] initWithFoo:aFoo] autorelease];
}
If compiling with ARC, omit the autorelease call.
Those are class-methods. Usually, they also have instance init* methods as well. For example...
- (id)initWithData:(NSData*)data
{
// Call appropriate super class initializer
if (self = [super init]) {
// Initialize instance with the data
}
return self;
}
+ (id)customObjWithData:(NSData*)data
{
return [[self alloc] initWithData:data];
}
Now, you can call it...
CustomObj *obj = [CustomObj customObjWithData:data];
You would need to do something like...
+ (CustomObj *)customObjWithData:(NSData *)data {
return [[[CustomObj alloc] initWithData:data] autorelease];
}
...and implement an initWithData: to handle initialization of variables.
Al lot of answers here are correct. I self always create a method for easy alloc en instantiation through Storyboard-instantiation:
//FooViewController.m
+ (id)create
{
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"Storyboard" bundle:nil];
return [storyboard instantiateViewControllerWithIdentifier:#"FooViewController"];
}
+ (UINavigationController *)createWithNavagionController
{
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"Storyboard" bundle:nil];
FooViewController *fooViewController = [storyboard instantiateViewControllerWithIdentifier:#"fooViewController"];
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:fooViewController];
return navigationController;
}
And if you need parameter, create class-methods like: createWithName:(NSString *)name

NSMutableArray as instance variable alway null

After many hours wasted, I officially turn to the experts for help!
My problem lies with using a NSMutableArray as an instance variable, and trying to both add objects and return the array in a method in my class. I am obviously doing something fundamentally wrong and would be grateful for help...I have already tried all the suggestions from other similar questions on stackoverflow, read apples documentation, and basically all combinations of trial and error coding I can think of. The mutable array just alway returns (null). I've even tried creating properties for them, but still the array returns (null) and then I also am running into memory management problems due to the retain while setting the property, and the init in the init method for the class.
Here is what I am trying to do:
1) Loop through a series of UISwitches and if they are 'switched on', add a string to the NSMutableArray
2) Assign this mutable array to another array in another method
Any help much appreciated,
Andy
And for some code...
fruitsViewController.h
#import <UIKit/UIKit.h>
#interface fruitsViewController : UIViewController
{
NSMutableArray *fruitsArr;
UISwitch *appleSwitch;
UISwitch *orangeSwitch;
}
#property (nonatomic,retain) NSMutableArray *fruitsArr; // ADDED ON EDIT
#property (nonatomic,retain) IBOutlet UISwitch *appleSwitch;
#property (nonatomic,retain) IBOutlet UISwitch *orangeSwitch;
- (IBAction)submitButtonPressed:(id)sender;
#end
fruitsViewController.m
#import "fruitsViewController.h"
#implementation fruitsViewController
#synthesize fruitsArr; // ADDED ON EDIT
#synthesize appleSwitch, orangeSwitch;
/* COMMENTED OUT ON EDIT
-(id)init
{
if (self = [super init]) {
// Allocate memory and initialize the fruits mutable array
fruitsArr = [[NSMutableArray alloc] init];
}
return self;
}
*/
// VIEW DID LOAD ADDED ON EDIT
- (void)viewDidLoad
{
self.fruitsArr = [[NSMutableArray alloc] init];
}
- (void)viewDidUnload
{
self.fruitsArr = nil;
self.appleSwitch = nil;
self.orangeSwitch = nil;
}
- (void)dealloc
{
[fruitsArr release];
[appleSwitch release];
[orangeSwitch release];
[super dealloc];
}
- (IBAction)submitButtonPressed:(id)sender
{
if ([self.appleSwitch isOn]) {
[self.fruitsArr addObject:#"Apple"; // 'self.' ADDED ON EDIT
}
if ([self.orangeSwitch isOn]) {
[self.fruitsArr addObject:#"Orange"; // 'self.' ADDED ON EDIT
}
NSLog(#"%#",self.fruitsArr); // Why is this returning (null) even if the switches are on?!
[fruitsArr addObject:#"Hello World";
NSLog(#"%#",self.fruitsArr); // Even trying to add an object outside the if statement returns (null)
}
#end
It seems like your init function is never called. If you're initializing this view controller from a NIB, you need to use initWithCoder. If not, just declare your fruitsArr in viewDidLoad.
Use view did load instead of init...
- (void)viewDidLoad
{
fruitsArr = [[NSMutableArray alloc] init];
}
Change that init for viewDidLoad and see what happens
Is your init method ever being called (in complicationsViewController). Add a NSLog to check this, you might be calling initWithNib: maybe.
At viewDidUnload you should remove self.fruitsArr = nil;, or, if you want to keep it, then initialize the fruitsArr in viewDidLoad (and remove it from init).
because fruitsArr don't be init.
you should do this first:
fruitsArr = [[NSMutableArray alloc] init];
so, I think you don't run - (id)init before you use fruitsArr.

Passing objects to a different view

I have an object name usr. I want to change views and I want to pass it along to the new view. How can I pass this object?
RVUser *usr = [[RVUser alloc] init];
UIViewController* exampleController = [[exampleClass alloc] initWithNibName:#"RVListsController" bundle:nil];
if (exampleController) {
exampleController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:exampleController animated:YES];
if (exampleController.title == nil) {
NSLog(#"enters");
//exampleController.title = #"Revistas Destacadas";
}
[exampleController release];
}
}
One way of doing it is to declare a property of type RVUser on exampleClass and assign it to that property after creating exampleController.
You should set properties BEFORE using [self presentModalViewController:exampleController animated:YES];
RVUser *usr = [[RVUser alloc] init];
UIViewController* exampleController = [[exampleClass alloc] initWithNibName:#"RVListsController" bundle:nil];
if (exampleController) {
exampleController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
if (exampleController.title == nil) {
NSLog(#"enters");
//exampleController.title = #"Revistas Destacadas";
}
//TODO: Set exampleController properties, declared as #property (nonatomic, release) RVUser *passedUsr;
//exampleController.passedUsr = usr;
//[usr release];
[self presentModalViewController:exampleController animated:YES];
}
[exampleController release];
You'll want to declare the instance of ExampleController as your custom UIViewController instead of UIViewController - this will give you code completion and compile time warnings if you call a method/property on it that doesn't exit. Then, change your definition of exampleClass (read the naming convention guide also) to have a property of type RVUser, like so:
#property (nonatomic, retain) RVUser *user;
And in the implementation file:
#synthesize user;
Now you can pass your object to that controller before you display it:
ExampleController.user = usr;
You really should read the intro guides on the Apple developer site, they cover this and a lot more that you need to know if you want to write iOS apps.

obj-c, confusion why can't I add a setter to this class?

Normally I don't have any problem adding a setter method to a class.
However, I'm trying to add to library usage class, which must be causing the problem.
Heres the class I've added it to...
#interface GraphController : TKGraphController {
UIActivityIndicatorView *indicator;
NSMutableArray *data; //I've added
NSString *strChartType; //I've added
}
-(void)setContentType:(NSString*)value; //I've added
#end
#implementation GraphController
-(void)setContentType:(NSString*)value { //I've added
if (value != strChartType) {
[value retain];
[strChartType release];
strChartType = value;
NSLog(#"ChartType=%#", strChartType);
}
}
Heres where I'm getting a warning..
UIViewController *vc = [[GraphController alloc] init];
[vc setContentType:myGraphType]; //Warnings on this line see below
[self presentModalViewController:vc animated:NO];
[vc release];
myGraphType if defined in my constant class.
* Warnings *
warning: 'UIViewController' may not respond to '-setContentType:'
warning: (Messages without a matching method signature
I know the first warning appears when you haven't added the method to the implementation. but I have.
Where am I going wrong ?
UIViewController *vc = [[GraphController alloc] init];
means that vc points to an instance of GraphController but the variable itself is of type UIViewController *, and UIViewController doesn’t declare a -setContentType: method.
Replace that with
GraphController *vc = [[GraphController alloc] init];
to tell the compiler you’re working with a GraphController instance, and it will recognise your -setContentType: method.
You just have to let the compiler know that you're working with a class that it knows responds to the method. You can do it a couple of ways but the easiest one if you just want to eliminate the warning is to cast the object in line before you make the method call.
UIViewController *vc = [[GraphController alloc] init];
[(GraphController *)vc setContentType:myGraphType]; //No warning should appear now.
[self presentModalViewController:vc animated:NO];
[vc release];