3

I'm working through a code listing from a book and it has a pair of variables (specifically NSString *) declared and initialised in the @implementation rather than the @interface but outside of any method body. I've not seen this before and I'm wondering what the difference this makes in scope and so on.

I've had a quick look in The Objective C Programming Language but I can't see anything describing what effect this has.

Thanks

Andy

Andrew
  • 698
  • 5
  • 13

1 Answers1

8

Variables declared inside @implementation have global scope.

If you declare them as "static", they are only visible from the methods in the same source file.

So:

@implementation MyClass

NSString *myString; // global scope, and accessible by all code in your project

or

@implementation MyClass

static NSString *myString; // global scope, but only accessible by code 
                           // in this source file
Philippe Leybaert
  • 168,566
  • 31
  • 210
  • 223
  • I was searching for answer and realized that if its in bracelet, then it's actually ivar. See http://stackoverflow.com/questions/6785765/instance-variables-declared-in-objc-implementation-file – huggie May 22 '12 at 08:01
  • are you sure about that ?? I can't make it work. Perhaps you made wrong comments – atastrophic Oct 24 '12 at 05:11
  • What's the difference between defining them outside the `@implementation` block or inside it? – Nicolas Miari Jan 29 '15 at 03:08