当前位置: 动力学知识库 > 问答 > 编程问答 >

ios - The const modifier in Objective-c

问题描述:

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.

网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: