I've tried several ways that i've found here but none have worked. what would be an easy way to pass this NSMutalbeArray into another View controller?
NSMutableArray *pph = [[NSMutableArray alloc] init];
[pph addObject:[NSString stringWithFormat:#"%d %d %d",diario.Cowid,diario.Lact,diario.Del]];
on the same file below i have
- (IBAction)masInfoPPH;
{
tipo = #"PPH";
adiario = pph;
NSLog(#"\n Array adiario: %#",pph);
DetDiarioViewController *DetDiarios = [[DetDiarioViewController alloc] initWithNibName:nil bundle:nil];
[self.navigationController pushViewController:DetDiarios animated:YES];
}
for some reason pph (the NSMutalbeArray) gets here as null but up there it does give me the objects it should have. adiario is a global array or at least its supposed to be. Help!
There really are no global arrays. Create a property in your class for pph in the interface of your class.
#property(nonatomic, strong) NSMutableArray *pph;
self.pph = [[NSMutableArray alloc] init];
[self.pph addObject:[NSString stringWithFormat:#"%d %d %d",diario.Cowid,diario.Lact,diario.Del]]
But you still need to get that into next view controller. Create a similar property in it's interface and then set it before pushing
DetDiarioViewController *detDiarios = [[DetDiarioViewController alloc] initWithNibName:nil bundle:nil];
detDiarios.pph = self.pph;
[self.navigationController pushViewController:detDiarios animated:YES];
BTW - in objective-c the convention is to use a lowercase letter for the first letter of an instance
The scope of your pph array is unclear from your description.. But ANYTHING declared inside a single method is LOCAL to that method, unless it is returned BY that method.
You have several options... Declare the array as an instance variable, ie..
#interface YourClass: NSObject { NSMutableArray *pph; }
or
#implementation YourClass { NSMutableArray *pph; }
or as a static variable (in your .m file) (which would enable you to access the value from Class (+) methods..
static NSMutableArray *pph = nil;
or most preferably... as a property
#interface YourClass #property (strong) NSMutableArray *pph;
which you can then call upon from any instance method via the automatically synthesized Ivar _pph, or via the property's accessors.. self.pph.
Hope this helps!
Related
I have a NSMutableArray of a class, and in other class I'd like to initialize it and add various objects. But the problem is that the NSMutableArray isn't retaining the elements. I have the following code:
-(void)viewDidLoad
{
[super viewDidLoad];
MyStops *myStops = [self.storyboard instantiateViewControllerWithIdentifier:#"My Stops"];
myStops.myStopsMArray = [[NSMutableArray alloc] init];
}
And this one:
- (void) addToFavourites:(id)sender
{
UITapGestureRecognizer *gesture = (UITapGestureRecognizer *) sender;
NSInteger tag = gesture.view.tag;
UITableViewCell *cell = [stopsTable dequeueReusableCellWithIdentifier:#"cell"];
MyStops *myStops = [self.storyboard instantiateViewControllerWithIdentifier:#"Mis Paradas"];
[myStops.myStopsMArray addObject:[stopsArray objectAtIndex:tag]];
}
And in the other file I have the NSMutableArray declared and synthesized:
//Header file
#property (nonatomic, retain) NSMutableArray *myStopsMArray;
//Implementation file
#synthesize myStopsMArray;
Can you tell me please what I'm doing wrong?
Thanks!
instantiateViewControllerWithIdentifier creates and returns NEW INSTANCE every time!
So you must have a direct pointer to that view controller.
In the header file of your current class make a property like:
#property (strong, nonatomic) MyStops *myStopsVC;
NOTE:
Change strong to weak if your current ViewController already presented from MyStops. But if you're going to push/present MyStops from this vc, then keep it as strong pointer.
You have two distinct instances of your MyStops ViewController, that's why.
In you viewDidLoad, you create a MyStops ViewController then
alloc/init its "myStopsMArray" NSMutableArray.
But in you addToFavorites method, you create another, different and brand new MyStops instance — for which you didn't alloc/init you myStopsMArray property. Hence in that method, myStops.myStopsMArray is still nil.
I have a main ViewController that contains a desginated class. Within that ViewController there is a Container that is linked to an embed ViewController. Within that embed ViewController I am creating an NSMutableArray. I am not trying to access that array inside the main ViewController. I know that if I use:
create_challenge_peopleSelect *myScript = [[create_challenge_peopleSelect alloc] init];
NSLog(#"%#",myScript.selectedCells);
The NSLog will output null because I am creating a new ViewController and that gets rid of the already set array. So my question is how can I access that array without overwriting it?
UPDATE:
Heres where the NSMutableArray is being created:
create_challenge_peopleSelect.h:
#property (strong, nonatomic) NSMutableArray *selectedCells;
create_challenge_peopleSelect.m:
if([selectedCells containsObject:label.text])
{
cell.accessoryType = UITableViewCellAccessoryNone;
[selectedCells removeObjectIdenticalTo:label.text];
}
else
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
[selectedCells addObject:label.text];
}
This class is the container class off the main ViewController
No I want to access the selectedCells within my main ViewController, I have been doing things such as:
create_challenge_peopleSelect *myScript = [[create_challenge_peopleSelect alloc] init];
I would prefer to stay away from the App Delegate If possible.
You seem to be unclear on the difference between classes and instances. OK, so, say we have two NSArrays:
NSArray *a = [[NSArray alloc] initWithObjects:#"hello", #"I", #"am", #"an", #"array", nil];
NSArray *b = [[NSArray alloc] initWithObjects:#"so", #"am", #"I", nil];
If I do a.count, I'll get 5 as the answer because the array contains five objects. Meanwhile, if I do b.count, I'll get 3, because that array contains three objects. It isn't that creating b "gets rid of the already set count". They are separate objects completely unrelated to each other.
Your view controller class is the same way. When you create a different instance, it doesn't overwrite the old one -- it's just not the same object. In order to use the original view controller object, you need to get a reference to it.
So how do you get a reference to it? Well, the general answer is you design your app so that the two objects know about each other. There are lots of specific ways to accomplish this. A lot of people will say "Just stick a reference in the app delegate." That is one thing you can do, but it's not always the best choice. It can get out of control if you just stick everything in your app delegate. Sometimes it's the right answer, often other things are the right answer. Another approach is to have an object that knows about both of those objects introduce them to each other. But sometimes there is no such object. So it's situational.
Basically, instead of creating a new view controller, you need to maintain a pointer to the original.
I suggest storing an instance of your UIViewController in the AppDelegate in order to retain the particular instance of the view controller you've created by making it a global variable.
ex. In the App Delegate.h
#import "ViewController.h"
#class ViewController;
#interface AppDelegate : UIResponder <UIApplicationDelegate>
#property (nonatomic) ViewController *viewController;
Then from whatever view controllers' .m's from which you need to read/write to the variable, create a pointer to the application's app delegate, ex:
#import "AppDelegate.h"
#interface WhateverViewController ()
AppDelegate *mainDelegate;
- (void)viewDidLoad {
mainDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
}
So wherever you first create that view controller in your code (before ever using it), initialize it using this global variable. ex. If you're using xibs:
mainDelegate.viewController = [[UIViewController alloc] initWithNibName:#"ViewController" bundle:nil];
[self.navigationController pushViewController:mainDelegate.viewController animated:YES];
ex. If you're using storyboards:
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"StoryboardName" bundle:nil];
mainDelegate.viewController = [storyboard instantiateViewControllerWithIdentifier:#"viewControllerID"];
[self.navigationController pushViewController:mainDelegate.viewController animated:YES];
(This is assuming it's in a place other than the app delegate in which case the pointer to the App Delegate isn't needed.)
Then when accessing the array from another UIViewController use
mainDelegate.viewController.array
To access the NSMutableArray from one class to another class use following code.
In the first view controller in which u have declared the object of NSMutableArray, declare the property and synthesize for the same as below,
//In FirstViewcontroller.h class,
#property (nonatomic, strong) NSMutableArray *arrData;
//In FirstViewcontroller.m class
#synthesize arrData;
Also FirstViewcontroller object should be global so you can create the object of FirstViewcontroller in app delegate file.
//appdelegate.h
#property (nonatomic, strong) FirstViewcontroller *objFirst;
//appdelegate.m
#synthesize objFirst;
FirstViewcontroller *objFirst=[[FirstViewcontroller alloc]init];
Now in SecondViewcontroller in which you have to access array,
create the share object of Appdelegate file
//SecondViewcontroller.m
AppDelegate *app = (AppDelegate*)[[UIApplication sharedApplication] delegate];
Then use will get the required array as below,
app.objFirst.arrData
This is your required array I hope it will help you.
The basic idea here is that in your original class, the array is referred to by a pointer. Your original class would allocate it and presumably load it. Other parts of your program can be handed the contents of the property, which is a pointer, assign that to their own pointer holder, and use it as if you had declared it there. Please use the above code;
MyClass *aClass = [[MyClass alloc] initWithMyInitStuff];
NSMutableArray *ThatArray = aClass.MyArray;
NSLog("Count of ThatArray: %d", [That.Array count]);
What you've done in the code provided is set a public property for a mutable array...
#property (strong, nonatomic) NSMutableArray *selectedCells;
The NSMutableArray is not "created" by setting that property. At some point in your code you also have to create the NSMutableArray by initialising...
NSMutableArray *selectedCells = [[NSMutableArray alloc] init];
or by using a convenience method such as...
NSMutableArray *selectedCells = [NSMutableArray arrayWithCapacity:(NSUInteger)<initialising capacity>];
or
NSMutableArray *selectedCells = [NSMutableArray arrayWithArray:(NSArray *)<initialising array>];
Initialising an NSMutableArray is often done only once. If it is repeated, the contents are overwritten against the property used to point to the array. As such, a useful location for this is often within the viewDidLoad view controller lifecycle method.
I am trying to use a NSMutableArray that I have created in ViewController in an ViewController2. But it is just returning nil.
Here is my ViewController.h file:
#property (nonatomic, strong) NSMutableArray *total_hours;
Here is my ViewController.m file:
total_hours = [[NSMutableArray alloc] init];
I also add object. Use NSLog to display that this have actually been added, so that is working. But now I try to use NSLog to display them again in the other ViewController2.
Here is my ViewController2.h file:
#property(nonatomic, assign)NSMutableArray*total_hours_copy;
here is my ViewController2.m file:
#import "TimelisteViewController.h"
// some auto enabled code
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
TimelisteViewController *test = [[TimelisteViewController alloc]init];
NSMutableArray *total_hours_copy = test.total_hours;
NSLog(#"%#", [total_hours_copy objectAtIndex:0]);
}
Why is this not working?
Your question implies that you create the array in ViewController and want to later pass it to ViewController2. However, in ViewController2's viewDidLoad method, you create a new instance of ViewController. So that's a problem.
It would be easier to answer your question if :
You indicated in which method total_hours is initialized.
How control is transferred between the 2 controllers.
You are not initializing you array in the right place. viewDidLoad is only called when the view controller is shown, not at the initialization.
You could override init method in your view controller :
- (void)init{
[super init];
total_hours = [[NSMutableArray alloc] init];
}
However this is not a usual pattern, and i won't recommend it. I'm not sure what you're trying to do, but i believe it would be best to initialize you array in your viewcontroller2 and pass it after to your newly initialize controller.
TimelisteViewController *test = [[TimelisteViewController alloc]init];
NSMutableArray *total_hours = [[NSMutableArray alloc] init];
//Add your data in the array
test.total_hours = total_hours;
Based on the fact that Paul Lalonde has made good considerations, if you need to pass the array from a view controller to another you can follow two ways.
Create a singleton class that would share the array (in this way each controller can access to that singleton and hence to that array)
Inject the array from a controller to another (preferred way since it allows decoupling components and having less application rigidity)
So, following the second solution, from ViewController1 you inject the array like the following snippet. Now both controller will share the same array. Modifications made by one controller will be visible to the other and vice versa...
ViewController2 secondController = // alloc-init here…
secondController.sharedArray = [self sharedArray];
where ViewController2 would have a property like
#property (nonatomic, strong) NSMutableArray* sharedArray;
Then, for example, within its viewDidLoad or wherever you want you can say
[self.sharedController add…]
Said this, what it your application flow? For example, is ViewController2 a controller that is displayed after ViewController1 through a UINavigationController or something similar?
total_hours_copy is a local variable in your viewDidLoad method, not a property!. Change your code to
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
TimelisteViewController *test = [[TimelisteViewController alloc]init];
self.total_hours_copy = test.total_hours;
// or maybe self.total_hours_copy = [test.total_hours copy];
NSLog(#"%#", [total_hours_copy objectAtIndex:0]);
}
i'm not new to OOP but i'm very new to objective c and i've been having trouble with reaching model from two different view controllers, one to set it the other to get the data. Here's my model:
#import <Foundation/Foundation.h>
#interface ModelUnit : NSObject{
NSString * nickname;
int total;
}
- (void)setTotal:(int)newTotal;
- (void)setName:(NSString *)nick;
- (NSString *)getName;
#end
#import "ModelUnit.h"
#implementation ModelUnit
- (void)setTotal:(int)newTotal{
total = newTotal;
}
- (void)setName:(NSString *)nick{
nickname = nick;
}
- (NSString *)getName{
return nickname;
}
#end
Here's how i try to set nickname in the initial viewcontroller:
//.h
#interface introViewController : UIViewController{
ModelUnit * modl;
}
-(ModelUnit *) modl;
-(IBAction)nickEntered:(UITextField *)sender;
#end
//.m
-(ModelUnit *) modl{
if(!modl){
modl = [[ModelUnit alloc] init];
}
return modl;
}
- (IBAction)nickEntered:(UITextField *)sender{
[[self modl] setName:[sender text]];
ViewController *vew = [[ViewController alloc] initWithNibName:nil bundle:nil];
[self presentViewController:vew animated:NO completion:Nil];
}
And here is how i try to receive and display it in the last viewcontroller:
- (void)viewDidLoad
{
[super viewDidLoad];
introViewController *pnt = [[introViewController alloc] initWithNibName:nil bundle:nil];
[display setText:[[pnt modl] getName]];
}
But it always prints it as null when i NSlog it to the console. I know it's a very novice question but i'm completely stuck. Thanks for any help.
It's because each of your UIViewController instances are referencing different instances of your model class (actually, a non-instance in the second case).
Make an #property in your "last" view controller (class name of "ViewController" it would seem), something like:
#property (strong, nonatomic) Model *model;
Then, when pushing your second view controller, set its model property, like this:
ViewController *vew = [[ViewController alloc] initWithNibName:nil bundle:nil];
vew.model = self.modl;
[self presentViewController:few animated:NO completion:NULL];
That way, you're passing around the same instance of your Model class. The way you're doing it, you're trying to access a property that was never initialized, which is why you're getting nil.
If you're not new to OOP, you should quite easily see the mistake you're making. You're trying to retrieve a value out of an object you just initialized.
Where you need to pass the data is in the first object as you initialized the second object.
Between this line:
ViewController *vew = [[ViewController alloc] initWithNibName:nil bundle:nil];
And this line:
[self presentViewController:vew animated:NO completion:Nil];
You're still in the first object and you hold a reference to the second object. Give the ViewController class (a better name and) a NSString property to hold the data the getName method returns. And then set that property between the two lines I posted.
Also, Objective-C doesn't name their getters with get.
I've declared a property in the .h file called cellTitles. In my .m file, I have a method as follows:
-(NSArray *)cellTitles
{
if(!_cellTitles){
_cellTitles = [[NSArray alloc] initWithObjects:#"several strings", nil];
NSLog(#"Home Array Created");
}
return _cellTitles;
}
But the array is not created when I refer to _cellTitles or self.cellTitles. I have several NSLogs that all say the array has 0 objects. Do I need more than this. Some answers have said I need to synthesize, but as I understand it, that is no longer necessary.
Make sure your property is assigned strongly.
#property (nonatomic, strong) NSArray *cellTitles;