-3

How can I make instance variable inside class @implementation in Objective-c?

Matt Taylor
  • 3,360
  • 1
  • 20
  • 34
Dusan
  • 5,000
  • 6
  • 41
  • 58
  • 1
    check out http://stackoverflow.com/questions/6785765/instance-variables-declared-in-objc-implementation-file – Sudha Tiwari Feb 15 '13 at 11:53
  • Reason I am asking this is because the way I tried to declare variable inside @implementation seems to produces some kind of global variable... so this question is no so stupid, so please, do not down vote, it has a syntax glitch compared to C#, java and other OOP languages. – Dusan Feb 15 '13 at 11:56

4 Answers4

4

Put them in curly braces, like so:

@implementation {
    id anIvar;
}
Carl Veazey
  • 18,392
  • 8
  • 66
  • 81
  • What exactly happens when variable declaration is not placed in curly braces? What kind of variable do I get? – Dusan Feb 15 '13 at 12:09
  • @Dusan I think it would be technically a global variable that is only visible within either the implementation block, or perhaps the file it was defined in. I think it'd act similarly to a static variable. – Carl Veazey Feb 15 '13 at 12:12
  • Yes it seems indeed something like that. Thanks! – Dusan Feb 15 '13 at 12:17
  • Indeed, without the brackets its a global variable. Meaning - just once instanciated - not one for each class, slightly different syntax accessing it plus linking issues when the same "global" variable name is used in other classes. But AFAIK, the brackets follow an `@interface` key word, not `@implementation`. That may well be a "second" `@interface` within the *.m file. – Hermann Klecker Feb 15 '13 at 12:26
  • You can actually put the brackets after the @implementation, I think I learned first of this from the modern obj-c session at WWDC 2012. – Carl Veazey Feb 15 '13 at 12:31
  • @Dusan You get a global variable. It's slightly different to static in that it's exposed out at linker time meaning if you have `CGFloat x;` in two `.m` files you will get a duplicate symbol linker error whereas `static CGFloat x;` in two files would give you two variables called `x`, each only visible inside it's own `.m` file. Neither of these is probably what you wanted :) – deanWombourne Feb 18 '13 at 13:06
2

You don't - instance variables are defined inside @interface blocks.

If you want it to only be visible inside your .m file you can add this before your @implementation

@interface MyClass () {
    NSInteger myInteger;
    NSString *myString;
}
@end   
deanWombourne
  • 38,189
  • 13
  • 98
  • 110
2

You can do this in class extension in implementation file:

@interface SomeClass () {
    NSInteger _aVariable;
}

@end

Or better define a property:

@interface SomeClass ()

@property(nonatomic, assign) NSInteger aProperty;

@end
eofster
  • 2,027
  • 15
  • 18
-2

Define an instance variable like this:

NSMyClass *_nameOfObject;

You should to do it in your @interface not your @implementation

Max Woolf
  • 3,988
  • 1
  • 26
  • 39