0

I want to set ivar using -> operator. I got an error: Interface type cannot be statically allocated. I don't want dot operator.

 @interface Dream : NSObject

 @property (nonatomic, assign) BOOL isBeer;

 @end

Class ViewController

 - (void)viewDidLoad
{
 [super viewDidLoad];

  Dream dr1;
  (&dr1)->isBear = YES;
 }
Voloda2
  • 12,359
  • 18
  • 80
  • 130
  • I haven't used -> operator for a long time. I forgot some aspects. Now I'm trying to refresh my knowledge about this operator. – Voloda2 Jun 28 '12 at 15:43

2 Answers2

2

You are missing the ' * ' in the declaration:

Dream *dr1;

That is the cause of the compiler error.

In Objective-C, objects are referenced by pointers only, much like C++ instances created with new().

Also note for Objective-C objects, the distinction between '->'(arrow) and '.'(dot) is not the same as for C++ objects/C structs. In C/C++, you use the dot to access members of a stack variable, e.g.:

// Stack
MyClass myObject;
myObject.memeber = 1; 

MyStruct info;
info.member = 1;


// Heap
MyClass* pMyObject = new MyClass();
myObject->memeber = 1; 

MyStruct* pInfo = (MyStruct*) malloc(sizeof(MyStruct));
pInfo->member = 1;

whereas in Objective-C, all objects are heap (referred to by pointers only), so you can only access members with the arrow.

The dot, on the other hand, has the different meaning of calling the getter/setter for a property, that might be backed by an ivar or not. (depends on internals)

Nicolas Miari
  • 16,006
  • 8
  • 81
  • 189
1

You need to make the instance variable public:

@interface Dream : NSObject
{
@public
    BOOL isBeer;
}
@end

Class ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    Dream *dr1 = [[Dream alloc] init];
    dr1->isBeer = YES;
}
trojanfoe
  • 120,358
  • 21
  • 212
  • 242
  • 3
    The produced error actually lies in the `Dream dr1;` line, you can't make an objective-C object on the stack. – joerick Jun 28 '12 at 15:34
  • @joerick Huh? I think you wanted to comment on the question? – trojanfoe Jun 28 '12 at 15:35
  • 3
    You corrected two errors in your answer- one was the visibility of the ivar, but you also corrected the object declaration... the object declaration was causing the _Interface type cannot be statically allocated_ error, I was just pointing this out. – joerick Jun 28 '12 at 16:12