xcode - execution error with string - ios

I am trying to store and load some text from global variable in x-code. I declare it in main.m, outside of the main function. Then when I want to access it, I use extern. The application crashes after I click the saveButton second time with text in it. It seems like there would be some error rewriting the global labelString string. Can you figure this puzzle out please?
EDIT: Thanks to BKC, I have made some minor changes in the code, however I still get the same error. The code is updated.
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
#property (retain, nonatomic) IBOutlet UITextField *field;
- (IBAction)saveButton:(id)sender;
FOUNDATION_EXPORT NSString *labelString;
FOUNDATION_EXPORT NSString *separator;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize field;
NSString *labelString = #"";
NSString *separator = #"|<->|";
- (IBAction)saveButton:(id)sender {
if([field.text length] != 0) // if field isn't blank
{
if([labelString length] == 0) // nothing stored in labelString
{
labelString = field.text;
}
else // if something is already stored in labelString
{
NSString *str = [NSString stringWithFormat:#"%#%#%#", labelString, separator, field.text];
labelString = str;
}
field.text = #"";
}
}
- (void)viewDidLoad
{
[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.
}
- (void)dealloc {
[field release];
[super dealloc];
}
#end
Thank you.

The way you are defining the variable isn't right way. i use any global variable in my project something like this..
Declare the variable in .h file
FOUNDATION_EXPORT NSString *labelString; // Use extern if mixing with C++
Define the varibale in .m file
NSString *labelString = #"";
Include the header wherever you want to use that. i think in your code its crashing because of multiple time definition of labelString variable.

Related

iOS use variable with another m file when button click change it

i need to change urlStr variable when my button clicked from another file. I'm writing my files; I explained everything i think too easy but hard for me please help me.
Thanks a lot.
Request.h file
#import <Foundation/Foundation.h>
#interface Request : NSObject{
}
Request.m file
#import "Request.h"
#import "MyViewController.h"
static NSString * const urlStr = #"http://google.com";
// I WANT TO CHANGE THIS urlStr WHEN storebutton CLICKED
#interface Request () {
BOOL reachable;
}
MyviewController.h file
#import <UIKit/UIKit.h>
#interface MyViewController : UIViewController{
}
#end
MyViewController.m file
#import "MyViewController.h"
#interface MyViewController ()
#end
#implementation MyViewController
- (void)viewDidLoad
{
[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.
}
-(void)storebutton
{
NSString *urlStr = #"http://yahho.com"; // WHEN MY store button click action
}
#end
Make urlStr as static variable only, then create a static setter method for it inside Request.m and declare it in Request.h as shown below.
+ (void)setURLString:(NSString *) urlString
{
urlStr = urlString;
}
call this method on done button press as
-(void)storebutton
{
NSString *newURL = #"http://yahho.com";
[Request setURLString:newURL];
}

Objective-C: Accessing variables from another class [duplicate]

This question already has answers here:
Passing data between view controllers
(45 answers)
Access Variable from Another Class - Objective-C
(2 answers)
Closed 8 years ago.
I'm creating a project so that I have two view controllers, connected by a modal segue with an identifier "login_success".
In the primary view controller, I have a text field that takes the input of whatever the user types, and a button to perform the segue.
In the next controller, I have a label that is supposed to print out whatever the user typed.
My code:
DICViewController.h (First View Controller):
#import <UIKit/UIKit.h>
#interface DICViewController : UIViewController <UITextFieldDelegate>
#property (weak, nonatomic) IBOutlet UITextField *txtUsername;
- (IBAction)sigininClicked:(id)sender;
- (IBAction)backgroundTap:(id)sender;
#end
DICViewController.m:
#import "NewViewController.h"
#interface DICViewController ()
#end
#implementation DICViewController
- (void)viewDidLoad
{
[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.
}
- (IBAction)sigininClicked:(id)sender {
{
[self performSegueWithIdentifier:#"login_success" sender:self];
}
}
- (IBAction)backgroundTap:(id)sender {
[self.view endEditing:YES];
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return YES;
}
#end
NewsViewController.h (The other view controller):
#import <UIKit/UIKit.h>
#interface NewViewController : UIViewController
#property (weak, nonatomic) IBOutlet UILabel *steamId; //my label
#end
NewsViewController.m:
No code was added here.
Thanks in advance to anyone that can help.
Again, I would like to be able to set the text in the label equal to the text the user types in the text field.
When performing a segue the preferred way to pass data from one view controller to another is to make use of the method -prepareForSegue:sender:.
In your case the following lines of code should work:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
NewsViewController *newsVC = segue.destinationViewController;
[newsVC view]; // this loads the view so that its subviews (the label) are not nil
newsVC.steamID.text = self.txtUsername.text;
}
(Place this method anywhere in your DICViewController.m.)
I think The better way is to set global variables. Just make normal class
variables.h
#import <Foundation/Foundation.h>
#interface variables : NSObject {
float VariableYouWant;
}
+ (_tuVariables *)sharedInstance;
#property (nonatomic, assign, readwrite) float VariableYouWant;
and
variables.m
#import "variables.h"
#implementation variables
#synthesize VariableYouWant = _VariableYouWant;
+ (_tuVariables *)sharedInstance {
static dispatch_once_t onceToken;
static variables *instance = nil;
dispatch_once(&onceToken, ^{
instance = [[variables alloc] init];
});
return instance;
}
- (id)init {
self = [super init];
if (self) {
}
return self;
}
#end
Way to use:
import header file of variables and
variables *globals = [variables sharedInstance];
and simply access variables with
globals.VariableYouWant =

I cannot set text of my Custom Text Field

I am trying to make a custom TextField (KSTextField). I inherited my text field from UITextField. As you can see my KSTextField.h file below.
#import <UIKit/UIKit.h>
#import <UIKit/UITextField.h>
#interface KSTextField : UITextField {}
#end
In my KSTextField.m i tried to set a dummy text attribute. But it doesn't work. Is super.text usage wrong?
My main purpose is, making a custom UITextField that only allows for upper case characters which is needed for my project.
#import "KSTextField.h"
#implementation KSTextField
- (id)init {
self = [super init];
super.text = #"help";
return self;
}
- (void)textFieldDidChangeForKS:(KSTextField *)textField {
self.autocapitalizationType = UITextAutocapitalizationTypeAllCharacters;
NSString *textToUpper = [textField.text uppercaseString];
[self setText:textToUpper];
}
#end
And also mine ViewController.h is below
#import <UIKit/UIKit.h>
#import "KSTextField.h"
#interface ViewController : UIViewController
#property (nonatomic, copy) IBOutlet KSTextField *txtKsName;
#end
Here's my ViewController.m which i want to set my KSTextField.text
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.txtKsName = [[KSTextField alloc] init];
}
Delegate events do not solve my issue. Because i'll add much more features later. It will be my custom textfield thanks!
The answer is: you're doing it wrong! You don't have to subclass to allow uppercase characters only. Use a UITextFieldDelegate:
http://developer.apple.com/library/ios/#documentation/uikit/reference/UITextFieldDelegate_Protocol/UITextFieldDelegate/UITextFieldDelegate.html
Using the textField:shouldChangeCharactersInRange:replacementString: method, you can say whether on not the character typed is allowed to be added to the box.
Try something like this:
- (BOOL)textField:(UITextField *)field shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)characters
{
NSCharacterSet *blockedCharacters = [[[NSCharacterSet uppercaseLetterCharacterSet] invertedSet] retain];
return ([characters rangeOfCharacterFromSet:blockedCharacters].location == NSNotFound);
}

