I understand that few users have already asked about the error listed in Title line. However, I am a novice in Objective-C programing and I am not able to connect how the responses on other pages answer why I am getting an error for this program.
Thanks!
@interface ClassA:NSObject
{
int x;
}
-(void)initVar:(int) a;
@end
@implementation ClassA
-(void)initVar:(int) a
{
x=a;
}
@end
@interface ClassB:ClassA
-(void)printVar;
@end
@implementation ClassB
-(void)printVar
{
NSLog(@"X = %i", x);
}
ClassA *a= [[ClassA alloc] init]; // shows error: Initializer element is not a compile-
// time constant.
[a initVar:100];
@end
Objective-C is a strict superset of C. It’s illegal in C to have any executable code outside of a function (or method in Objective-C).
If your intention is to have a global variable of type
ClassA, the best solution (IMHO) is to use a class method to access it. This will also allow you to do your initialisation.The
dispatch_once()call is the currently favoured idiom to ensure the initialisation code only gets executed once and is all done in a thread safe way.You should choose a different name for your
initVar:method. Theinitprefix is a convention that signifies an object initialisation method (likeinit).