I am reading: http://cocoacast.com/?q=node/103
I came across this method in the above page:
-(void)foo
{
self->iVar = 5; //legal because we are referencing a member variable
iVar = r; // illegal because we are referencing a readonly property
}
I then created a project in Xcode.
Test0.h
#import <Foundation/Foundation.h>
@interface Test0 : NSObject
{
@private int iVar;
}
@property (readonly, assign) int iVar;
- (void) foo;
@end
Test0.m
#import "Test0.h"
@implementation Test0
@synthesize iVar;
- (void) foo
{
iVar = 5;
}
@end
main.m
#import <Foundation/Foundation.h>
#import "Test0.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
Test0 *t1 = [[Test0 alloc] init];
[t1 foo];
NSLog(@"%d", t1.iVar);
}
return 0;
}
The result in Console is 5.
My questions:
- The web page mentioned above uses
self->iVar = 5
I have used iVar = 5
What difference does it make?
- The web page mentioned above says
iVar = r; // illegal because we are referencing a readonly property
Is iVar = 5 (which I have used) not same as iVar = r ?
How is it not illegal?
The compiler simply does not generate or verify the existence of the setter. It will generate the getter, and that property may be backed by an ivar. As well, the setter is not declared in the class interface.
None. They are identical. They are both direct assignment of the ivar. It’s similar to other languages, when adding a superfluous scope resolution (e.g.
this->).The difference is when you attempt to use the setter method (e.g.
self.prop = valor[self setProp:val];). In this case, the compiler will emit a warning and the runtime would throw an exception (unless you or a subclass defined the setter yourself).That’s wrong. Direct access to the ivar of a readonly property is fine if the ivar exists. You don’t see an error in this case because you’re accessing the ivar directly, rather than using the setter.
Other issues: