About private instance variables in Objective-C

2019-04-15 08:32发布

问题:

In xCode 3, I defined private instance variables in a class. When I directly access the private variables in the client codes, why does the compiler just show me a warning, not an error? The code can still run. The warning says this maybe a hard error in the future. What does the "hard error" mean? Thanks.

回答1:

Hard Error means that sometime in the future the compiler will behave the way you expect it to behave (i.e., it won't compile the source file when you directly access an instance variable outside the defined visibility scope).

Right now the compiler simply isn't enforcing Objective-C the visibility restrictions. The warning is there, however, to remind you that you're doing something that you shouldn't be doing and bring you attention to that in case you did it by accident.

If I had to hazard a guess as to why the visibility isn't enforced, I'd say that with all the toll-free bridging stuff between the Foundation library and the CoreFoundation library, there is probably a decent amount of library code that accesses instance variables that, strictly speaking, should not be visible.

In general, it's a bad idea to directly access instance variable anyway. As long as you can use Obj-C 2.0, it's probably better to use something like properties if you're designing a pure-data model object.



回答2:

Well, the hard error would mean that it will become an error in the future rather than a warning. As for why it's a warning now, I'm not sure. I would imagine it's for the same reason that when you try to call a method that doesn't exist on a class, that is also only a warning.