Hey there, I'm a designer thats really new to programming with xcode or Objective-C in general. I'm trying to create a few simple apps to try to get a better hang on programming the iPhone. Currently, I'm working on a very basic app which has 3 textfields, a name field and two number fields, and when you click the button, it shows in the label "name, the answer is answer" problem is, when i click the button, nothing is appearing in the label.
im pretty sure i have the code done right, i may be mistaken, i think i might have missed an outlet or something silly of the like. this is the part i get really lost on. any suggestions?
the .h:
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#interface fordaddyAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
IBOutlet UITextField *name;
IBOutlet UITextField *myInt1;
IBOutlet UITextField *myInt2;
IBOutlet UILabel *sum;
IBOutlet UIButton *click;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
-(IBAction)click:(id)sender;
#end
the .m:
#import "fordaddyAppDelegate.h"
#implementation fordaddyAppDelegate
#synthesize window;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
[window makeKeyAndVisible];
}
-(IBAction)click:(id)sender;
{
int sum;
sum = myInt1, myInt2;
NSLog (name, #", the answer is %i", sum);
}
- (void)dealloc {
[window release];
[super dealloc];
}
#end
and im terribly sorry in advance, the preview doesnt look to pretty :/
your problem is that you are just writting a message to the console, not displaying the result in the label...
Here's what it should be:
- (IBAction)click:(id)sender {
int sum = [myInt1.text intValue] + [myInt2.text intValue];
label.text = [NSString stringWithFormat:#"%# the answer is %d", name.text, sum];
}
That makes a variable 'sum' which is the result of the integer values of the text fields being added together. you access the string of a UITextView by using the .text. Then you have to convert it into an integer for addition, so you call the intValue method on it. You then make an NSString with stringWithFormat, and have it contain the name.text and the sum. I would highly recommend doing some more reading about Objective-C in general before you start with all this GUI stuff... just a suggestion.
Your problem is this:
int sum;
sum = myInt1, myInt2;
sum is an integer. myInt1 and myInt2 are UITextFields. The comma does not do what you're expecting.
You need to extract the intValue from each of the textfields, and add them together using a "+" (just like you would with regular math).
Related
Is there any alternative to use like tag to property of UIView? The thing is I'd like to pass UITextField some NSInteger. Way to do is tag. But I want to pass 2 different NSInteger.
Any ideas?
You could subclass UITextField and add two NSInteger properties to the class.
#interface CustomTextField : UITextField
#property (nonatomic, assign) NSInteger x;
#property (nonatomic, assign) NSInteger y;
#end
You can attach any data to any object using an Associative Reference. This is a very handy approach. It even correctly handles memory management. I sometimes use a category to wrap these so I can create new properties on an existing class. For example, in one project I'd like every view controller to know about a special label (like how they all know about navigationController). I do it this way:
#interface UIViewController (MYSpecialViewController)
#property (nonatomic, readwrite, strong) UILabel *specialLabel;
#end
#implementation UIViewController (MYSpecialViewController)
static const char kMySpecialLabelKey;
- (UILabel *)specialLabel
{
return objc_getAssociatedObject(self, &kMySpecialLabelKey);
}
- (void)setSpecialabel:(UILabel *)value
{
objc_setAssociatedObject(self, &kMySpecialLabelKey, value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
#end
You can find a simple working example using a UIAlertView in the iOS5:PTL sample code for Chapter 3.
Take the general, object-oriented solution, but remember you can a stuff lot of data into a tag:
- (uint32_t)pack:(uint16_t)a with:(uint16_t)b {
return (uint32_t)(a << 16 | b);
}
- (uint16_t)getA:(uint32_t)pair {
return (uint16_t)((pair & 0xffff0000) >> 16);
}
- (uint16_t)getB:(uint32_t)pair {
return (uint16_t)(pair & 0xffff);
}
// use it
- (void)setupSomeView {
someView.tag = [self pack:1024 with:2048];
}
- (IBAction)someControlEventHappened:(id)sender {
NSLog(#"%d %d", [self getA:sender.tag], [self getB:sender.tag]);
}
Caveats:
#RobNapier's answer is more general, more correct. The only
advantage this way is that it's quick and dirty
Works for pairs of unsigned ints < 32k
Works NSInteger implementations >= 32 bits, which is everywhere, I think.
hey guys i'm making an app that has 2 views. the first view is where the user inputs the numbers and when they hit calculate button.. its takes them to a new view where the answer is displayed on a textfield. the calculation is handled by a different file. "calc.h " and "calc.m"
this is the main view files (the view where the user enters the numbers )
#import <UIKit/UIKit.h>
#interface test2ViewController : UIViewController {
IBOutlet UITextField *num1; //input number 1
IBOutlet UITextField *num2; // input number2
}
#property (nonatomic,retain) UITextField *num1;
#property(nonatomic, retain)UITextField *num2;
-(IBAction)calculate:(id)sender; //the calculate button
-(IBAction)exit:(id)sender;
#end
the answer is displayed in a different view that shows up when the user hits the calculate button. below is the code for that !
#import "test2ViewController.h"
#import "answer.h"
#import "calculate.h"
#implementation test2ViewController
#synthesize num1,num2;
-(IBAction)calculate:(id)sender{
calculate *testclass = [[calculate alloc]init];
answer *view = [[answer alloc]initWithNibName:nil bundle:nil];
[self presentModalViewController:view animated:YES];
int i = [[num1 text] intValue];
testclass.number1 = i;
int j = [[num2 text] intValue];
testclass.number2 = j;
[testclass calc];
}
".h" file of the view that displays the answer
#import <UIKit/UIKit.h>
#interface answer : UIViewController {
IBOutlet UITextField *text;//textfield to display answer
}
#property(nonatomic,retain) UITextField *text;
-(IBAction)back:(id)sender;
#end
".m" file
#import "answer.h"
#import "test2ViewController.h"
#import "calculate.h"
#implementation answer
#synthesize text;
-(IBAction)back:(id)sender{
test2ViewController *view = [[test2ViewController alloc]initWithNibName:nil bundle:nil];
[self presentModalViewController:view animated:YES];
}
the next is an objective c class file that does the calculation. it has one function that does the calculation and here is the ".h" and ".m" file
".h"
#import <Foundation/Foundation.h>
#interface calculate : NSObject {
int number1;
int number2;
NSString *ans;
}
#property int number1;
#property int number2;
#property (nonatomic , retain) NSString *ans;
-(void)calc;
#end
".m"
#import "calculate.h"
#import "answer.h"
#import "test2ViewController.h"
#implementation calculate
#synthesize number1,number2,ans;
-(void)calc{
int i = number1 + number2;
answer *ans1 = [[answer alloc]init];
ans = [NSString stringWithFormat:#"%d",i];
ans1.text.text = ans;
}
#end
so as you can see the above function calculates the answer..puts it into a string and sets that to the textfield. but the textfield doesn't show anything..so the problem here is that i cannot access the textfield even though i created an object from it....
Im a bit confused to what your trying to accomplish, do you want to use an NSString or the text UITextField in another class? If thats the case give the string that is carrying whatever you want to be displayed a #property, then set whatever you want the strings value to it, next import the calc.h (#import "calc.h") in the second class, then in the interface create this calc *getString; create a #property for that, #synthesize it. Then to get the value of the string from calc do something like this getString.SomeStringName, now you are able to do whatever you want with it.
I think this is what you want? if not feel free to comment. Good Day :)
Edit: Im going to give you an example because this is a bit confusing the way i wrote it lol
So here is your calc.h file, also remember im typing this online and not in xcode, so if i spell something wrong or make a simple mistake, thats why:
#interface calc : UIViewController {
NSString *answer;
}
#property (nonatomic, retain) NSString *answer;
#end
Your .h could have more
Now lets hop into your .m
#implementation calc
#synthesize answer;
//do all the work to get the answer, once you have it do this
[answer retain];
//load your new view controller
Lets hop into your other view controller that will be loaded
this is .h file of it
#import "calc.h"
#interface secondController : UIViewController {
calc *getAnswer;
}
#property (nonatomic, retain) calc *getAnswer;
#end
Then go to your .m
#implementation secondController
#synthesize getAnswer;
-(void)viewDidLoad{
WhateverYouWantTheStringToBeSetTo.text = getAnswer.Answer;
}
This should then grab the string from the other controller and allow you to use it in this one..
Hope this helps :)
The problem is that your "ans" UIViewController did not load yet.
The most standard way to do this is to give your UIViewController "ans" a #property with the result. Then in the "ans" viewDidLoad method, set the text field to the appropriate value.
I am new to objective C and I have a c++ background. I want to display a value in the label on the screen. I am calling the label value from the MainView.m. However, the label becomes blank after I click a button instead of printing a value. What is the problem? Here is the code.
MainView.h
#interface MainView : UIView {
int a;
}
-(int) vr;
#end
MainView.m
-(int) vr
{
return 100;
}
#end
MainViewController.h
#interface MainViewController : UIViewController {
IBOutlet UILabel *myLabel;
NSMutableString *displayString;
MainView *view1;
}
#property (nonatomic, retain) UILabel *myLabel;
#property (nonatomic, retain) NSMutableString *displayString;
(IBAction)showInfo;
(IBAction) pressButton:(id) sender;
#end
MainViewController.m
#synthesize myLabel, displayString;
-(IBAction) pressButton:(id) sender{
[displayString appendFormat:#"%i", view1.vr];
myLabel.text = displayString;}
- (void)viewDidLoad {
view1 = [[MainView alloc] init];
[super viewDidLoad];}
- (void)dealloc {
[view1 dealloc];
[super dealloc];}
I have not mentioned code that had been auto generated. This is enough to get the whole picture. I tried a lot to debug this thing. I believe that IBAction carries out direct command such that
myLabel.text = #"string";
but it does not invoke any method or class. Any subtle ideas? Thanks.
Few issues:
1
In MainView.h you declare -(id) vr;
And in MainView.m it returns int.
2
Maybe pressButton is not connected to the right event in Interface Builder (it is usually touch up inside).
Try to write to log in this method.
3
Maybe myLabel is not connected to the label in the Interface Builder.
Try to set tome hard-coded string to label's text property.
4
Do you initiate view1 in some place?
Can you post this piece of code too?
5
You can use [displayString appendFormat:#"%i", view1.vr];...
EDIT (due to changes in question):
6
The line [super viewDidLoad]; should be the first line inside viewDidLoad.
7
[view1 dealloc]; - never call dealloc directly on objects. Call release instead. The only place, where you can and should use dealloc is the line [super dealloc]; inside dealloc method.
8
When you format your question/answer in Stack Overflow, remember that each code line should start with at least 4 spaces (or tab). Try reformatting you question by adding 4 spaces in the beginning of each code line.
9
I think that displayString is not initiated. Add the next line in the viewDidLoad: displayString = [NSMutableString new];
In my code, there is an memory leak, when the Keyboard appears for the first time when I am about to enter values in the UITextField. Can someone please give me some idea about this.
In the Interface File
IBOutlet UITextField *userEmail;
#property (nonatomic, retain) IBOutlet UITextField *userEmail;
Implementation File
#synthesize userEmail;
- (void)dealloc
{
[userEmail release];
}
- (void)viewDidUnload
{
self.userEmail = nil;
}
-(IBAction) emailOver:(id)sender{
[sender resignFirstResponder];
}
In the one of the functions NSLog(#"User Email: %#",[userEmail text]); Memory Leak occurs when the keyboard appears for the first time Do I have implement UITextFieldDelegate? Thanks
Consider that there's a bug in the iPhone simulator: if you write an almost empty project, putting only a UITextField in the XIB, and no code, you'll have a leak when you tap on the UITextField. On the contrary, if you try to build and run on the device, you'll have no leak. So It may be your case!! Give it a try, and let us know..
One problem is that your dealloc method is missing the MANDATORY [super dealloc] line.
- (void)dealloc
{
[userEmail release];
[super dealloc];
}
You don't need IBOutlet defined twice. One or the other should do.
UITextField *userEmail;
#property (nonatomic, retain) IBOutlet UITextField *userEmail;
I don't see anything else in your code that would cause a problem. What other methods do you have in your #implementation file.
I think you're right caprosky. Using a very simple test project I've Run With Monitoring Tools -> Leaks and as soon as I click on UITextField there is a memory leak that rises continuously.
I'll forget this for now and keep it in mind next time I'm using a UITextField (no
I am very new to objective-c and having a problem to initialize an object in view controller. The problem I am having is that when setTemp method is called, "0" is printed on the screen instead of the value of cTemp I would like it to be. Can anyone help me on this problem?
Below are excerpts of the code I have.
SJT.h
#import <Foundation/Foundation.h>
#import <stdlib.h>
#interface SJT : NSObject {
int cTemp;
}
- (int) newTemp;
#end
SJT.m
#import "SJT.h"
#implementation SJT
- (int) newTemp
{
cTemp = 25 + rand() % 8;
return cTemp;
}
#end
SJTViewController.h
#import <UIKit/UIKit.h>
#class SJT;
#interface SJTViewController : UIViewController {
IBOutlet UILabel *temp;
SJT *sjt;
}
#property (retain, nonatomic) UILabel *temp;
#property (retain, nonatomic) SJT *sjt;
- (IBAction) setTemp: (id) sender;
#end
SJTViewController.m
#import "SJTViewController.h"
#import "SJT.h"
#implementation SJTViewController
#synthesize temp;
#synthesize sjt;
- (IBAction) setTemp: (id) sender
{
NSString *tempText = [[NSString alloc] initWithFormat:#"%d",sjt.newTemp];
temp.text = tempText;
[tempText release];
}
.
.
.
#end
The problem is that you're mistaking property syntax for a method call; i.e.
sjt.newTemp
would become a call to [sjt newTemp]. Which happens to be exactly what you want, except that you have not specified in your header/implementation that there actually is a property called newTemp.
So, in this scenario what you want to do is either a) define the property in the header:
#property(nonatomic, readonly) int newTemp;
or b), just call the method newTemp:
[sjt newTemp]
Are you certain that sjt is not nil? You don't provide the code where and instance of SJT is constructed. In Objective-C you can call a method on a nil reference without error, and if you do so on a method that returns an int it will return 0.
So sjt.newTemp will return 0 if sjt is nil.
Both Jacob and teabot have pointed out valid possible reasons -- which one is correct (or both!) depends on pieces of code we can't see in your post.
Based on what you've written so far, you might not be thinking of newTemp as a property, but more as a function call, so I would suggest changing your code to:
- (IBAction) setTemp: (id) sender {
int tempInt = [self.sjt newTemp];
self.temp.text = [NSString stringWithFormat:#"%d", tempInt];
}
which is functionally equivalent. Note the convenience constructor stringWithFormat: returns an autoreleased object, which is then retained by the retain property text of the temp UILabel.
The other thing to double-check in your code is that self.sjt is not nil, which is exactly what teabot said. Objective-C returns 0 on method calls invoked on a nil pointer.