-3

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

2
  • 1
    check out stackoverflow.com/questions/6785765/… Commented Feb 15, 2013 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. Commented Feb 15, 2013 at 11:56

4 Answers 4

4

Put them in curly braces, like so:

@implementation {
    id anIvar;
}
Sign up to request clarification or add additional context in comments.

6 Comments

What exactly happens when variable declaration is not placed in curly braces? What kind of variable do I get?
@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.
Yes it seems indeed something like that. Thanks!
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.
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.
|
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   

3 Comments

well, I almost always put them in @implementation {} like Carl Veazey's answer in these days.
You can put them in the implementation block in curly braces, see the possible duplicate.
True but then if you wanted to add 'private' properties you run into problems . . . personally, I prefer the separation :)
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

1 Comment

Didn't know you could do that in the class extension, neat.
-2

Define an instance variable like this:

NSMyClass *_nameOfObject;

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

1 Comment

You can put them in your implementation block, see the possible duplicate.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.