How can I make instance variable inside class @implementation in Objective-c?
2
-
1check out stackoverflow.com/questions/6785765/…Sudha Tiwari– Sudha Tiwari2013-02-15 11:53:58 +00:00Commented 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.Dusan– Dusan2013-02-15 11:56:19 +00:00Commented Feb 15, 2013 at 11:56
Add a comment
|
4 Answers
Put them in curly braces, like so:
@implementation {
id anIvar;
}
6 Comments
Dusan
What exactly happens when variable declaration is not placed in curly braces? What kind of variable do I get?
Carl Veazey
@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.
Dusan
Yes it seems indeed something like that. Thanks!
Hermann Klecker
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.Carl Veazey
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.
|
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
Bryan Chen
well, I almost always put them in
@implementation {} like Carl Veazey's answer in these days.Carl Veazey
You can put them in the implementation block in curly braces, see the possible duplicate.
deanWombourne
True but then if you wanted to add 'private' properties you run into problems . . . personally, I prefer the separation :)
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
Carl Veazey
Didn't know you could do that in the class extension, neat.
Define an instance variable like this:
NSMyClass *_nameOfObject;
You should to do it in your @interface not your @implementation
1 Comment
Carl Veazey
You can put them in your implementation block, see the possible duplicate.