0

I would like to define a number of variables that I will use in view controllers to set font size depending on whether the user is on an iphone or an ipad. So far I can define, say, a global float no problem. However, I am not able to include any conditional statements in my file. This works fine:

.h file:

#import <Foundation/Foundation.h>
@interface GlobalDeclarations : NSObject
extern float MyGlobalVariable;
@end

.m file:

#import "GlobalDeclarations.h"
@implementation GlobalDeclarations
float MyGlobalVariable = 0.0f;
@end

But I cannot modify my .m file to include any if statement at all - I always get the same error:

"expected idenitifer or ')'

For example, this version of the .m file produces the above error:

#import "GlobalDeclarations.h"
@implementation GlobalDeclarations
float MyGlobalVariable = 0.0f;
if(MyGlobalVariable > 2.0f)
{ 
   NSLog(@"inside if statement");
}

@end

I get the error even if I just write something like if(TRUE)...

How can I conditionally define globals in an attachment like this? What is wrong with the if-statement? Thanks for any suggestions.

1 Answers1

0

For variables you can only have declarations and limited initialisation expressions as the file level. If you need more complex initialisation you must put the code in a method, and Objective-C supports the method + initialize for doing class-wide setup.

Rewrite your code as:

#import "GlobalDeclarations.h"

@implementation GlobalDeclarations

float MyGlobalVariable = 0.0f;

+ initialize
{
   if(MyGlobalVariable < 2.0f)
   { 
      NSLog(@"inside if statement");
   }
}

@end

The + initialize method will get called before the first use of the class.

Note: for more obscure situations there is also a + load method which gets called even earlier than + initialize, and there are attributes you can use to mark any function to be called in a similar way.

CRD
  • 52,522
  • 5
  • 70
  • 86