3

Could someone please explain the Objective-C difference between myString and anotherString in the following snippet:

   // In .h file
   @interface MyClass : NSObject {
 NSString* myString;
   }
   @end

   // In .m file
   @interface MyClass ()
   NSString* anotherString;
   @end

   @implementation MyClass
   //...
   @end

Thanks!

2 Answers 2

4

In the .h file, you declare an instance variable. Each object will have a different one.

In the implementation file, you declare a global variable (the fact it's in a category does not change anything).
So the value of that variable will be the same, no matter the object's instance.

Note that this is often useful to simulate class variables, but with the static keyword, so the variable is only available from the implementation file.

2

In the .m file, the @interface MyClass() is actually a category, not a proper interface declaration. The difference is that categories can not add instance variables, only methods.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.