0

My problem is that I am declaring some strings, arrays.... in an implementation file, and I wanna a kind of include (like in PHP) to avoid declaration errors...

For example in the code bellow coordi (see the end of the last line) an NSString which is declared in another implementation file, in my code now, xCode is giving me an error saying that coordi is not declared, however it is declared in another implementation file.

- (IBAction)searchButton:(id)sender {   
   if (_searchQuery.text.length < 3 ) {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No destination !" message:@"Please enter a destination !" delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
    [alert show];
} else {
[self performSegueWithIdentifier:@"seg_map" sender:self];
    NSString *query = [[self.searchQuery text] stringByReplacingOccurrencesOfString: @" " withString:@"\%20"];       
    NSURL *jsonURL = [NSURL URLWithString:[NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/directions/json?origin=%@&destination=%@&sensor=false", coordi, query]]; }}

Any ideas on how to solve this issue ?

Al_fareS
  • 725
  • 1
  • 9
  • 18

3 Answers3

3

You should declare this as a const string. Then in a .h file you should specify the const using the extern specifier. This will make it available to any files the import that .h file.

This is better answered here: Constants in Objective-C

Community
  • 1
  • 1
atreat
  • 4,243
  • 1
  • 30
  • 34
2

in the header file of the .m file where your coordi variable has been defined, you have to do the declaration.

FOUNDATION_EXPORT NSString *coordi; // Can use extern if mixing with C++

and in your implementation file you can do

NSString *coordi= @"myString";

now whereever you include the header you will have access to the variable.

bhawesh
  • 1,310
  • 2
  • 19
  • 57
1

(I'll assume the coordi variable is in a class called YourClass)

Create the coordi variable as static, just bellow your @implementation YourClass, like this

static NSString *coordi;

in YourClass.h

create a method with a + instead of a - (These works like static methods):

+ (void)setCoordiString:(NSString*)string;

in YourClass.m

    + (void)setCoordiString:(NSString*)string{
         coordi = string;
    }

Now, in whatever class you want to set YourClass's coordi string just do this:

First, import YourClass.h:

#import "YourClass.h"

Then this code right in the moment you want to set coordi:

[YourClass setCoordiString:@"Your String Here!"];

Hope it helped!