Share a bool variable / NSNUmber between two view controllers - iphone

I have two view controllers and I want to share a bool variable between them.
So I create a bool variable with a #propery (nonatomic, assign) on both sides and on the one side I wrote
newVC.myBool1 = self.myBool2;
On the other view controller I can read the value of the passed bool variable, but I need to change it at the second view controller so I can read the value at the first view controller.
So I know, this is not possible, because `bool* it is a primitive type.
So I used NSNumber, but this also does not work. On the first view controller I set on viewDidLoad
self.myBool1 = [NSNumber numberWithBool:NO];
On the second view controller:
self.myBool2 = [NSNumber numberWithBool:YES];
But on the first view controller the value is 0 - NO... So it seems that creating the new NSNumber is not shared to the first view controller.
What can I do to solve this problem?
Regards Tim

You have lots of choices, but which you should use depends on whether both viewControllers need notification of when the value changes.
If you don't need notification, the easiest choice is to use a global BOOL variable, although purists will scoff at the suggestion. But really it's two lines of code and you're done. Another option would be to store the value in NSUserDefaults.
If you need change notification in each viewController, perhaps the cleanest design is to write a "set" method in one viewController that sets the value in both itself and the other viewController. Something like:
-(void) setMyBool:(BOOL)newValue
{
myBool = newValue;
otherViewController.myBool = newValue;
}
If you want to change the value from either viewController, it gets a little trickier because you have to have each viewController keep a reference to the other and make sure not to recurse when setting the value. Something like:
-(void) setMyBool:(BOOL)newValue
{
if ( self.busyFlag == YES )
return;
self.busyFlag = YES;
myBool = newValue;
otherViewController.myBool = newValue;
self.busyFlag = NO;
}
Yet another option would be to use NSNotifications to change the value and have each viewController class listen for the change notification. And TheEye's suggestion of writing a wrapper class and keeping a reference to an instance of that class in both viewControllers would work too.
If you don't need change notifications, though, I would just create a global BOOL variable and get on with the rest of the application because it's so easy, reliable and hard to mess up.

An NSNumber object is immutable, so you can't use it like that. If you write [NSNumber initWithxxx], in fact you create a new object.
If you want to share a number or boolean between several classes, you should create your own wrapper class with setters and getters for the bool value (or subclass NSNumber). This class you can share between classes.

Related

Add a property to all view controllers in an iPhone app

View controllers in my iPhone app either extend from UIViewController or UITableViewController. I need to add a property to all of them so that I can pass user information between controllers. The solution I am aware of is to add a BaseViewController and a BaseTableViewController, add the property to both of them, then make all controllers to inherit from them instead.
Repeating the property in BaseViewController and BaseTableViewController doesn't seem to be the most elegant solution to me. Is there any better ones?
Thanks!
As extensions will not work in your case, you could write a category on UIViewController and use objc_getAssociatedObject to store the data you want and retrieve it with objc_getAssociatedObject. But you should use this option with care.
static NSString *key = #"example";
- (void)setExampleProperty:(id)value {
objc_setAssociatedObject(self, (__bridge void *)key, value, OBJC_ASSOCIATION_RETAIN);
}
- (id)exampleProperty {
return objc_getAssociatedObject(self, (__bridge void *)key);
}
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ObjCRuntimeRef/Reference/reference.html

using segmented control

okay i have a tabbed view, so two view controllers. in one view controller i have a segmented control and to know which segment was selected i have an action connected to it. like this:
-(IBAction)selectAngle:(id)sender{
clickedSegment = [myAngleType selectedSegmentIndex];
}
here clickedSegment is an integer which i have exposed as a property in my header. now i want to use the value of this clickedSegment in my other view controller but whenever i create an instance of that VC(segmented controller one) and try to use clickedSegment, i always get 0 as the value no matter if i selected other segment 1 or 2. its always zero. where am i going wrong?
How is your second view controller going to know about any property in the first view controller? This is impossible, unless you explicitly get a reference to it.
// in second view controller
FirstViewController *firstVC =
(FirstViewController*)[self.tabBarController.viewControllers objectAtIndex:0];
NSLog(#"clicked segment: %d", firstVC.clickedSegment); // assuming int
You are not using the synthesized setter correctly, you should set it like this:
-(IBAction)selectAngle:(id)sender{
self.clickedSegment = [myAngleType selectedSegmentIndex];
}

Accessing a value from a property that is being set in a method to another method

I want to get the value of the resultingPoints inside this delegate method
- (void)perksDetailsViewController:(PerksDetailsViewController *)sender didPassRequiredPoints:(NSNumber *)requiredPoints withCard:(Card *)selectedCard
{
double perksPoints = [requiredPoints doubleValue];
self.resultingPoints = [NSNumber numberWithDouble:[selectedCard subtractPoints:perksPoints] ];
NSLog(#"points remaining %#", self.resultingPoints);
}
This works fine but then when I try to access the resultingPoints inside the method below, resultingPoints has a null value, as being said also by the NSLog I placed.
- (void) didPressDone:(id)sender {
PointsResultsViewController *pointsResults = [self.storyboard instantiateViewControllerWithIdentifier:#"resultsPointsVC"];
[self.navigationController pushViewController:pointsResults animated:YES];
pointsResults.leftPointsLabel.text = [self.resultingPoints stringValue];
NSLog(#"hey points left is%#", self.resultingPoints);
}
What could be a good way to get the value of the resultingPoints from the first method?
Thanks in advance.
EDIT:
Log outputs
2012-05-02 15:47:48.297 CardWallet[22196:f803] points remaining 900
2012-05-02 15:47:49.291 CardWallet[22196:f803] hey points left is(null)
From your last comment:
this is it's property declaration #property (nonatomic, weak) NSNumber *resultingPoints;
This is probably the source of your problem. A weak property will be deallocated and set to nil if nothing else is retaining it, which is the case here. Make it a strong property and it will still be around when you push the new view controller.
From the details you've given in chat, you are actually dealing with two different instances of this class. One that is on the screen, and one that is being used as a delegate.
When assigning the delegate, you have to make sure it is the same object that is on the screen. This is best done in prepareForSegue, when the segue's destination view controller is the view controller that is about to appear.

How to save nsdictionary of a subview to a mainview based off tableviewcell selection

I am currently parsing some xml that looks like this
<Rows>
<Row MANUFACTURERID="76" MANUFACTURERNAME="Fondont" ISMANU="F" ISAUTO="F"/>
<Row MANUFACTURERID="18" MANUFACTURERNAME="Anti" ISMANU="T" ISAUTO="T"/>
</Rows>
I parse it so that there is an array of dictionaries (each dictionary has the four values of the Row in it).
I then pass ManufacturerName to my startSortingTheArray method like this
if (dataSetToParse == #"ICMfg") // ICMfg is a string passed to this view from the parent view cell selection enabling me to pass different data sets to this view
{
//Filter results (ISAUTO = T)
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"%K like %#",#"ISAUTO",#"T"];
NSArray *filteredArray = [myDataArray filteredArrayUsingPredicate:predicate];
//Passes Manufacturer strigs over to startSortingtheArray method
[self startSortingTheArray:[filteredArray valueForKey:#"MANUFACTURER"]];
}
So from here all of the ManufacturerNames are sent to my method as an array of strings. I then use this array to set up all of my sections / index-scroller. The method below shows how I am doing this.
//method to sort array and split for use with uitableview Index
- (IBAction)startSortingTheArray:(NSArray *)arrayData
{
//If you need to sort incoming array alphabetically use this line of code
//TODO: Check values coming in for capital letters and spaces etc
sortedArray = [arrayData sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
//If you want the standard array use this code
//sortedArray = arrayData;
self.letterDictionary = [NSMutableDictionary dictionary];
sectionLetterArray = [[NSMutableArray alloc] init];
//Index scrolling Iterate over values for future use
for (NSString *value in sortedArray)
{
// Get the first letter and its associated array from the dictionary.
// If the dictionary does not exist create one and associate it with the letter.
NSString *firstLetter = [[value substringWithRange:NSMakeRange(0, 1)] uppercaseString]; //uppercaseString puts lowercase values with uppercase
NSMutableArray *arrayForLetter = [letterDictionary objectForKey:firstLetter];
if (arrayForLetter == nil)
{
arrayForLetter = [NSMutableArray array];
[letterDictionary setObject:arrayForLetter forKey:firstLetter];
[sectionLetterArray addObject:firstLetter]; // This will be used to set index scroller and section titles
}
// Add the value to the array for this letter
[arrayForLetter addObject:value];
}
//Reload data in table
[self.tableView reloadData];
}
from here I do several things to do with setting up the tableview after [self.tableView reloadData]; is called, The main thing being is that I set the cell up with the string values of the array.
//Display cells with data
NSArray *keys = [self.letterDictionary objectForKey:[self.sectionLetterArray objectAtIndex:indexPath.section]];
NSString *key = [keys objectAtIndex:indexPath.row];
cell.textLabel.text = key;
when the cell is then selected the string value inside the cell is then sent back to the main view and used later as a search parameter... The thing being is that I am setting up several parameters that will be used as one search string.
Looking back at the XML I parsed
<Rows>
<Row MANUFACTURERID="76" MANUFACTURERNAME="Fondont" ISMANU="F" ISAUTO="F"/>
<Row MANUFACTURERID="18" MANUFACTURERNAME="Anti" ISMANU="T" ISAUTO="T"/>
</Rows>
These are the values of columns inside an SQl table that has a keyvalue MANUFACTURERID that is also found in other tables that I parse. I would like to use these key values to restrict/refine other queries but I just cannot figure out how to pass them to my parentview where I set up all of the search parameters, that is my question how can I save the dictionary of values that is related to the users tableview selection from the subview. So that I can then pass one or some of those values back to the subview of a different dataset to restrict the information that is displayed dependent on the users previous selections.
This has taken me about an hour to type up. Hopefully it makes sense, I am still fairly new to iOS development and Objective C, and this concept is really pushing my capabilities and before I move on and end up hasing some crap together that I will have to fix later on I am hoping that one or some of you will be able to lend your experience in this type of this to me so I can get this right first time :)
If you need me to clarify anything or provide you more information that will help you help me just let me know.
Thanks in advance!
The common pattern for passing information backwards in your view controller hierarchy is to use delegation. You can achieve this in your scenario by implementing the following:
1) Define a protocol in the SearchParametersViewController, which represents your the parent view controller you mentioned.
#protocol SearchParametersViewControllerDelegate <NSObject>
#optional
- (void)searchOptionsSelected:(NSArray *)selectedSearchOptions;
#end
2) Conform to that protocol in your SearchOptionsSelectionViewController, which represents the table view controller that has a list of selections to choose from. Make sure to import or forward-declare the class the protocol is defined in (e.g. SearchParametersViewController) .
#import "SearchParametersViewController.h"
#interface SearchOptionsSelectionViewController <SearchParametersViewControllerDelegate>
3) Define a delegate property in your SearchOptionsSelectionViewController (assumes you are using ARC on iOS 5.0, 4.x use unsafe_unretained instead of weak. Use assign if the project is using manual memory management). This delegate object will contain a reference to your parent view controller (e.g. SearchParametersViewController). You do not want this property to be retained as to avoid retain cycles/circular references where one object references another, which in turn has a reference back to the first and neither object is ever deallocated.
#property (nonatomic, weak) id<SearchParametersViewControllerDelegate> delegate;
4) When instantiating the SearchOptionsSelectionViewController instance inside your parent view controller (SearchParametersViewController), set the delegate property to the parent view controller instance as represented by the self keyword. This ensures you can send the message (and corresponding data) backward in your view controller hierarchy, yet the object relationships remain loosely coupled. This delegate protocol could be conformed to in any other view controller, there are no tight relationships in the selection view controller back to the parent view controller, the only thing linking them is the flexible delegate protocol adoption by the selection view controller.
SearchOptionsSelectionViewController *selectionViewController = [[SearchOptionsSelectionViewController alloc] init];
selectionViewController.delegate = self;
5) Finally, in your SearchOptionsSelectionViewController table view's -tableView:didSelectRowAtIndexPath: delegate method, pass the data corresponding to the selected row back to your parent view controller (SearchParametersViewController) via the delegate method you defined in the SearchParametersViewControllerDelegate protocol. You must use the -respondsToSelector: method to ensure that the delegate object actually implements the -searchOptionsSelected: delegate method. To force this implementation, change #optional to #required above the method prototype in the protocol definition in step #1. self.someDataArray represents a the data source you are using with the selection table view controller. The specifics of the delegate protocol method and data object(s) sent back to the parent view controller can be changed, the important thing here is the delegation pattern and not having any tightly coupled relationships between the instances of either class, but especially backwards in the view controller hierarchy.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([self.delegate respondsToSelector:#selector(searchOptionsSelected:)])
{
NSArray *selectedObjs = [NSArray arrayWithObject:[self.someDataArray objectAtIndex:indexPath.row]];
[self.delegate searchOptionsSelected:selectedObjs]
}
}
6) Implement the delegate method inside SearchOptionsSelectionViewController.m
- (void)searchOptionsSelected:(NSArray *)selectedSearchOptions
{
// do what you need to with selectedSearchOptions array
}
Further reading:
Cocoa Fundamentals Guide - Delegates and Data Sources
Cocoa Core Competencies - Protocol
You could use the application delegate to achieve your goals here.
I'm going to assume your app has a structure a bit like this. Please excuse the crudity of this model.
Application delegate (A) --> Search Options View (B) --> Table where you do selections (C)
|
|
--> Some other view where you need the selection (D)
Your problem is that you need information to flow from C to D.
Your application delegate has the merit of being universally accessible via [[UIApplication sharedApplication] delegate]. So you can get a pointer to it from anywhere. From C, you can send your selection information back to A. A can either send this on automatically to D, or D can request it from A whenever it wants it.
A couple of points:
I won't expand any further on my answer at the moment because it's beer o' clock here now, plus I might have misunderstood your requirement. If you do need anything else, I will be up at baby o' clock in the morning UK time so there might be some delay.
Some people frown on using the application delegate as a "data dump" in the way I have suggested. Some of those people would rather set up a whole singleton class and treat that as a data dump instead. It seems to be one of those neverending arguments so I try not to get involved.
You have a few options, one is to use user defaults. It might be the easiest.
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/Reference/Reference.html
Another is to post a notification with the information.
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsnotificationcenter_Class/Reference/Reference.html

Cant access an int value

i declared an int value as my imageIndexForSend through the following code in myView class.
int imageIndexForSend;
#property int imageIndexForSend;
#synthesize imageIndexForSend;
after on a button click i am displaying a popover which is PopOver calss.
there is table view with multiple indexes in popover class.when i click on any row in PopOver class table it set myView class imageIndexForSend as
In PopOver
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
myView *obj = [[myView alloc] init];
[obj getImageForSend:indexPath.row];
[staticSceneController release];
}
in myViewClass
-(void)getImageForSend:(int)index{
imageIndexForSend = index;
}
then i am return to myViewClass after dismissing popover (popOver class) and doing some actions in myViewClass.
then i am clicking a send button.but the integer value imageIndexForSend is zero.cant get the old value which i set from PopUp.
can any one tell me a way to get the old imageIndexForSend value.may i know what mistake i done.
First, you name a method with get to set the value, it's bad.
Second, you use a property and synthesize it, so you don't need to rewrite the set method unless you need to have a custom set method.
And finally you create a new view on each selection of tableview cell !
1) Remove your getImageForSend: method, you don't need that with property
2) Instead using : [obj getImageForSend:indexPath.row];, use : obj.imageIndexForSend = indexPath.row;
3) Don't create a new view on each selection, assign the value on the existing view.
A better way to transmit data from your popover to your view (controller ?) is to have a delegate property in your popover class and set it with your view object, create a delegate protocol with a method that is called when a cell is selected in popover with an int argument (the index) then make your view class adopts the protocol and do a obj.imageIndexForSend = argument; in your protocol method.
It seems you're allocating a myView instance and assigning that to a local variable (obj), but then you don't keep a pointer to that new instance anywhere.
From what I understand, you already have an existing instance of myView, so what you need to do is to set the variable on that instance, and not create a new one every time.
Each instance have their own set of variables, so changing it in a new instance won't affect any other instances.
You are instantiating a new MyView whenever the user taps on any row of your UITableView. You should try to access the original MyView instead (or whatever object shall retain that setup value).
Within your popover, you should find a way to access the instance that holds the actual index-value. How exactly that is achieved depends a lot on your implementation.
In other words, do not instantiate something within an object that has a shorter lifetime than the object that will access that very instance.
If you're trying to access the index of the selected row in the UITableView you can just use the following:
int index = [myTableView indexPathForSelectedRow].row;