1

I want to declare variables in objective-c that are available throughout an instantiated instance of a class, but not available outside the scope of that class. I have been doing my code as below:

@interface myClass
{
 NSString* classVariable;
}
@end

@implementation myClass

-(void)method
{
 NSLog(@"%@",classVariable);
}

@end

This seemingly works in the code, but I am new to Objective-c (coming from Java and C#). Is this best practice? Are there any pitfalls?

Thanks in advance!

steventnorris
  • 5,656
  • 23
  • 93
  • 174
  • Just use properties instead and you're good! – CrimsonChris Aug 28 '14 at 17:23
  • @CrimsonChris Thanks. Are there any pitfalls to the method I'm currently using? I know properties are visible outside of the class, which I'd like to avoid. – steventnorris Aug 28 '14 at 18:18
  • They are only visible outside of the class if you put them in the header file. Put them in the _class category_ right above your class's implementation. – CrimsonChris Aug 28 '14 at 18:24
  • @CrimsonChris Ah, I see. So that's best practice. Out of curiosity, are there any pitfalls to what I'm doing now? – steventnorris Aug 28 '14 at 18:31
  • Properties automatically provide getter and setter methods that you can override. They also allow you to declare them as weak or strong for ARC. The most important reason to use them is so that you can be consistent with the rest of the community. – CrimsonChris Aug 28 '14 at 18:35
  • @CrimsonChris That's a *class extension*, not a category; those are two very different things. – jlehr Aug 28 '14 at 18:47
  • possible duplicate of [Difference between Category and Class Extension?](http://stackoverflow.com/questions/3499704/difference-between-category-and-class-extension) – CrimsonChris Aug 28 '14 at 18:58

1 Answers1

1

Many will tell you to use properties, but sometimes you just want an instance variable which is private (which just means harder to access in Objective-C which has no real access control). If this is your case, the Objective-C language gained the ability to declare instance variables in the implementation not too long ago just to meet your need. Change your code to:

@interface myClass
@end

@implementation myClass
{
   NSString* classVariable;
}

-(void)method
{
   NSLog(@"%@",classVariable);
}

@end

Instance variables declared in this way are as hidden as Objective-C allows.

CRD
  • 52,522
  • 5
  • 70
  • 86