Objective-c programming Language (3) defining the implementation of class---classes

Source: Internet
Author: User
Tags bool data structures instance method
Reprint please indicate source: http://blog.csdn.net/zhangxingping
implementation of the classThe definition of a class is structurally similar to the declaration of a class. The definition of the class begins with the @implementation command word and ends with the @end command word:
    @implementation Class Name: Super Class name
    {
        instance variable declaration
    }
    method implementation
    @end
One point to note is that the corresponding interface file must be introduced into the implementation file of the class. For example, you must introduce Rectangle.h in the RECTANGLE.M file. Also, because there is no need to repeat the contents of the introduced file in the implementation of the class, these classes can be omitted:
The name of its superclass
Declaration of an instance variable in a class
In this way, the introduction of its corresponding interface file simplifies the implementation of the file, and in the implementation file we can focus more on the implementation of the various methods in the class:
    #import    "class name. h"
    
    @implementation
    the implementation of the class name method
    @end
The implementation of the method is the same as in the C language, surrounded by a pair of curly braces. Before the curly braces, the content is the same as the declaration of the method in the interface file, except for the semicolon at the very back of the declaration. For example:
    + (ID) alloc
    {
        ...
    }
    
    -(BOOL) isfilled
    {
        ...
    }
    
    -(void) setfilled: (BOOL) flag
    {
        ...
    }
The parameters are treated in the same way as the normal method using the variable parameter:
    #import <stdarg.h> ...
    -Getgroup:group,...
    {
        va_list_ap;
        Va_start (ap,group);
        ...
    }

referencing an instance variable by default, an instance method can access all of the instance variables in the class. Use the name directly when you are using it. Although the compiler creates a peer C struct to store these instance variables, the struct is invisible to the outside. We do not need to manipulate the data in the struct operator (. or). For example: The filled variable of the receiver is used in the definition of the following method:

    -(void) setfilled: (BOOL) flag
    {
        filled = flag;
    }
Although the filled variable and the recipient of the message are not passed in as parameters to the method, they are still accessible in the method implementation of the class. This syntax greatly simplifies the writing of objective-c code.
When an instance variable of an object is not the recipient of a message, the type of the instance variable must be displayed to the compiler in a statically typed manner. When referencing instance variables of these static types, we want to use the pointer operator of the struct body.
For example, a static type of twin is declared in the sibling class as one of the instance variables:
    @interface sibling:nsobject
    {
        Sibling *twin;
        int gender;
        struct features *appearance;
    }
As long as the scope of the instance variable of the static type object contains the class (as in the preceding program segment, because the type of the twin instance variable is the same as the Class), the method of the sibling class can set its value directly:
    -Makeidenticaltwin
    {
        if (!twin)
        {
            twin = [[Sibling alloc] init];
            Twin->gender = gender;
            Twin->appearance =appearance;
        }
    }

the scope of an instance variable Although the instance variable is declared in the interface file, the instance variable expresses more of the way the class is implemented rather than the way it is used by the class. The interface that an object provides to the outside world is a method, not a data within itself.
Typically, each instance variable has a corresponding method. As follows:

  -(BOOL) isfilled
  {
      return filled;
  }
But it is not necessary to do so. Some methods may return information that is not stored in instance variables, and some instance variables store information that you do not want to be perceived by the outside world.
In the process of continuous refinement of the class, although its methods may remain the same, the instance variables have a greater likelihood of change. However, as long as the message of the interaction between instances of the class does not change, this change in the internal instance variable does not affect the interface that the class provides to the outside world.
To force an object to hide its data from the outside world, the compiler restricts instance variables, that is, limits the visible scope of these instance variables in the program. But for the sake of flexibility, programmers are allowed to display one of the following four options for this limitation:

┌───────────┬───────────────────────────────────────────────────────────────────────────────┐

│ command word │ meaning │

├───────────┼───────────────────────────────────────────────────────────────────────────────┤

│ @private │ Instance variables can only be accessed in the class that declares him │

├───────────┼───────────────────────────────────────────────────────────────────────────────┤

│ @protected │ Instance variables can only be accessed in a derived class that declares his class and its class │

