14

The following code compiles:

@interface MyClass : ParentClass // missing {
// missing }
@property (nonatomic, copy) NSString *myString;
@end

I'm wondering if the curly braces in @interface declarations are actually necessary.

SundayMonday
  • 19,147
  • 29
  • 100
  • 154

2 Answers2

22

No, the { } section isn’t necessary; your code will compile fine without it. It’s the area where you declare instance variables, and if you’re not doing that, you’re free to leave it out. You don’t even actually need to declare ivars for your properties—the compiler’s smart enough to add them where they’re needed.

Noah Witherspoon
  • 57,021
  • 16
  • 130
  • 131
  • 2
    Depends on your compilers warning flags. You may also get an error saying the class struct has no members. – Macmade Sep 06 '11 at 22:14
  • @Mac Which warning flag? Neither clang 2.1 nor gcc 4.2.1 give warnings with `-Wall -Wextra` –  Sep 06 '11 at 22:24
  • @Bavarious I get warnings in Xcode 4.1 with default settings if I omit the braces. – Beltalowda Sep 06 '11 at 22:26
  • 2
    @Thu I don’t and I wonder why. In fact, Xcode 4.1’s template for a subclass of `NSObject` doesn’t even have braces in the class declaration. –  Sep 06 '11 at 22:29
  • Maybe it is a C++-ism, it certainly is not a default behavior in Objective-C to give any such compiler warning. – bbum Sep 06 '11 at 23:14
9

The compiler is clever enough to add your @property delarations to the class.

The only use for those brackets is when you want to make a variable private, protected or specifically public.

Example:

@interface Example: NSObject {
@public
    int publicVar;
@private
    int privateVar;
    int privateVar2;
@protected
    int protectedVar;
}
@end
Ahmad F
  • 30,560
  • 17
  • 97
  • 143
robinryf
  • 406
  • 3
  • 5