It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have to find a way to check (at the touch of a button) if the text in a textfield is present in an xml file.
I thought that if I load the xml file as an array then I could use a for loop to see if it is the same result as in the array.
are not at all practical for loops, could you explain me how can I write the code for this kind of problem?
I want that if the object is not present in the whole array then show the alert
thanks
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
cose = [[NSArray alloc] initWithObjects:#"giovanni",#"giulio",#"ciccio",#"panzo", nil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(IBAction)prova {
for (NSString *myElement in cose) {
if ([myElement isEqualToString:textfield1.text]) {
label1.text = textfield1.text;
}
else {
UIAlertView *alertCellulare = [[UIAlertView alloc] initWithTitle:#"Attenzione!" message:#"connessione assente" delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil, nil];
[alertCellulare show];
}
}
}
With fast-enumeration:
-(IBAction)prova
{
BOOL present = NO;
for (NSString *myElement in cose) {
if ([myElement isEqualToString:textfield1.text]) {
label1.text = textfield1.text;
present = YES;
break;
}
}
if (!present){
UIAlertView *alertCellulare = [[UIAlertView alloc] initWithTitle:#"Attenzione!" message:#"connessione assente" delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil, nil];
[alertCellulare show];
}
}
with block based enumeration
-(IBAction)prova
{
__block BOOL present = NO;
[cose enumerateObjectsUsingBlock:^(NSString *name, NSUInteger idx, BOOL *stop){
if ([name isEqualToString:textfield1.text]) {
label1.text = textfield1.text;
present = YES;
*stop = YES;
}
}];
if (!present){
UIAlertView *alertCellulare = [[UIAlertView alloc] initWithTitle:#"Attenzione!" message:#"connessione assente" delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil, nil];
[alertCellulare show];
}
}
Why not use a For-In loop (fast enumeration)?
Something like this:
for (NSString *myElement in myArray) {
if ([myElement isEqualToString:myTextField.text]) {
// Do something
}
}
Related
This question already has an answer here:
Using text field to display an alert [closed]
(1 answer)
Closed 8 years ago.
I asked this question before but for some reason it says closed, but i never got the right answer,can anyone help me add a text field, where if the user types a number in text field once the number reaches the same number as the counter it displays an alert.
#import <UIKit/UIKit.h>
int NumberCount;
#interface ViewController : UIViewController
{
int counter;
IBOutlet UILabel *count;
}
-(IBAction)minus;
-(IBAction)plus;
-(IBAction)zero;
#end
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
-(IBAction)plus {
counter=counter + 1;
count.text = [NSString stringWithFormat:#"%i",counter];
}
-(IBAction)minus {
counter=counter - 1;
count.text = [NSString stringWithFormat:#"%i",counter];
}
-(IBAction)zero {
counter=0;
count.text = [NSString stringWithFormat:#"%i",counter];
}
- (void)viewDidLoad {
counter=0;
count.text = #"0";
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
I tried adding this in but it didn't work
if (count.text == textField ) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Congrats"
message:#"You met that number"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
My ViewController.h :
__weak IBOutlet UITextField *textField;
You are comparing a string with an UITextField object.
You have to compare the count.text string with textField.text string.
Try this:
if ([count.text isEqualToString:textField.text]) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Congrats"
message:#"You met that number"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Hello this is the iOS project I'm working on .
I'm just a beginner at programming iOS apps.
I just need help so that I can improve ><
Here's my app so far.
So my job is under the reminder that shows the box " Daily Vibes".
I need to include 100 messages randomly.
I've heard of arc random function. I just need some examples on how to do use it.
Here's my code :
AppDelegate.m
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
UIApplicationState state = [application applicationState];
if (state == UIApplicationStateActive) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Daily Vibes"
message:notification.alertBody
delegate:self cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
AddtoDoViewController.m
implementation AddToDoViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.itemText.delegate = self;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)cancel:(id)sender {
[self dismissViewControllerAnimated:YES completion:nil];
}
- (IBAction)save:(id)sender {
[self.itemText resignFirstResponder];
// Get the current date
NSDate *pickerDate = [self.datePicker date];
// Schedule the notification
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = pickerDate;
localNotification.alertBody = self.itemText.text;
localNotification.alertAction = #"Show me the item";
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
// Request to reload table view data
[[NSNotificationCenter defaultCenter] postNotificationName:#"reloadData" object:self];
// Dismiss the view controller
[self dismissViewControllerAnimated:YES completion:nil];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[self.itemText resignFirstResponder];
return NO;
}
#end
I would like some assistance please.
Thank you.
Expectation :
With the box
Daily Vibes
-Attached 100 random messages-
Example of the affirmation :
NSarray *100affirmations = #[#"Every day in every way I am getting happier and happier.",
#"I am thankful to everybody who has touched my life and made it worth living. ",
#"Happiness is contagious. My happiness makes all these people happy, thus making it one big happy world.",
#"My happy disposition attracts happiness into my life and I only interact with happy people and have only happy experiences.",
#"I spread happiness to others and absorb happiness from others. I enjoy every moment of the day.",
#"Be happy is my motto and happiness is not a destination. It’s my way of life.",
#"I am living my life, feeling motivated and excited about the greatness I am creating, on a daily basis.",
#"I am going to make the best out of my life. I will appreciate all opportunities which are given to me and follow my way.",
Put your messages in an NSMutableArray and the following method will be good enough for your purposes I think:
+ (void) randomOrderedMutableArray:(NSMutableArray *) array
{
int count = [array count];
for (int i = 0; i < count; ++i)
{
int nElements = count - i;
int n = (arc4random() % nElements) + i;
[array exchangeObjectAtIndex:i withObjectAtIndex:n];
}
}
This code is not giving me any output or even setting up the accelerometer it seems. I am first and foremost trying to get the device to recognize the accelerometer and the thresh input. It is a simple accelerometer app where I can set up a thresh hold variable where I can then compare some values from previous and current accelerometer output. The thresh input is a simple text box for input. Any help would be appreciated.
#import "ViewController.h"
#interface ViewController (){
//set up variables for switch and BOOL variables
BOOL isStarted;
BOOL switchX;
BOOL switchY;
BOOL switchZ;
}
#end
#implementation ViewController
-(IBAction)startSensor:(id)sender{
//start with displaying the values...then move onto the just flash method
//set up the accelerometer function within the button press
[self.motionManager startAccelerometerUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
[self showAccelerationdata:accelerometerData.acceleration];
//print statements for future debugging. only in the log files though
if (error){
NSLog(#"%#", error);
}
}];
}
-(void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
currentAccelx = 0;
currentAccely = 0;
currentAccelz = 0;
previousAccelx = 0;
previousAccely = 0;
previousAccelz = 0;
//set up class for movement controls
self.motionManager = [[CMMotionManager alloc] init];
self.motionManager.accelerometerUpdateInterval = .1;
}
-(IBAction)checkSwitchx:(UISwitch *)sender{
if (sender.on){
switchX = TRUE;
}
else{
switchX = FALSE;
}
}
-(IBAction)checkSwitchy:(UISwitch *)sender{
if (sender.on){
switchY = TRUE;
}
else{
switchY = FALSE;
}
}
-(IBAction)checkSwitchz:(UISwitch *)sender{
if (sender.on){
switchZ = TRUE;
}
else{
switchZ = FALSE;
}
}
-(void)showAccelerationdata:(CMAcceleration)acceleration
{
self.view.backgroundColor = [UIColor whiteColor];
if ([thresh.text length] == 0){
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"numbers are blank!" message:#"Please enter numbers!"
delegate:self cancelButtonTitle:#"Ok!" otherButtonTitles: nil];
[alert show];
[alert resignFirstResponder];
}
else{
threshold = [thresh.text floatValue];
NSLog(#"%#", thresh);
}
}
-(void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Show the code where you set self.motionManager.
If you don't actually create a CMMotionManager, you are sending messages to nil in the startSensor: method, and you will observe that no accelerometer callbacks are executed.
I did not set up my CMMotionManager correctly it seems. After I looked at my setup it was pretty straight-forward on how to get everything to display correctly.
I am making a calculator using Xcode iOS SDK 6.1. However, I have faced a problem because my calculator cannot add the two numbers together. It seems that the calculator always give me the first number as an answer. Is there a way to solve the problem?
Here's the code:
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize FirstNumber,SecondNumber;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.FirstNumber.delegate = self;
self.SecondNumber.delegate = self;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)dealloc
{
[FirstNumber release];
[SecondNumber release];
[super dealloc];
}
- (IBAction)Calculate:(id)sender
{
NSString *finalNumberString;
int firstNumberInt, secondNumberInt, finalNumberInt;
firstNumberInt = [FirstNumber.text integerValue];
secondNumberInt = [SecondNumber.text integerValue];
finalNumberInt = firstNumberInt + secondNumberInt;
UIAlertView *alerting = [[UIAlertView alloc]initWithTitle:#"Answer" message:[NSString stringWithFormat:#"The answer is %d",finalNumberInt] delegate:nil cancelButtonTitle:#"Cancel" otherButtonTitles: nil];
[alerting show];
_FinalNumber.text = [[NSString alloc] initWithFormat:#"%i",finalNumberInt];
}
- (BOOL)textFieldShouldReturn:(UITextField*)textField
{
[FirstNumber resignFirstResponder];
[SecondNumber resignFirstResponder];
return NO;
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
if ([touch view] == self.view)
{
[FirstNumber resignFirstResponder];
[SecondNumber resignFirstResponder];
}
}
#end
It looks like you're showing the wrong value in the alert.
[NSString stringWithFormat:#"The answer is %d",secondNumberInt]
This should probably be
[NSString stringWithFormat:#"The answer is %d", finalNumberInt]
instead.
UIAlertView *alerting = [[UIAlertView alloc]initWithTitle:#"Answer" message:[NSString stringWithFormat:#"The answer is %d",secondNumberInt] delegate:nil cancelButtonTitle:#"Cancel" otherButtonTitles: nil];
secondNumberInt looks like it should be finalNumberInt
Incorrect values used as make the Alert message,
UIAlertView *alerting = [[UIAlertView alloc]initWithTitle:#"Answer" message:[NSString stringWithFormat:#"The answer is %d",secondNumberInt] delegate:nil cancelButtonTitle:#"Cancel" otherButtonTitles: nil];
[alerting show];
Change that part like this,
UIAlertView *alerting = [[UIAlertView alloc]initWithTitle:#"Answer" message:[NSString stringWithFormat:#"The answer is %d",finalNumberInt] delegate:nil cancelButtonTitle:#"Cancel" otherButtonTitles: nil];
[alerting show];
Try to put an NSLog between the two integer casts, and check if strings are read fine or if one of them is zero. If one of them is zero, probably you haven't connected the outlet to the UITextField in interface builder, or maybe you are just typing some weird string in the textfield: since you are casting to integer, you obiouvsly shouldn't put decimal digits.
firstNumberInt = [FirstNumber.text integerValue];
secondNumberInt = [SecondNumber.text integerValue];
NSLog(#"FirstNumber string %# integer %d", FirstNumber.text, firstNumberInt);
NSLog(#"SecondNumber string %# integer %d", SecondNumber.text, secondNumberInt);
finalNumberInt = firstNumberInt + secondNumberInt;
I want to show the user how long it took him or her to answer a certain amount of questions (for example 5) as an alert. I believe that I have the correct timer in place although I could be wrong. How would I finish the coding?
- (void)updateCounter:(NSTimer *)theTimer {
static int count = 0;
count += 1;
NSString *s = [[NSString alloc]
initWithFormat:#"%d", count];
self.timer.text = s;
[s release];
}
- (void)generate
{
int a = 1 + arc4random() % 12;
int b = 1 + arc4random() % 12;
int sum = a * b;
label.text = [NSString stringWithFormat: #"%d * %d = ", a, b];
label.tag = sum;
}
- (void)viewDidLoad
{NSLog(#"viewDidLoad");
[super viewDidLoad];
[self generate];
[self.answer becomeFirstResponder];
UIAlertView *alert;
{alert = [[UIAlertView alloc]
initWithTitle:#"Welcome to iCanMultiply!"
message:#"Tap 'Start' to start the game"
delegate: self
cancelButtonTitle:#"Start"
otherButtonTitles: nil];
}
[alert show];
[alert release];
[NSTimer scheduledTimerWithTimeInterval:1.0f
target:self
selector:#selector(updateCounter:)
userInfo:nil
repeats:YES];
}
- (IBAction)submit:(id)sender {
int num = [answer.text intValue];
UIAlertView *alert;
if (num == label.tag)
{
// answer was correct
alert = [[UIAlertView alloc]
initWithTitle:#"Correct"
message:#"Bet you can't do that twice!"
delegate:self
cancelButtonTitle:#"Next Question"
otherButtonTitles: nil];
// use the alert tag to mark that answer was correct
alert.tag = 1;
} else
{
// answer is incorrect
alert = [[UIAlertView alloc]
initWithTitle:#"Wrong!"
message:#"Sorry, try again..."
delegate:self
cancelButtonTitle:#"Try Again"
otherButtonTitles: nil];
}
// show and release the alert
[alert show];
[alert release];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (alertView.tag == 1)
{
[self generate];
answer.text = #"";
}
}
Store that value and then display it in an alert view.
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Title" message#"It took you %# seconds.",time delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
Let me know if the ,time works. I haven't tested this yet, but it should work.