I have a question, here's the code:
@interface MyFoo : NSObject {
NSString *nameStr;
}
@end
@implementation MyFoo
- (id)init {
self = [super init];
if (self) {
self->nameStr = [@"some value of the string that is set right into the private ivar" copy];
}
return self;
}
@end
The question is: ignoring all the C++ rules, ignoring memory dump vulnerability, why exactly I shouldn't use such arrow operator syntax? Is there somewhere in Apple documentation a rule which says that it's incorrect because in future class may be represented differently than a pointer to a struct in runtime etc. ?
Thanks in advance!
-> is not specific to Objective-C. It's a C operator. Now that's cleared, it's the member access operator, equivalent to a pointer dereference and then using the dot operator on the result.
It is called as “Indirect member selection” operator and it has precedence just lower to dot (.) operator. It is used to access the members indirectly with the help of pointers. Can dot (.)
The use of self->someIvar
is identical to someIvar
. It's not wrong but it's not needed either.
The only time I use the arrow notation is in an implementation of copyWithZone:
so I can copy each of the ivars that don't have properties.
SomeClass *someCopy = ...
someCopy->ivar1 = ivar1; // = self->ivar1
someCopy->ivar2 = ivar2; // = self->ivar2
Where are you seeing anything that says you shouldn't use such arrow operator syntax?
Using arrow notation on just the ivar name to access a property will not guarantee they will be retain, assign or etc ... Because you are directing accessing an ivar and not calling and setter ou getter method used in properties.
Example:
@interface MyFoo : NSObject {
}
@property(nonatomic,retain) NSString *nameStr;
@end
@implementation MyFoo
- (id)initWithString:(NSString *)name {
self = [super init];
if (self) {
self->nameStr = name; // will not be retained
}
return self;
}
@end
For ivar variables as already be answer there`s nothing wrong.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With