├───────────┼───────────────────────────────────────────────────────────────────────────────┤

│ @public │ Instance variables can be accessed everywhere │

├───────────┼───────────────────────────────────────────────────────────────────────────────┤

││ in modern runtime systems, instance variables of @package type are visible to the executable "imagery" that implements its class │

││, and @private for the rest of the code. │

The scope of the @package variable in ││objective-c is similar to the scope of the Private_extern variable in C. Any │

│ @package │ Access to this class's implementation "imagery" will result in link errors. │

││ This scope limit is useful for framework framework classes. At this time the @private limit is too strict │

││ and @protected or @public restrictions are too lenient. │

└───────────┴───────────────────────────────────────────────────────────────────────────────┘Translator Note: The word "image" is used in the description of the meaning of @package, and the word "image" in the original text. Given that no suitable Chinese word has been found to describe it, here's what the translator understands: the image here usually refers to the framework frame, A dynamic library or executable file, which has no relation to the word "image". It refers to the "image" that the linker can load when it is linked. A common run-time error is this: "Dyld image not Found", which is the meaning of the image here. More information can be consulted: http://stackoverflow.com/questions/772600/what-does-the-package-directive-do-in-objective-c, but in English yo.


┌────────────────────┐─┐─┐─┐
│││││
│ class │├───> for declaring instance variables @private ││
│││││
└─────────┬──────────┘─┘││
│├───> @protected │
┌─────────┴───────────┐││
││││
│ class ││├──> for inheriting instance variables @public
││││
└─────────────────────┘─┘│


┌─────────────────────┐│
│││
│ Other unrelated code ││
│││
└─────────────────────┘─┘

Figure 2-1 Scope of the instance variable (not including the @package type)
The scope command Word works on the variable following it until the next command word or the end of the list is encountered. In the following example program, the age and evaluation instance variables are private, name,job and wage are protected (protected), and bosses are public:

    @interface worker:nsobject
    {
        char * name;
    @private:
        int age;
        char * evaluation;
    @protected:
        ID job;
        float wage;
    @public:
        ID boss;
    }
By default, the variables that do not display the scope command Word are @proetected.
All variables declared in a class, regardless of their preceding command word, are visible within the scope of the class. For example, a class that defines a job instance variable, such as the worker class above, can use the job variable in its methods:
    -Promote:newposition
    {
        id old = jog;
        Job = newposition;
        return old;
    }
Obviously, if a class cannot access his instance variables, then these instance variables will become useless.
In general, a class can also access instance variables that it inherits from. Classes can be accessed within the scope of their data structures, which makes sense, especially when we think of a class as a more granular description of its base class. Previous Promoteto: Method can be defined in any derived class that inherits the job instance variable from the worker class.
However, it is also necessary to restrict this inheritance to avoid direct access to these instance variables:
Once an inherited instance variable is accessed in a derived class, the class that declares the instance variable is bound to that part of the implementation. In later versions, if the effects on derived classes are not carefully considered, you cannot delete these variables or modify the role of these instance variables.
Furthermore, if the values of inherited instance variables are accessed or modified in a derived class, it is possible to introduce bugs into the classes that declare these instance variables, especially when these instance variables are only closely related to the inner class that declares them.
In order to limit the scope of the instance variable to only the class that declares him, we must use the @private command Word. Instance variables that are qualified by the @private command can only be accessed by the derived class through the public interface provided by the class in which it resides. If the class in which it is located does not provide a corresponding public interface, these instance variables are not visible to the derived class.
Another extreme is the @public command word. He makes the instance variable a common variable, even outside the scope of declaring his class, or beyond the scope of its derived class. In general, other objects must get the information stored in an instance variable by sending a message. However, the public instance variable can be accessed directly from anywhere in the program, just like a field in a C-language struct.
    Worker *ceo = [[Worker alloc] init];
    Ceo->boss = nil;
At this point the object must be of a static type.
@public command word destroys the ability of an object to hide its data. This approach goes against the object-oriented programming idea that data is encapsulated in objects to avoid errors caused by carelessness. Therefore, common instance variables should be avoided in non-special cases.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.