tags:

views:

96

answers:

2

I'm a little bit confused now after I've seen a code snippet for iPhone SDK which makes use of -> rather than dot notation. It looks a lot like PHP but it does work on the iPhone. Can someone explain what's up with ->, is that some deep C-secret I should know about?

Example:

- (void)setFileURLs: (NSArray*)elements {
    if (self->fileURLs != elements)

fileURLs is an instance variable or property, like so:

@property(nonatomic, retain) NSArray *fileURLs;

and there's an @synthesize for fileURLs. Now what I think this is: Because this is the setter method for fileURLs, it would be bad to use dot notation to access the instance variable. In fact, when I do it, the application crashes. That is because it calls itself over and over again, since the dot notation accesses the accessor method and not the ivar directly. But -> will access the ivar directly.

If that's right, the question changes a little bit: Why then write "self->fileURLs" and not just "fileURLs"? What's the point of adding that self-> overhead in front of it? Does it make sense? Why?

+5  A: 

a->b is just another way for writing (*a).b. This is a way for accessing fields of a structure or instance variables of an object that are referenced by a pointer.

mouviciel
A: 

See section "Other operators" at:

http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B

Since self is a pointer, you have to use -> and not . to access its members. Prepending the self reference to fileURLs is probably just a coding style used by the author (equivalent to writing this.member).

Ian Kemp
Except that because there is a property defined, self.fileURLs would work just fine... seems like someone used to C++ using Objective-C.
Kendall Helmstetter Gelner
self->fileURLs is accessing the member variable (as mouviciel pointed above). self.fileURLs is running the accessor method for the fileURLs property that might return something completely different.
Nir Levy