Adding to a NSMutableArray - ios

I can't find an obvious answer this. I'm trying to add things to an array, so I assume I need to use an NSMutableArray
I have a ViewController (CVDownload) and and a TableViewController(CVTableViewController). The NSMutableArray is declared in CVTableViewController.h
#property (strong, nonatomic) NSMutableArray *cvFiles;
I then try to add a string to it in the CVDownload.m
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
CVTableViewController *controller = (CVTableViewController *)segue.destinationViewController;
[controller.cvFiles addObject:(#"sdsd")];
}
That doesn't work. I'm assuming because I haven't initialised the array. I've tried initialising the array in CVDownload.m
NSMutableArray *cvFiles = [NSMutableArray array];
but that doesn't work either. In debug, the array is still nil. I don't understand where I'm going wrong.
Basically, my goal is to have an array in CVTableViewController that is used to populate a Table, and I want to be able to add to the array in CVDownload. Is there something I'm missing? Does NSArray have a similar method to NSString's stringByAppendingString?

In the init method of CVTableViewController write this:
self.cvFiles = [NSMutableArray new];

CVTableViewController *controller = (CVTableViewController *)segue.destinationViewController;
if(nil == controller.cvFiles)
{
controller.cvFiles = [[NSMutableArray alloc] init];
}
[controller.cvFiles addObject:(#"sdsd")];

Where are you initializing the array? Are you sure that it is created before prepareForSegue: is called?
// Edit: I ask because, as confirmed in the comments, the array is initialized after prepareForSegue: is called. The fix, as mentioned there, is to initialize the array in -awakeFromNib instead of -viewDidLoad.

Related

Using Text Field to add String to NSMutableArray

I am looking to get an NSString value from a Text Field and add it to an array, I want to build an array with many strings in it ex:
[hello, goodbye, too soon].
This is my current solution:
- (IBAction)submitButton:(id)sender {
NSMutableArray *wordArray = [[NSMutableArray alloc] init];
NSString *input = textField.text;
[wordArray insertObject:input atIndex:arrayIndex];
arrayIndex++;
}
This works for the first item in the array, but when I press submit again it reinitializes.My issue is how do I initialize the NSMutableArray to use in the button function, without having it in there so that it doesn't initialize every time. Thank you
Your are using a local array that disappears as soon as the submitButton method is finished.
Make your wordArray an instance variable and initialize it once in viewDidLoad. Then in your submitButton: method (and any others), you reference the instance variable instead of creating local arrays.
Honey's answer is almost, but not, correct.
Your code uses a local variable in your submitButton method, and creates a new, empty array each time the method gets called. Both of those things are wrong.
Honey's answer has you create a different local variable in viewDidLoad. That's also wrong.
You need to make wordArray an instance variable or property of your class. If you class is called ViewController, say, it might look like this
#interface ViewController: UIViewController;
#property (nonatomic, strong) NSMutableArray *wordArray
...
#end
And then initialize it in viewDidLoad:
- (void)viewDidLoad {
[super viewDidLoad];
self.wordArray = [[NSMutableArray alloc] init];
}
Then in the rest of your program refer to self.wordArray, the property.
Here's the solution,
#implementation ViewController{
NSMutableArray *_wordArray;
}
- (void)viewDidLoad {
[super viewDidLoad];
_wordArray = [[NSMutableArray alloc] init];
}
- (IBAction)submitButton:(id)sender {
NSString *input = textField.text;
[wordArray addObject:input];
}
You was re init the array each time you make the action, which will let you always save the last value of the textfield.
but this creates an array as global variable so that you can add all the values entered in textfield.
Hope this help you :)

How to store value in NSMutableArray from ViewControllers

I'm tying to solve my problem which is, i don't know how to store value from (for ex) 4 viewControllers and keep it in the last one. It should be like the scorecard, in first quarter I earned 4pt (and write it in TextField), in second quarter 5pt etc. In the last one it should be summed and sorted etc.
i stared from the last ViewController called it Result, another four called first, second etc.
In Result i created
#property(strong, nonatomic) NSMutableArray *array;
first, second etc inherits array from result and for First I created:
-(void) prepereForSegue:(UIStoryboardSegue*)segue sender :(id)sender
{
if ([segue.identifier isEqualToString:#"id1"]) {
NSString *str1 = [_firstResult text];
Result *Result1 = [segue destinationViewController];
Result1.array = [[NSMutableArray alloc]init];
[Result1.array addObject:str1];
}
}
for second:
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([segue.identifier isEqualToString:#"id2"]) {
NSString *str2 = [_SecondResult text];
Result *Result1 = [segue destinationViewController];
Result1.array = [[NSMutableArray alloc]init];
[Result1.array addObject:str2];
}
}
When I run the project in array is just the last score from fourth quarter.
I think that i shouldn't alloc and init NSMutableArray in each viewController but i don't know how make it work..
Please Help me.
Appreciate!
Yup, you are, every time creating a new array which have its current and single object.
Create a shared object and call that array to save and fetch values.
Or just create a array in appdelegate.
Each time you are creating a new array that's why array contains only last value. create an array in appDelegate or use shared object to save the results.

Access NSMutableArray in another class

I'm can see that there is a lot of questions regarding this already, but none of them seems to have given me an explanation to why I cannot access my array from another class.
Here's where I wan't to access the array
(XYZPaymentViewController.m)
- (void)viewDidLoad
{
[super viewDidLoad];
XYZMateOverviewViewController *test = [[XYZMateOverviewViewController alloc] init];
NSMutableArray *t = test.mates;
NSLog(#"Count of ThatArray: %d", [t count]);
}
Nomatter what - the log writes out 0 !!
In another class (XYZMateOverviewViewController.h) I declare the array
#property (retain) NSMutableArray *mates;
I synthesize the array in the implementation area in XYZMateOverviewViewController.m
#synthesize mates;
I hope you can help me understand what I'm doing wrong :)
If you want to access an array from another ViewController you have to pass the array between the ViewControllers.
For example:
You have two ViewControllers. 'A' and 'B', so u have to do this:
In the 'A' ViewController, is where you have the array that you want to send to another ViewController. Then create an instance of 'B' ViewController and send the array to him:
CODE OF 'A' ViewController:
NSMutableArray *arrayToSend = [[NSMutableArray alloc]init];
BViewController *bViewController = [[BViewController alloc]initWithNibName:#"BViewController" bundle:nil];
BViewController.arrayReceived = arrayToSend;
[self.view addSubView:BViewController.view];
After, in your BViewController you just have to take your arrayReceived and use it.
CODE OF 'B' ViewController:
NSLog(#"%#", [arrayReceived objectAtIndex:0]); // For example.
Hope i did help you, if u have any question tell me.
What are you doing with the mates array in the XYZMateOverviewViewController init method?
If you're not adding any data to it a count of 0 is just right.
With the line
XYZMateOverviewViewController *test = [[XYZMateOverviewViewController alloc] init];
you are creating a completely new instance of XYZMateOverviewViewController—one that has nothing to do with any other part of your application*. What you should be doing instead is getting a reference to the already-set-up instance of the view controller. That instance presumably has its mates property set up with the data you want.
The general topic of sharing data between different parts of your application—and between different view controllers, in particular—should be covered somewhere toward the beginning of any “introduction to iOS programming” book or tutorial.
* Unless you’re doing something funky with singletons or shared state, of course, but I doubt that’s the case here.
Do you alloc/init the mutable array in the init method?

NSArray losing value at the end of method

I have a project I am working on, to learn some more about JSON and restkit. It all is working great, however I am having trouble with an array losing it's values.
This is the last method that is executed in my network request.
SHRetrieveStoresWS.m
- (void)objectLoader:(RKObjectLoader *)objectLoader didLoadObjects:(NSArray *)objects
{
self.stores = [[NSArray alloc] initWithArray:objects];
StoresViewController *viewController = [[StoresViewController alloc] init];
[viewController didLoadObjects:objects];
for (Store *aStore in stores) {
NSLog(#"%#", [aStore longName]);
}
}
Which calls this method in my view controller.
StoresViewController.m
#property (strong, nonatomic) NSArray *data;
- (void)didLoadObjects:(NSArray *)aArray
{
NSLog(#"%d", aArray.count);
self.data = [[NSArray alloc] initWithArray:aArray];
NSLog(#"%d", data.count);
[self.tableView reloadData];
}
The values are correct when I ask for the values within this method, but the array shows 0 objects immediately afterwards. Am I missing something here?
I am later checking the value with this method.
- (IBAction)pushMe:(id)sender
{
NSLog(#"Data: %d", self.data.count);
}
You should pass the data in the segue...
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if ([segue.identifier isEqualToString: #"MY_IDENTIFIER"]){
StoresViewController *viewController = segue.destinationViewController;
[viewController didLoadObjects: objects];
}
}
That should work for you! Just change MY_IDENTIFIER to whatever the identifier of your segue is.
StoresViewController is initialised as a local variable which is only accessible in the method that it was declared (aka objectLoader). After objectLoader has completed, the local variable is no longer valid.
The problem is most likely that you're creating multiple instances of StoresViewController instead of giving your network controller a reference to the original instance.
You can demonstrate it to yourself by printing out self in -viewDidLoad and again in didLoadObjects:. You'll see that the pointer addresses are different.
This line is the culprit:
StoresViewController *viewController = [[StoresViewController alloc] init];
Instead of instantiating StoresViewController again, add a property to your SHRetrieveStoresWS class and use it to hold a reference to your view controller.
#property (strong) StoresViewController *viewController;
You'll need to set that property before -didLoadObjects: is invoked.

Passing a MutableArray between ViewControllers

BookingDocumentsViewController *bdVc = [self.storyboard instantiateViewControllerWithIdentifier:#"BookingDocs"];
bdVc.orId = rl_id;
bdVc.docsArray = self.documentsArray;
[self.navigationController pushViewController:bdVc animated:YES];
I have Above code snippet. I'm trying to load a new viewcontroller and assign its Mutable Array (docsArray) object to current view's mutableArray (documentsArray <=this is not nil)
Whenever I execute above code I get EXC_BAD_ACCESS error.
but if I comment the 3rd line. It works but I can't get my array to the new view. I even tried with [[NSMutableArray alloc] initWithArray:self.documentsArray]; this doesnt work either.
But if I use bdVc.docsArray =[[[NSMutableArray alloc] init]; it works but again I can't get my mutable array to the new view.
Edit:
However 2nd line has NSString values. And they can be passed without a problem.
What am I doing wrong here?
I'm not getting any errors in console, instead I get this.
Maybe consider using a Segue. It instantiates the destination viewcontroller for you. Then in your source view controller implement
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
Get a reference to your destination viewcontroller and set its data.
BookingDocumentsViewController *bdVc = [segue destinationViewController];
bdVc.docsArray = self.documentsArray;
in BookingDocumentsViewController.h
#property(nonatomic, retain)NSmutableArray *docsArray;
You do can do in your BookingDocumentsViewController.m:
#synthesize docsArray;
- (void)viewDidLoad
{
NSmutableArray *array = [NSmutableArray alloc]initWithArray:docsArray];
[super viewDidLoad];
}
then when you are pushing the view
BookingDocumentsViewController *bdVc = [self.storyboard instantiateViewControllerWithIdentifier:#"BookingDocs"];
bdVc.orId = rl_id;
bdVc.docsArray = self.documentsArray;
[self.navigationController pushViewController:bdVc animated:YES];
[bdVc Release];
I think I found the issue. A very basic mistake. In bdVc's viewDidLoad I had the following line,
NSLog(#"Booking Documents viewDidLoad : %#",self.docsArray.count);
This was causing the error. that %# instead of %d. I wonder why xcode didn't show proper reason for the error.
Thank you all for the help. :)

Resources