Reputation: 2171
I am trying to use a variable integer throughout multiple methods in my view controller. The secondsLeft variable works fine, but the otherNumber variable won't work. I get the error: initializer element is not a compile-time constant. Any ideas on how I am supposed to do this? THank you!
@interface ViewController ()
@end
@implementation ViewController
@synthesize countDown,Timerlbl;
int secondsLeft = 500;
int otherNumber =[(AppDelegate *)[UIApplication sharedApplication].delegate otherNumber];
Upvotes: 0
Views: 3271
Reputation: 601
You can't declare a variable like this because the compiler can't create an instance of AppDelegate
and ask it what the value of otherNumber
should be.
Depending on how it's being used, it might be better not to define the otherNumber
variable at all, and instead retrieve it from AppDelegate
each time it is used. This might mean a little more typing, but it does mean you'll always get the latest correct value of otherNumber
Also, it's a good idea in general to use NSInteger
instead of int
when defining integer variables.
Upvotes: 0
Reputation: 24477
The problem is that you have declared otherNumber
as a global variable and the compiler expects the initial assignment to be a compile-time constant. [delegate otherNumber]
results in a selector invocation and this is not a compile-time constant.
The solution is to move the assignment into code. For example:
- (id)init
{
self = [super init];
if(self) {
otherNumber = [(AppDelegate *)[UIApplication sharedApplication].delegate otherNumber];
}
return self;
}
As another note, global variables are generally inadvisable in Objective-C. @property
values are generally more recommended. Not only that, your ViewController
class now has a dependency with your AppDelegate
. Since your AppDelegate
most likely is the one responsible for instantiating your ViewController
, consider having it inject in the value of otherNumber
. For example:
@interface ViewController ()
@property (nonatomic, assign) int otherNumber;
@end
- (id)initWithSomeNumber:(int)otherNumber
{
self = [super init];
if(self) {
self.otherNumber = otherNumber;
}
return self;
}
Upvotes: 2
Reputation: 8511
I assume that AppDelegate
is the name of your app delegate class?
Have you tried adding an import for your AppDelegate, like this...
#import "AppDelegate.h"
@interface ViewController ()
Upvotes: 0