Pass an int between a view and it's subview - iphone

I have a view called PatternsViewController and a subview named SolutionsViewController. I want to pass a variable in PatternsViewController named iteration to my SolutionsViewController, right before I present it with
solutions = [[SolutionsViewController alloc] init];
solutions.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentModalViewController:solutions animated:YES];

solutions = [[SolutionsViewController alloc] init];
solutions.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
// Set your value here
[solutions setMyIntWithSomeMethodIWrote:123];
[self presentModalViewController:solutions animated:YES];
And in SolutionsViewController
- (void)setMyIntWithSomeMethodIWrote:(int)value {
myInstanceVar = value;
}

I figured it out by slightly modifying Squeegy's code.
In PatternsViewController.m
[solutions setIteration:iteration];
and in SolutionsViewController.m
-(void) setIteration:(int)value {
iteration = value;
NSLog(#"Iteration set from value: %d" , iteration);
}

I would use a Singleton class.
What should my Objective-C singleton look like?
Then you can do like:
[SingletonClass sharedInstance].var = iteration;
And access it with:
[SingletonClass sharedInstance].var

Why not simply over-ride the init with an additional argument that take the int you want to set? This allows a clean instantiation without an added set call.
solutions = [[SolutionsViewController alloc] initWithIntVal: int];

The selected answer works for me but it is giving me a semantic warning. I'm a little annal retentive about warnings even if the code works so I am wondering if there is a way to make it work without the warning.
The warning is:
Instance method '-SetPrompt:' not found (return type defaults to 'id')
Here is what I did while following along to the answer in this question.
In the calling .m file
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
vcSelection *ViewSelection = [[vcSelection alloc] initWithNibName:#"vcSelection" bundle:nil];
ViewSelection.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
if ([[SettingsTableData objectAtIndex:indexPath.row] isEqualToString:DeviceType])
{
[ViewSelection SetPrompt:#"Select the device type."];
}
else if ([[SettingsTableData objectAtIndex:indexPath.row] isEqualToString:DeviceManufacturer])
{
[ViewSelection SetPrompt:#"Select the device manufacturer."];
}
else if ([[SettingsTableData objectAtIndex:indexPath.row] isEqualToString:DeviceModel])
{
[ViewSelection SetPrompt:#"Select the device model."];
}
[self.view addSubview:ViewSelection.view];
}
In the receiving .m file
#implementation vcSelection
NSMutableString *Prompt;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Debug"
message:Prompt
delegate:self
cancelButtonTitle:#"Done"
otherButtonTitles:nil];
[alert show];
[alert release];
}
- (void) SetPrompt:(NSMutableString *)Value
{
Prompt = Value;
}
#end

Related

load a different nib if phone is not connected to internet

I use Apple's Reachability class and it's working fine using an alert to tell the user that the connection is not available or the connection is lost. However, I want to change the alert to something more visual. I want to load a nib that tells the user no active connection is present but the nib is not loading. I also tried loading my other nibs but it also doesn't load the nib.
- (BOOL) checkNetworkStatus:(NSNotification *)notice
{
// called after network status changes
NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
switch (internetStatus)
{
case NotReachable:
{
NSLog(#"The internet is down.");
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"No Internet Connection" message:#"You are currently not connected to a WI-FI or cellular Data.\nPlease make sure you are connected." delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
[alert release];
//NoConnection *noConn = [[NoConnection alloc] initWithNibName:#"NoConnecton" bundle:nil];
//[self presentModalViewController:noConn animated:NO];
//[NoConnection release];
self.isConnected = NO;
return NO;
break;
}
//more cases.........
the alert part is working just fine but the part for loading the nib is not. can you tell me whats wrong here? I'm calling this function in viewWillAppear. Thanks!
You can do the following:
if ( ! isConnected )
{
NoConnection *noConn = [[NoConnection alloc] initWithNibName:#"NoConnecton" bundle:nil];
[self presentModalViewController:noConn animated:NO];
[NoConnection release];
}
The code you have presented should work, sow the problem must be somewhere else probably in the nib - linking, you might have forgot to link something to the nib file.
try this
[self.navigationController presentModalViewController:noConn animated:YES];
Does your nib has NoConnection as a File's Owner (I guess NoConnection is a subclass of UIViewController, check it. I'll call this NoConnectionViewController bellow because you should name it like that for no mistake) ?
Is the file's owner view property linked with the graphical view ? Check it.
Are you working without status bar at top of the window ? That could be a problem.
Are your here inside a modalViewController ? If yes, your code won't work, you must use instead :
NoConnectionViewController* nextWindow = [[NoConnectionViewController alloc] initWithNibName:#"NoConnecton" bundle:nil]; // Check your nib name here, seems to be a mistake
UINavigationController* navController = [[UINavigationController alloc] initWithRootViewController:nextWindow];
[self presentModalViewController:navController animated:YES];
[navController release];
[nextWindow release];
You need to use the delegate method of alert view
#pragma mark - AlertView Delegates
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if(alertView.tag == 1)
{
NoConnection *noConn = [[NoConnection alloc] initWithNibName:#"NoConnecton" bundle:nil];
[self presentModalViewController:noConn animated:NO];
[NoConnection release];
}
}
don't forget to assign tag value of alertView to 1.
and also dont forget to conforms to the UIAlertViewDelegate protocol
Happy Coding :)

Best way to pass variables between views

I am very new to xcode & Objective-C (having come from PHP) i have started to play around and am finding it very hard to pass variables between views this is what i have so far:
Game_info.h
#import <UIKit/UIKit.h>
#interface Game_Info : UIViewController {
IBOutlet UITextField *groupName;
IBOutlet UISegmentedControl *gameType;
}
#property (nonatomic,retain) IBOutlet UITextField *groupName;
- (IBAction) GameTypePicker;
- (IBAction) KeyboardHide;
- (IBAction) BackBTN;
- (IBAction) NextBTN;
#end
Game_Info.m
#import "I_Dare_YouViewController.h"
#import "Game_Info.h"
#import "Game_TDoR.h"
#implementation Game_Info
#synthesize groupName;
// Next Button
-(IBAction) NextBTN{
if ([groupName.text length] == 0) {
// Alert
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Group Name"
message:#"Please enter a group name"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil
];
[alert show];
[alert release];
}else if([groupName.text length] < 3){
// Alert
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Group Name"
message:#"Please enter a name longer than 3 characters"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil
];
[alert show];
[alert release];
}else{
Game_TDoR *screen = [[Game_TDoR alloc] initWithNibName:nil bundle:nil];
screen.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentModalViewController:screen animated:YES];
[screen release];
Game_TDoR *screen1 = [[Game_TDoR alloc] initWithNibName:nil bundle:nil];
NSLog(#"Game_Info: %#",self.groupName.text);
screen1.groupNameText = self.groupName.text;
[self presentModalViewController:screen1 animated:YES];
[screen1 release];
}
}
Then in another view / .h / .m file i am trying to get to the 'groupName' property.
Game_TDoR.m
#import "I_Dare_YouViewController.h"
#import "Game_Info.h"
#import "Game_TDoR.h"
#implementation Game_TDoR
#synthesize groupNameText,Testlbl;
- (void)viewDidLoad
{
NSLog(#"Game_TDoR: %#",self.groupNameText);
NSString *msg = [[NSString alloc] initWithFormat:#"Hello, %#",[self.groupNameText capitalizedString]];
[Testlbl setText:msg];
[msg release];
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
So what i am trying to do is on the first view page (Game_info) there is an input text box and im trying to pass that to a label on another view page (Game_TDoR)
This is what comes out in the NSLog (note that the second page (Game_TDoR) comes out first in the log.
2011-07-17 00:25:34.765 I Dare You[3941:207] Game_TDoR: (null)
2011-07-17 00:25:34.774 I Dare You[3941:207] Game_Info: Name
Problem solved:
On the next button i needed to add the variable before i moved page (not the other way around - silly noobish thing to do...)
Game_TDoR *screen1 = [[Game_TDoR alloc] initWithNibName:nil bundle:nil];
NSLog(#"Game_Info: %#",self.groupName.text);
screen1.groupNameText = self.groupName.text;
[self presentModalViewController:screen1 animated:YES];
[screen1 release];
Game_TDoR *screen = [[Game_TDoR alloc] initWithNibName:nil bundle:nil];
screen.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentModalViewController:screen animated:YES];
[screen release];
If you need to pass the value of groupName.text from the Game_Info view controller to the Game_TDoR view controller, which is presented modally by the former, you can declare a property in Game_TDoR to hold the value:
1) Declare a NSString property in Game_TDoR #interface block:
#property (nonatomic,copy) NSString *groupNameText;
(Remember to synthesize or implement the accessor methods in the implementation block)
2) In NextBTN action, after you initialize your Game_TDoR instance, set the property:
Game_TDoR *screen = [[Game_TDoR alloc] init...];
screen.groupNameText = self.groupName.text;
Merely including the header file will not make the variable available. You are only including the definition of the class (class is for PHP what #interface is for Obj-C) You have to instantiate Game_Info and access the variable via the instance of Game_Info.
groupName is a member (ivar) of Game_Info. Its default visibility is #protected, so any classes outside Game_Info can't access it, unless they derive from Game_Info. To make groupName accessible, you can either create a property that exposes it, or you can make it #public. How this is done is documented in the vast documentation for Xcode.
But groupName, being an ivar (instance variable) of an object, only exists if there is in fact an instance of the Game_Info. I assume you have some globally accessible instance of Game_Info in your program, let's call it globalGameInfo. Now you can access its groupName using
UITextField *gName = [globalGameInfo groupName];
Take this in .h file in SecondViewController
NSString *strABC;
Make below function in SecondViewController.m
-(void)setString:(NSString *)strEntered{
strABC=strEntered;
}
Now In First view controller do like this:
SecondViewController.m *objSecond = [[SecondViewController.m] initwithNibName:#"secondView.xib" bundle:nil];
[objSecond setString:#"Comment Controller"];
[self.navigationController pushViewController:objSecond animated:YES];
[objSecond release];
Now, In secondViewController viewWillAppear Method write this.
-(void)viewWillAppear:(BOOL)animated{
lblUserInput.text = strABC;
}
Please check spelling mistakes as I hand written this. Hope this help.
If you are not using navigationContoller then you can do something like this.
SecondViewControler *objSecond = [[SecondViewController] initwithNibName:#"secondview.xib" bundle:nil];
[objSecond setUserInput:txtUserInput.text];
[objSecond viewWillAppear:YES];
[self.view addSubview:objSecond];
[objSecond release];

AQGridview Not Calling Datasource Methods

I am trying to implement AQGridView based upon the ImageDemo in the /examples folder. I have a view controller with the following declaration:
#interface ImageDemoViewController : UIViewController <AQGridViewDelegate, AQGridViewDataSource, ImageDemoCellChooserDelegate>
{
...
None of the datasource methods in my view controller such as
- (NSUInteger) numberOfItemsInGridView: (AQGridView *) aGridView
{
return ( [images count] );
}
are being called. Here is where I setup the gridview making my view controller the delegate for the gridview.
- (void)viewDidLoad
{
[super viewDidLoad];
self.gridView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
self.gridView.autoresizesSubviews = YES;
self.gridView.delegate = self;
self.gridView.dataSource = self;
images=[[NSMutableArray alloc]init];
[images addObject:#"http://t3.gstatic.com/images?q=tbn:ANd9GcTOXAzFMoK441mcn9V0OemVe_dtAuCpGjBkLrv4rffyOjYIo45BEw"];
[self.gridView reloadData];
}
If I set a breakpoint on
[self.gridView reloadData];
the line is executed but reloadData method in AQGridView is not called. The only difference from the ImageDemo is I do not have a .xib file for the view controller. Have I forgotten to hook up something, resulting in the datasource methods not being called?
If there's no XIB, then who's creating the gridView? If it's never created, then it would be NIL, and you'd have the behavior you describe. (If that's it, then just adding:
self.gridview = [AQGridView alloc] initWithFrame: ...]; should suffice.
Had the same problem. Solved by replacing the view with the AQGridView.
[self.view addSubview:self.gridView]
self.view = self.gridView;
Full method:
- (void) viewDidLoad
{
[super viewDidLoad];
self.gridView = [[AQGridView alloc] init];
self.gridView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
self.gridView.autoresizesSubviews = YES;
self.gridView.delegate = self;
self.gridView.dataSource = self;
self.view = self.gridView;
[self.gridView reloadData];
}
Maybe you could try implementing this:
- (void)LoadSearch
{
NSURL *test1 = [NSURL URLWithString:#"http://www.4ddraws.com/search_iphone.asp"];
NSURLRequest *test = [NSURLRequest requestWithURL:test1];
[web4D setScalesPageToFit:(YES)];
[web4D loadRequest:test];
}

iPhone UISearchBar view not updating immediately?

I currently have a UISearchBar and UIDisplayController defined in my RootViewController as:
- (void)viewDidLoad {
[super viewDidLoad];
//Add the search bar
aSearchBar = [[UISearchBar alloc] initWithFrame:CGRectZero];
[aSearchBar sizeToFit];
aSearchBar.delegate = self;
aSearchBar.placeholder = #"Search YouTube...";
self.tableView.tableHeaderView = aSearchBar;
searchDC = [[UISearchDisplayController alloc] initWithSearchBar:aSearchBar contentsController:self];
[self performSelector:#selector(setSearchDisplayController:) withObject:searchDC];
searchDC.delegate = self;
searchDC.searchResultsDataSource = self;
searchDC.searchResultsDelegate = self;
[aSearchBar release];
[searchDC release];
}
When the search button is fired, this event is executed to run an API call:
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
[videoList removeAllObjects];
if (searchBar.text.length > 0) {
NSString *searchCriteria = [searchBar.text stringByReplacingOccurrencesOfString:#" " withString:#"+"];
YTJAppDelegate *appDelegate=(YTJAppDelegate*)[[UIApplication sharedApplication] delegate];
[appDelegate searchWithCriteria:searchCriteria];
}
}
The data is fetched correctly. However. It only becomes visible when I hit the 'Cancel' button on the search.
How can I get the view to update correctly the moment the data source is updated/search button is hit? Is there a special SearchDelegate method I need to implement?
the code for the associated table view might be helpful, but I am going to guess that you are not calling [self.tableView reloadData] after the search is completed
turns out the solution was to point the searchDisplayController delegates and data sources at the table view it was implementing:
searchDC.delegate = self;
searchDC.searchResultsDataSource = self.tableView.dataSource;
searchDC.searchResultsDelegate = self.tableView.delegate;

Take a random Number from one ViewController and use it in a second ViewController - Update

I have two ViewControllers: The RedButtonViewController and the TweetViewController. The RedButtonViewController generates random numbers in Textlabels and I want to use the number or the label with the TweetViewController. How can I make this?
Thanks for your help!
My TweetViewController will be opened with this code in the RedButtonViewController:
- (IBAction)TweetViewController:(id)sender {
TweetViewController *Tweet = [[TweetViewController alloc] initWithNibName:nil bundle:nil];
[self presentModalViewController:Tweet animated:YES];
}
Here is an exemple of how I generate the random number:
- (IBAction)pushRedButton:(UIButton *)sender {
int ZahlDerToten;
ZahlDerToten = arc4random() % 1000000;
outputLabel.text = [NSString stringWithFormat:#"You killed %d people.", ZahlDerToten];
Create a property on the TweetViewController and set it before presenting it:
- (IBAction)TweetViewController:(id)sender {
// Note: don't put leading capitals on a local variable
TweetViewController *tweet = [[TweetViewController alloc] initWithNibName:nil bundle:nil];
tweet.randomNumber = [self generateRandomNumber];
[self presentModalViewController:tweet animated:YES];
// Note: You were leaking the view controller
[tweet release];
}
Another solution (and how I usually do this kind of thing) is to create a new initializer called -initWithNumber: (probably something a little more descriptive than "number") and call it like this:
- (IBAction)TweetViewController:(id)sender {
TweetViewController *tweet = [[TweetViewController alloc] initWithNumber:[self generateRandomNumber]];
[self presentModalViewController:tweet animated:YES];
[tweet release];
}
-initWithNumber would then look something like:
- (TweetViewController *)initWithNumber:(NSInteger)number {
self = [super initWithNibName:nil bundle:nil];
if (self != nil) {
self.number = number;
}
return self;
}