What does -> mean?

前端 未结 5 910
太阳男子
太阳男子 2021-01-12 13:03

I\'m a relative newbie to Objective-C (only studied Arron Hillegras\'s book) and am confused by the following snippit of code I\'ve found in one of Apple\'s code examples, i

相关标签:
5条回答
  • 2021-01-12 13:53

    You use -> when you want to access an ivar. Like C structures you will use a . or -> (in pointers to structs) in Objective-C objects you can use -> but is not necessary since you can access them directly.

    Hence:

    self->_numbers = [numbers copy];
    

    and

    _numbers = [numbers copy];
    

    are the same

    You want to use -> when you want to access that ivar explicitly.

    Be aware that in Objective-C you can use . but only when its a property. You can use -> regardless that.

    0 讨论(0)
  • 2021-01-12 13:59

    -> is a normal C operator for accessing the members of a pointer to a struct; the . operator is for accessing members of a struct. Thus:

    a->b
    

    is translated to

    (*a).b
    

    Since Objective-C objects are pointers to structs underneath it all, this works for accessing instance variables.

    0 讨论(0)
  • 2021-01-12 14:02

    It's an operator which roots from C Programming Language. And since Objective-C is compatible with C programming, you may see developers using traditional C-style programming.

    "->" is used to access a elements of a pointer. And since the "objects" in Objective-C are just pointers (denoted by *), e.g. NSNumber *number; , you can use this notation to access their elements.

    I never used this notation in Objective-C since the dot notation in Objective-C is accepted. If "self" has a synthesized property "number" then self.number should be the same as self->number (this is true ONLY in Objective-C.

    0 讨论(0)
  • 2021-01-12 14:04

    That indicates a reference to -in this case- an instance variable of an object. Self refers to the object itself, and by writing self->_numbers, you refer to the variable that is part of the class instead of a global variable named _numbers.

    Are you sure this is not mentioned in your book?

    0 讨论(0)
  • 2021-01-12 14:05

    It's usually called the 'arrow' operator. It allows you to access the instance variables of an object (or of a struct) using a reference or pointer to the instance. It's common syntax with C and C++.

    I'm struggling to find a nice write up, but you might find this one informative.

    As to the underscore - commonly they mean "private"; according to the Coding Guidelines for Cocoa - Naming Basics:

    Avoid the use of the underscore character as a prefix meaning private, especially in methods. Apple reserves the use of this convention. Use by third parties could result in name-space collisions; they might unwittingly override an existing private method with one of their own, with disastrous consequences.

    0 讨论(0)
提交回复
热议问题