Objective-C basic syntax Class definition

Source: Internet
Author: User

Objective-CBasic syntaxClassDefinition is the content to be introduced in this article,Objective-CIs an object-oriented language, soClassIs the basis.Objective-CIt is the super of C, but its syntax is a little different from that of C, especially when accessing attributes and methods, it has a very special syntax. ReadObjective-CThe code knows that there will be a lot of brackets in it. This isObjective-CUnique.

InObjective-COneClassIs generally composed of two parts, one is the header file of the member and method declaration (. h), the other isClassMethod implementation file (. m. Of course, you can alsoClassThe statement is written in the. m file, but this is a private member.ClassIt cannot be used.ClassThe Declaration of Members is implemented through interfaces. If you know C #, you should know that C # also has interfaces. However, interfacegen and C # in Objective-C are totally different, the interface in Objective-C is used to defineClassThere are those attributes and methods.

There are two methods for a class, one is a class method and the other is an instance method. The class method is a bit like a static method. It belongs to a class rather than an instance of a class. The instance method is a class instance method. Class method is identified by "+" before definition, and "-" before instance method. For example:

 
 
  1. + (Id) allObjective-C; // This is a class Method
  2. (Void) doSomething; // This is an instance method

Use the brackets syntax during the call, for example:

 
 
  1. MyClass * class = [MyClass allObjective-C]; // call the class method to allocate memory
  2. [Class doSomething]; // call the instance method to implement certain functions

First, let's look at a complete example of class definition and implementation.
 
The. h file code is:

 
 
  1.  @interface Person:NSObject{  
  2. NSUInteger age;  
  3. NSString *name;  
  4. }  
  5. @property (nonatomic, assign)NSUInteger age;  
  6. @property (nonatomic,retain)NSString *name;  
  7.  
  8. + (Person *)person;  
  9. - (id)init;  
  10. - (void)setAge:(NSUInteger)theAge;  
  11. - (NSUInteger)age;  
  12.  
  13. - (void)vote;  
  14. @end  

. M file code:

 
 
  1.  #import "Person.h"  
  2. @interface Person ()  
  3. - (BOOL)canVote;  
  4. @end  
  5. @implementation Person  
  6. @synthesize name;  
  7. - (void)setAge:(NSUInteger)theAge{  
  8. age = theAge;  
  9. }  
  10. - (NSUInteger)age{  
  11. return age;  
  12. }  
  13. - (id)init{  
  14. if (self = [super init]){  
  15. age = 0;  
  16. name = @"";  
  17. }  
  18. return self;  
  19. }  
  20. - (BOOL)canVote{  
  21. return age >= 18;  
  22. }  
  23. - (void)vote{  
  24. //do something  
  25. }  
  26. @end  

The above is an example of a complete definition class. First, two fields, age and name, are defined in the header file. There are also two attributes, that is, age and name, there is also an initialization method and an instance method. Many of my friends may not understand when they first came into contact with Objective-C. Why is the field and attribute name the same? What's the difference? Yes, in Objective-C, the names of fields and attributes can be the same, but they are different. Generally, the header file declaration structure of a class is as follows:

 
 
  1. @ Interface class name {
  2. Field Declaration
  3. }
  4. Attribute Declaration
  5. Method Declaration
  6. @ End

Fields are private and cannot be used outside the class. Properties must be used for external use. What is an attribute? In fact, the attribute is the get and set methods for a field. In C #, we can easily use get and set accessors, but we need to define them in Objective-C. For example, the preceding example defines a setAge set method and a get method called age.
 
If we do not need to perform any operations in the get or set method of the attribute, it is a little troublesome to write so much code by ourselves. In Objective-C, you can quickly define attributes by using synthesize. After synthesize is followed by the attribute name, the compiler will automatically add an attribute for you instead of writing the get and set methods on your own. What if the attribute you want to define is read-only or has other features? When looking at the attributes defined in the header file, you only need to make some instructions.
 
For example, the name attribute in the above example is described in the previous section (nonatomic, retain. These instructions are related to memory management and access permissions. For example, if you add a retain, it is similar to name = [value retail]. that is to say, when assigning values to this attribute, the retain count will be added by one. Other instructions, such as readonly, are not listed one by one. In general, adding nonatomic and assign to attributes of the basic type such as NSInteger indicates nonatomic and assign, while adding nonatomic and retain to attributes of the reference type indicates nonatomic.

In addition to defining fields and attributes, we also need to define methods. Defining methods is simple. You only need to distinguish between class methods and instance methods. Note that the name of a method in Objective-C contains a colon. For example, the complete name of the set Method in the age attribute is setAge:, rather than setAge. In Objective-C, the method definition is quite strange. It allows a method name to be mixed with the parameter name. For example, in C #, I define a method:

 
 
  1. Void SetPosition (int x, int y)
  2. {}
  3. In Objective-C, it will become like this:
  4. -(Void) setPositionX :( NSInteger) x Y :( NSInteger) y {
  5. }

At this time, the complete method name is "setPositionX: Y:". The method name and parameter name are mixed together. Separate parameters with spaces. The parameter names are followed by colons, extend the parameter type with parentheses (do not forget to add * to indicate the pointer for the reference type), and then follow the name of the parameter.

Note that the name of the form parameter must not be the same as the name of the attribute or field. Otherwise, a compilation warning is displayed, indicating that the local variable overwrites the global variable. When I first came into contact with Objective-C, I may not get used to it, but later I felt quite comfortable.

The code in the. m file is the specific implementation of the method, which is invisible to the outside world. The content of a typical m file is:

# Import "header file. h" // use the system's built-in <> instead of double quotation marks.

 
 
  1. @ Implementation class name {
  2. // IMPLEMENTATION OF THE METHOD
  3. }

The implementation of the method does not need to be explained too much. In the above example, some additional things are added.

 
 
  1. @interface Person ()   
  2.      - (BOOL)canVote;   
  3. @end  

What does this mean? In Objective-C, this is called "extension ". The so-called extension is actually to extend the methods or attributes of a class. Methods or attributes not in the original class can be easily extended. However, you must note that only attributes and methods can be extended in expansion. If you want to add fields, compilation errors will occur. A typical extension method is similar to an interface, for example:

 
 
  1. @ Interfae Class Name (you can add descriptive text or leave it blank)
  2. // Defines attributes and methods, but cannot add fields. Therefore, the braces cannot contain
  3. @ End

Extensions can be public or private, depending on where you define them. Here I am defined in the m file, which is naturally private. If it is defined in the header file, it is public.

The interface can be defined multiple times separately, and the same implementation class can also be written multiple times. The advantage of writing multiple times is that the conditioning is clear and the code readability is improved. For example, you can write some function-related code in

 
 
  1. @ Implementation @ end

Then some other code is written somewhere else.

InObjective-CThe most basic syntax for defining a class in.

Summary:Objective-CBasic syntaxClassThe definition has been introduced. I hope this article will help you!

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.