arrow operator in objective-c

左心房为你撑大大i 提交于 2019-12-17 20:04:20

问题


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!


回答1:


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?




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/13919793/arrow-operator-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!