Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

chrono1081

macrumors G3
Original poster
Jan 26, 2008
8,456
4,164
Isla Nublar
Hi guys,

I was referencing one of my Objective-C books* and noticed that there were instance variables defined in the implementation section of a class. I assume because the users in the class don't need to know about the instance variables, just the interface file but it leads me to two questions:

1. When did this start? I'm pretty sure its new as I've never seen it before. (Some internet research suggests its new in Xcode 4.2, but I can't find anything in Apple's docs about it).

2. If it's Xcode only, wouldn't this be a bad way to do things since some other IDE's support Objective-C, but not necessarily putting the ivars in the implementation section?

The book is the newest version (4.0) of Steve Kochan's programming in Objective-C. I have and read the 2.0 version and the classes do not have ivars in the implementation section, but I couldn't find in the new version where this difference, and the reasoning behind it is mentioned.
 

KnightWRX

macrumors Pentium
Jan 28, 2009
15,046
4
Quebec, Canada
Maybe post some code of what you mean ? Are you sure these are "instance" variables ?

Usually, when doing this for methods, it's to make them "private". For variables, you can do so in the interface section using the @private directive, so no need to stick them in the implementation file.

However, I do use variables in implementation files, as a global symbol. These I use as "class variables", variables that survive and are accessible by all instances of the class or by class methods.
 

chrono1081

macrumors G3
Original poster
Jan 26, 2008
8,456
4,164
Isla Nublar
Here is some code straight from the book:

Code:
@interface Fraction : NSObject
{
    
}

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

@end

Code:
@implementation Fraction
{
    int numerator;
    int denominator; 
}

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

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

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

@end

I did see in this version of the book it confirms that the change is new to Xcode 4.2, but that it will explain the changes later. I use this book only for reference so I'm not sure where it explains the changes (I haven't found it yet).
 
Last edited:

Catfish_Man

macrumors 68030
Sep 13, 2001
2,579
2
Portland, OR
This is a new feature of the most recent clang (aka Apple LLVM) compiler, specifically. It's useful to hide private state of classes.
 

kainjow

Moderator emeritus
Jun 15, 2000
7,958
7
I forgot about this feature. I like having only public things in the header, and this makes it even more cleaner. FWIW, it works with the Snow Leopard Xcode 4.2 build.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.