Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 649
art-divin Avatar asked Dec 17 '12 18:12

art-divin


People also ask

What is-> in Objective-C?

-> 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.

What is dot operator called in C?

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 (.)


2 Answers

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?

like image 137
rmaddy Avatar answered Oct 10 '22 21:10

rmaddy


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.

like image 33
Guilherme Torres Castro Avatar answered Oct 10 '22 21:10

Guilherme Torres Castro