user1107888
user1107888

Reputation: 1525

Objective C private instance variables error

I am just starting out with Objective C trying out a sample program about fractions from the Programming in Objective C book:

#import <Foundation/Foundation.h>

//---- @interface section ----

@interface Fraction: NSObject

-(void)   print;
-(void)   setNumerator: (int) n;
-(void)   setDenominator: (int) d;

@end

//---- @implementation section ----

@implementation Fraction
{
 int  numerator;
 int  denominator;
}
-(void) print
{
  NSLog (@"%i/%i", numerator, denominator);
}

-(void) setNumerator: (int) n
{
  numerator = n;
}

-(void) setDenominator: (int) d
{
  denominator = d;
}

@end

//---- program section ----

I keep getting the inconsistent instance variable specification error for the instane variables numerator and denominator.If I move the declarations to the @interface section, the error goes away but I want to know why I am getting this error? I am using Xcode 3.6.2 on Snow Leopard 10.6.8

Upvotes: 2

Views: 3491

Answers (2)

Daniel Mart&#237;n
Daniel Mart&#237;n

Reputation: 7845

Instance variables in @implementation blocks are only supported since Xcode 4.2 (LLVM compiler version 3.0). You must upgrade your development tools to take advantage of this feature.

The motivation for this language feature is to achieve better information hiding in your class structure. That means that clients of your interface (your .h file) may not need to be aware of the ivars the class is using, so they are "hidden" in the implementation file.

Another way to hide ivar is to include them in a class extension in your implementation (.m) file:

// Fraction.m

@interface Fraction () {
  int  numerator;
  int  denominator;
}

@end

@implementation Fraction
// ...
@end

But it also requires Xcode 4.2+ and a modern runtime environment.

For complete compatibility with old compilers, ivars can only be placed in the interface section of the .h file.

Upvotes: 3

faffaffaff
faffaffaff

Reputation: 3559

You're getting an error because ivars needs to be declared in the interface.

By the way, you're using a veeeeery old version of xcode (probably too old to submit to the appstore), so you might want to look into getting xcode 4.6. There's also been many updates to the Objective-C language. In modern objective-c, there is no longer a need to manually declare ivars like this.

If you REALLY would like to keep ivars out of the header file, you can declare them in an empty category interface (also called a "class extension") like this, in the .m file:

@interface YourClass() {
  ivars here
}
@end

Upvotes: 3

Related Questions