I am pretty new to objective c. I have looked through a ton of questions on stack overflow to try to find an answer but nothing has helped, so I appreciate any help anyone can offer.
I am trying to make an app that will have the picker view load from my array of 51 numbers. a random object will be generated from the array and if the user selects that object from the picker, an alert will show. I'm going to make a simple little guessing game, but for now I just have the picker that loads but is blank with no text. The alerts do work tho.
I have already assigned datasource and delegate to picker view on the view controller.
I need help figuring out why my picker view is not loading my array and what I can do to fix it. Thank you
here is my h file:
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController <UIPickerViewDataSource, UIPickerViewDelegate>
#property (strong, nonatomic) IBOutlet UIPickerView *picker;
#end
here is m file:
#import "ViewController.h"
#interface ViewController ()
#property NSArray *numbers;
#property NSString * selection;
#property NSString *randomObject;
#property NSInteger rnd;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor darkGrayColor];
[_numbers arrayByAddingObjectsFromArray:_numbers];
}
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return 1;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent: (NSInteger)component{
return _numbers.count;
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
_numbers = #[#0,#1,#2,#3,#4,#5,#6,#7,#8,#9,#10,#11,#12,#13,#14,#15,#16,#17,#18,#19,#20,#21,#22,#23,#24,#25,#26,#27,#28,#29,#30,#31,#32,#33,#34,#35,#36,#37,#38,#39,#40,#41,#42,#43,#44,#45,#46,#47,#48,#49,#50];
//create random object from array
_rnd = arc4random() % ([_numbers count]);
_selection = [NSString stringWithFormat:#"%ld",(long)row];
_randomObject = [_numbers objectAtIndex:self.rnd];
NSLog(#"%#",self.randomObject);
//strings for alerts
NSString *right = [[NSString alloc]initWithFormat:#"You Guessed Right! Congratulations you've earned 3 points!"];
NSString *oneOff = [[NSString alloc]initWithFormat:#"You were so close! Only 1 off! The number was %lu. Congratulations you've earned 2 points!",(unsigned long)self.rnd];
NSString *twoOff = [[NSString alloc]initWithFormat:#"You were so close! Only 2 off! The number was %lu. Congratulations you've earned 1 point!",(unsigned long)self.rnd];
NSString *threeOff = [[NSString alloc]initWithFormat:#"Nice try! You were 3 off. The number was %lu. You earned -1 point.",(unsigned long)self.rnd];
NSString *fourOff = [[NSString alloc]initWithFormat:#"Good try! You were 2 off. The number was %lu. You earned -2 points.",(unsigned long)self.rnd];
NSString *fiveOff = [[NSString alloc]initWithFormat:#"You were no where close! The number was %lu. You earned -3 points!",(unsigned long)self.rnd];
//alerts for guesses
UIAlertView *rightAlert = [[UIAlertView alloc]initWithTitle:#"Spot On!" message:right delegate:nil cancelButtonTitle:#"Sweet!" otherButtonTitles:nil, nil];
UIAlertView *oneOffAlert = [[UIAlertView alloc]initWithTitle:#"Only one off!" message:oneOff delegate:nil cancelButtonTitle:#"Ok!" otherButtonTitles:nil, nil];
UIAlertView *twoOffAlert = [[UIAlertView alloc]initWithTitle:#"Only Two Off!" message:twoOff delegate:nil cancelButtonTitle:#"Ok!" otherButtonTitles:nil, nil];
UIAlertView *threeOffAlert = [[UIAlertView alloc]initWithTitle:#"Three Off" message:threeOff delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
UIAlertView *fourOffAlert = [[UIAlertView alloc]initWithTitle:#"Four Off" message:fourOff delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
UIAlertView *fiveOffAlert = [[UIAlertView alloc]initWithTitle:#"No Where Close!" message:fiveOff delegate:nil cancelButtonTitle:#"Ok!" otherButtonTitles:nil, nil];
NSInteger a = [_selection integerValue];
//guessed right
if (_selection == _randomObject)
{
[rightAlert show];
}
//one off
if (a == (_rnd + 1) || (a == (_rnd - 1)))
{
[oneOffAlert show];
}
//two off
if (a == (_rnd + 2) || (a == (_rnd - 2)))
{
[twoOffAlert show];
}
//three off
if (a == (_rnd + 3) || (a == (_rnd - 3)))
{
[threeOffAlert show];
}
//four off
if (a == (_rnd + 4) || (a == (_rnd - 4)))
{
[fourOffAlert show];
}
//five or more off
if ((_rnd + 5) >= a || (_rnd - 5) <= a ||(_rnd - 5) >= a || (_rnd + 5) <= a)
{
[fiveOffAlert show];
}
}
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
return _numbers[row];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
The problem is that this line
_numbers = #[#0,#1,#2,#3,#4,#5,#6,#7,#8,#9,#10,#11,#12,#13,#14,#15,#16,#17,#18,#19,#20,#21,#22,#23,#24,#25,#26,#27,#28,#29,#30,#31,#32,#33,#34,#35,#36,#37,#38,#39,#40,#41,#42,#43,#44,#45,#46,#47,#48,#49,#50];
appears in the wrong place. It is in the pickerView:didSelectRow:inComponent: method which is only called after the user has made a selection. Therefore, your _numbers array will always be empty.
Move it to the viewDidLoad method, replacing the following statement which currently hasn't any effect at all:
[_numbers arrayByAddingObjectsFromArray:_numbers];
Also, you need to change this method:
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
return [_numbers[row] stringValue];
}
because _numbers[row] is an NSNumber, not an NSString.
i have an ios app which uses a login page and after authenticating it enters into the inbox page.But after entering the inbox page it comes back automatically to the login page
Login.m
{
if ([username length] == 0 || [password length] == 0)
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Oops!"
message:#"Make sure you enter a username and password!"
delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
else
{
NSString *query = [NSString stringWithFormat:#"SELECT * FROM Login_Info WHERE username='%#'",username]; // Execute the query.
NSLog(#" query = %#", query );
// Get the results.
if (self.arrLogin_Info != nil) {
self.arrLogin_Info = nil;
}
self.arrLogin_Info = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query]];
[def setObject:[self.arrLogin_Info objectAtIndex:0] forKey:#"idKey"];
[def setObject:[self.arrLogin_Info objectAtIndex:1] forKey:#"usernameKey"];
[def setObject:[self.arrLogin_Info objectAtIndex:2] forKey:#"passwordKey"];
[def setObject:[self.arrLogin_Info objectAtIndex:3] forKey:#"emailKey"];
NSLog(#" query output = %#", self.arrLogin_Info);
NSString *val = [self.arrLogin_Info objectAtIndex:2];
// NSLog(#" val = %#",val);
if ([val isEqualToString:password] )
{
// NSLog(#" Inside if before entering app");
[self.navigationController popToRootViewControllerAnimated:YES];
}
else
{
//NSLog(#" Inside else before entering app");
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Sorry!"
message:#"Please ensure you have entered the correct password!"
delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
}
}
#end
Inbox.m
-(void) viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
id u = [def objectForKey:#"idkey"];
if(u)
{
NSString *query = [NSString stringWithFormat:#"Select *from Messages where recipient_ID=%#",u];
self.msg = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query]];
// [self.tableView reloadData];
}
else
{
[self performSegueWithIdentifier:#"showLogin" sender:self];
}
// [self.tableView reloadData];
}
- (IBAction)logout:(id)sender {
//[PFUser logOut];
[self performSegueWithIdentifier:#"showLogin" sender:self];
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([segue.identifier isEqualToString:#"showLogin" ])
{
[segue.destinationViewController setHidesBottomBarWhenPushed:YES];
}
}
Your Inbox view controller uses the presence of an object for the key 'idkey' in NSUserDefaults to determine whether the user is already logged in, or whether to show the login screen.
I presume that this line in login.m
[def setObject:[self.arrLogin_Info objectAtIndex:0] forKey:#"idKey"];
is supposed to be setting that key, but you don't show where you initialise def - so my guess is that this is nil and you aren't saving the data in NSUserDefaults.
Also, all of this -
if (self.arrLogin_Info != nil) {
self.arrLogin_Info = nil;
}
self.arrLogin_Info = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query]];
can be simplified to this
self.arrLogin_Info = [self.dbManager loadDataFromDB:query];
I have a picker view that has values already inside, for example one of the things inside is weather, I have a button that works with the picker view so when u pick weather and push the button an alert pops up and says Welcome to X. You selected Weather than u push OK to remove the alert, I was wondering if it was possible to after you push OK it takes you to the view controller that has the weather. I have never seen this done and this is an all in one app, also there are about 6 or 7 other items on the picker so if someone could help that would be great: here is my code. By the way I am new to the site sorry if I didn't do Code Blocks.
- (void)viewDidLoad
{
NSArray *data = [[NSArray alloc] initWithObjects:#"Weather", #"Calendar", #"Facebook", #"Twitter", #"Instagram",#"Tasks" ,nil];
self.array = data;
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
#pragma marks Picker Data Source Methods
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
return [_array count];
}
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 1;
}
#pragma mark Picker Delegate Methods
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
return [_array objectAtIndex:row];
}
- (IBAction)ButtonPressed:(id)sender {
NSString *select = [_array objectAtIndex:[_picker selectedRowInComponent:0]];
NSString *title = [ [NSString alloc] initWithFormat:#"You selected %#!" , select];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:#"Welcome To One" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
You have to do like bellow need to give tag to UIAlertView otherwise it will push view on each UIAlertView click
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent: (NSInteger)component
{
NSString *select = [_array objectAtIndex:component];
NSString *title = [ [NSString alloc] initWithFormat:#"You selected %#!" , select];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:#"Welcome To One" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
alert.tag = 1001;
alert.delegate = self;
[alert show];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (alertView.tag == 1001)
{
[self.navigationController performSegueWithIdentifier:#"Identifier" sender:nil];
}
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
// Show alert here
[[[UIAlertView alloc]
initWithTitle:#"" message:#"Alert Message"
delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil]
show];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0)
{
UIStoryboard * storyboard = self.storyboard;
ViewController * detail = [storyboard instantiateViewControllerWithIdentifier: #"YourViewControlller"];
[self.navigationController pushViewController: detail animated: YES];
}
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent: (NSInteger)component
{
NSString *select = [_array objectAtIndex:component];
NSString *title = [ [NSString alloc] initWithFormat:#"You selected %#!" , select];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:#"Welcome To One" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
alert.delegate = self;
[alert show];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0)
{
[self.navigationController performSegueWithIdentifier:#"Identifier" sender:nil];
}
}
I have two buttons that will pop up an alertview with textfield to input data. However, only certain characters are allowed in each of the two textfields. Somehow, if I press the second button, the character set from the first button is used. What's going on here?
Also, what would be a more elegant form of inputting data without having to use an alertview? Could I use a modal view? If so, how?
- (IBAction)editRate
{
if(!self.powerOn) return;
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Edit Jail Fee Rate"
message:#"Enter New Daily Rate"
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"Ok", nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[[alert textFieldAtIndex:0] setKeyboardType:UIKeyboardTypeNumberPad];
[alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex != alertView.cancelButtonIndex)
{
UITextField *field = [alertView textFieldAtIndex:0];
field.placeholder = #"Enter New Rate";
NSCharacterSet * set = [[NSCharacterSet characterSetWithCharactersInString:#"0123456789."] invertedSet];
if ([field.text rangeOfCharacterFromSet:set].location != NSNotFound)
{
UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Only numbers are allowed in this field."delegate:self cancelButtonTitle:#"OK"otherButtonTitles:nil];
[errorAlert show];
FeeRate.text=#"0.00";
}
else
{
FeeRate.text = field.text;
[[NSUserDefaults standardUserDefaults] setObject:field.text forKey:RATE_KEY];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}
else
{
}
}
- (IBAction)editDate
{
if(!self.powerOn) return;
UIAlertView *alertDate = [[UIAlertView alloc] initWithTitle:#"Edit Jail Fee Date"
message:#"Enter New Date"
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"Ok", nil];
alertDate.alertViewStyle = UIAlertViewStylePlainTextInput;
[[alertDate textFieldAtIndex:0] setKeyboardType:UIKeyboardTypeNumberPad];
[alertDate show];
}
- (void)alertDate:(UIAlertView *)alertDate clickedButtonAtIndex:(NSInteger)buttonIndex2
{
if (buttonIndex2 != alertDate.cancelButtonIndex)
{
UITextField *fieldDate = [alertDate textFieldAtIndex:0];
fieldDate.placeholder = #"Enter New Date";
NSCharacterSet * setnew = [[NSCharacterSet characterSetWithCharactersInString:#"0123456789/"] invertedSet];
if ([fieldDate.text rangeOfCharacterFromSet:setnew].location != NSNotFound)
{
UIAlertView *errorAlert1 = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Only numbers and slashes are allowed in this field."delegate:self cancelButtonTitle:#"OK"otherButtonTitles:nil];
[errorAlert1 show];
FeeDate.text=#"00/00/0000";
}
else
{
FeeDate.text = fieldDate.text;
[[NSUserDefaults standardUserDefaults] setObject:fieldDate.text forKey:DATE_KEY];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}
else
{
}
}
When a UIAlertView is dismissed then a function called
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
is called.
So, both your alert views call this function.
One way to tell which alertView is calling it, you could create an ivar or better two properties like this:
#property (nonatomic, strong) UIAlertView *rateAlert;
#property (nonatomic, strong) UIAlertView *dateAlert;
and you should initialize like this:
[self setRateAlert:[[UIAlertView alloc] initWithTitle...
[self.rateAlert show];
and
[self setDateAlert:[[UIAlertView alloc] initWithTitle...
[self.dateAlert show];
and then:
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (alertView==self.rateAlert) {
//do whatever for rateAlert
} else {
//do whatever with dateAlert
}
}
i have been trying to copy text input from alertview textfield to a NSMutableArray that i will use later, alertview pops up and i enter the input to text field but when i press OK alert view disappears but doesnt copy text to my mutable array
here is my code
-(IBAction)add:(UIButton *)sender
{
addCustomStand = [[NSMutableArray alloc] init];
UIAlertView* dialog = [[UIAlertView alloc] initWithTitle:#"Enter a Stand Location"
message:#" "
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"OK", nil];
UITextField *nameField = [[UITextField alloc]
initWithFrame:CGRectMake(20.0, 45.0, 245.0, 25.0)];
[nameField setBackgroundColor:[UIColor whiteColor]];
nameField.text = #"";
[dialog addSubview:nameField];
if ([nameField text]){
NSLog(#"Name Field %# ",nameField.text);
[addCustomStand addObject:nameField.text];
}
[nameField release];
[dialog show];
[dialog release];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:#"OK"])
{
NSLog(#"Button 1 was selected.");
NSLog(#"StandLocations %# ",addCustomStand);
}
}
here is my output on log screen
2012-02-07 20:26:57.315 Avicii[1399:b603] Name Field
2012-02-07 20:26:59.720 Avicii[1399:b603] Button 1 was selected.
2012-02-07 20:26:59.721 Avicii[1399:b603] StandLocations (
""
)
anyone can help whats wrong with that code?
That's because [nameField text] doesn't have user entered value yet when you added it in your [addCustomStand addObject:nameField.text];
so change your adding into array in UIAlertView delegate method.
-(IBAction)add:(UIButton *)sender
{
addCustomStand = [[NSMutableArray alloc] init];
UIAlertView* dialog = [[UIAlertView alloc] initWithTitle:#"Enter a Stand Location"
message:#" "
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"OK", nil];
UITextField *nameField = [[UITextField alloc]
initWithFrame:CGRectMake(20.0, 45.0, 245.0, 25.0)];
[nameField setBackgroundColor:[UIColor whiteColor]];
nameField.text = #"";
// Note at this line
nameField.tag = 100;
//
[dialog addSubview:nameField];
[nameField release];
[dialog show];
[dialog release];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:#"OK"])
{
// Note at this line
UITextField* nameField = (UITextField *)[alertView viewWithTag:100];
[addCustomStand addObject:nameField.text];
//
NSLog(#"Button 1 was selected.");
NSLog(#"StandLocations %# ",addCustomStand);
}
}
You are adding nameField.text to your addCustomStand array before you even show the alert dialog. At the time you add it to the array the value is an empty string.
Instead you need to copy the value into your array during your clickedButtonAtIndex: method, by doing something like this:
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:#"OK"])
{
NSString *location;
UIView *view;
for (view in [alertView subviews]) {
if ([view isKindOfClass:[UITextField class]]) {
location = [(UITextField*)view text];
}
}
if (location) {
[addCustomStand addObject:location];
}
}
}