Variable in my iOS app?

I can't belice I am asking this, but im very crazy with this variable stuff.
I want to save a username information. I load them at the load of my view. After this I will get the information when I click on a button.
Here is my code:
#interface SelfViewController : UIViewController
{
NSString *usernameString;
}
- (void)viewDidLoad
{
usernameString = #"test";
}
- (IBAction)goToProfileButtonPressed:(id)sender
{
NSLog(#"%#", usernameString); //CRASH BAD EXEC
}
What did I wrong????
Change your .h file to:
#interface SelfViewController : UIViewController {
    NSString *usernameString;
}
#property (retain, nonatomic) NSString *usernameString;
Then in your .m file:
#synthesize usernameString;
- (void)viewDidLoad {
     self.usernameString = #"test";
}
- (IBAction)goToProfileButtonPressed:(id)sender {
    NSLog(#"%#", self.usernameString); // "self." can be omitted, but it is best practice not to
}
- (void)dealloc {
[usernameString release];
[super dealloc];
}
The problem is that you assign usernameString to an autoreleased string object. By the time the button is pressed, usernameString has been released and has become garbage memory. By retaining it (and subsequently releasing it in -dealloc to avoid a leak) you know that it will not be prematurely released.
You need to synthesize the ivar and add it as a property. (For not-ARC compiling):
in the .h:
#interface SelfViewController : UIViewController
{
NSString *usernameString;
}
#property (nonatomic, retain) NSString *usernameString;
in the .m:
#synthesize usernameString;

Property implementation must have declaration in interface

When I try to compile this I get this error. What do I need to add for the property declaration in the interface? If textBox is an instance variable, why does it need to be declared as a property?
ViewController.h
#import <UIKit/UIKit.h>
#interface TNRViewController : UIViewController {
IBOutlet UITextField *textBox;
IBOutlet UILabel *label;
}
- (IBAction)button:(id)sender;
#end
ViewController.m
#import "TNRViewController.h"
#implementation TNRViewController
#synthesize textBox;
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)dealloc {
[textBox release];
[label release];
[super dealloc];
}
- (IBAction)button:(id)sender {
NSString *Name = textBox.text;
NSString *Output = Nil;
Output = [[NSString alloc] initWithFormat:#"%# says: Hello World!", Name];
label.text = Output;
[Output release];
}
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
[textBox resignFirstResponder];
return YES;
}
#end
textBox needs to be declared as a property because you are #synthesizing it in your implementation.
You need to either:
Add the #property declaration for textBox in your interface.
OR, You could remove the #sythesize line from your implementation if you don't plan on needing the setter/getter methods.
by writing #synthesize textBox in your implementation the compiler generates 2 methods for you automatically.
-(UITextField*)textBox
-(void)setTextBox:(UITextField *)textBox
To be accessed these need to be defined in the class' interface. Objective-C for the iPhone has a nifty shortcut for declaring these two methods, the #property directive. You can also include information about how the variable should be stored in this directive.
#property (nonatomic, retain) IBOutlet UITextField * textBox
Would give you your IBOutlet for a text field. It is also a stand in for the 2 methods above. It tells us that the textBox is retained by your class. By always using the setter and getter methods for a variable you can avoid releasing an object and referencing the instance variable later, when it may not be safe. It is best practise to do this. You would access the text field from within your class by doing
[self.textBox setText:#"aString"];
self.textBox.text = #"aString";
(the lines above are equivalent)
This error happened when I added a pod. I ended up deleting a updating my pod file and it fixed the error.

Resources