3

1, Please see the following code:

const UIView *view = [[UIView alloc] init];
view.tag = 2;

2,In my mind, the "const" meaning the variable can't be changed.
3, So I think I can't change the content of the object which "view" point to,but I can change the view.tag, I don't know why.

huixing
  • 321
  • 2
  • 11

1 Answers1

5

The correct usage would be UIView *const view = [[UIView alloc] init];

You can't change the content of view but you can always change the content of the object which view holds

Rest is explained in this question : What is the difference between const int*, const int * const, and int const *?

Why you are able to change the tag is because it is defined as

@property(nonatomic) NSInteger tag; // default is 0

It's not defined as constant(readonly) thus you are able to change its tag. If you want that content of the object should not change then in that case you have to change the definition of that class and make their ivar as const or readonly in case of properties.

Community
  • 1
  • 1
Inder Kumar Rathore
  • 39,458
  • 17
  • 135
  • 184