简体   繁体   中英

arrow operator in objective-c

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!

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.

Using the arrow notation isn't incorrect, and there is a difference between using the arrow and the dot notation.If you use the arrow operator you access to the instance variable, if you use the dot operator you access to the property.
It doesn't work like C structs where you use the arrow notation to access to a member of a struct pointed, and dot notation to access the struct members. So I would make a significative example:

@property (nonatomic, strong) NSString *text;

In .m file:

- (void)setText:(NSString *)string {
    NSLog(@"Accessing property");
    self->text = string; // let's suppose that text is not synthesized
}

If you use the dot notation , then you access to the property and it would print "Accessing property".But this hasn't to do with C structs syntax.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM