Voloda2
Voloda2

Reputation: 12597

I want to set ivar using -> operator

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;
 }

Upvotes: 0

Views: 279

Answers (2)

Nicolas Miari
Nicolas Miari

Reputation: 16246

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)

Upvotes: 2

trojanfoe
trojanfoe

Reputation: 122381

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;
}

Upvotes: 1

Related Questions