Introduction to object-oriented in objective-C

Source: Internet
Author: User

I have been dealing with object-oriented objects for some time. At that time, I learned OOP through C ++, and later I came into contact with PHP and Java. Every OOP language is more or less different in Object-Oriented aspects. Now I am learning the object-oriented part of OC, and I feel the characteristics of OC object-oriented. Write a blog post to summarize the object-oriented in OC. Just getting started with OC, the convenient initialization method and the convenience constructor in OC are a little lame, but within the acceptable range, the following things may have object-oriented features: abstract, encapsulation, inheritance, and so on are summarized less, mainly summarizes the characteristics of object-oriented in OC. When using the convenience constructor, it will be easier to understand if you have learned the design pattern before.

In the following code example, it may be difficult to understand the convenience initialization method and the convenience constructor. To put it simply, the constructor was born to simplify object initialization. In the previous blog, I also mentioned that programming is an indirect process, in fact, using the constructor is an indirect process. Indirectly is used everywhere in the program. For example, variables and functions you define are indirectly used. In real life, the indirect function is very great, even finding a girlfriend is indirect. If the indirect effect is good, you are likely to become a good friend with Obama, isn't it, isn't there a theory called "six connections? What are the indirect benefits of the program?

According to my personal understanding, the indirect principle will make the code written more flexible, and avoid unnecessary repeated code writing. A function is the best example. It encapsulates the unchanged and commonly used parts in the program, and then transmits the changed parts to the function parameter list, in this way, the code reuse function is well implemented, which is also the significance of the function in programming. In pseudo-literature, there is not a philosophical saying that every existence in the world has its own meaning. Darwin's theory of survival of the fittest is also very useful in the development of computer technology, and what can be preserved will certainly play his role.

The convenience constructor is an indirect use of convenience initialization functions to simplify object initialization (my personal understanding here ). Convenience initialization functions (Object methods) are used to assign initial values to instance constants. After Class instantiation, you can call convenience initialization functions. The constructor is a class method and returns an object. It does two things in the constructor: one is to allocate space to the object, the second is to call the convenience initialization function for data initialization. All the friends who have learned the design pattern should know the "template method pattern". I personally feel that the convenience constructor and the template method pattern have similar functions.

The following things are explained by code. Do you want to program code? Even if you want to talk about ideas, do you need code. Please criticize and correct them. If you want to reprint them, please indicate the source.

The main objective of object-oriented program development is to use code to simulate objects in reality, present certain behavior capabilities and features of objects in reality with code, and then use the code to simulate problems in reality.

Each object is described from two perspectives: feature and behavior.

Feature: it can be a component of an object or a physical or logical attribute used to represent the object's form, composition, and state.

Behavior ability: operations performed on an object or operations initiated by the object itself. Used to accept external operations or perform external operations.

Encapsulation: combines attributes and methods to reflect the characteristics of objects. encapsulation can hide internal implementations and stabilize external interfaces.

In oC, classes are composed of interfaces and implementation. Classes in OC are defined by two separate files. The interface is defined in the corresponding header file. This file is used to describe the attributes and methods of this class, but does not implement its behavior.

1. The interface definition in OC is as follows:

1234567891011121314151617181920 #import <Foundation/Foundation.h> @interface Student : NSObject{// Define attributes in braces    // Define the student's student ID, name, age, and hobbies;    @public    NSString *studentName;    int age;    NSString *hobby;} /* Define student-related methods. + modify the class methods. Class access can be directly used without instantiation.*-The number is modified as an object method and must be instantiated before it can be used. It is a method called by an object.*/ // Define a greeting Method- (void) sayHello;// Meal Behavior- (void) eat;@end

 

Code Description:

1. # The import <Foundation/Foundation. h> statement tells the compiler to view the header file of foundation. h In the foundation framework.

2. Use the # import command to import the corresponding file. # The role of import is equivalent to require_once in PHP. If the file has been imported before, it will not be imported, and # include will repeatedly import the file

3. Use the compiler command @ interface to define the class declaration. @ interface is followed by the class name. STUDENT: nsobject indicates that student inherits from the nsobject class.

4. in the interface, the method is declared and not implemented. The minus sign in front of the method indicates that this method is an object method. If it is a + sign, it indicates a class method, that is, the class can directly access this method.

[Email protected] And @ end appear in pairs. @ end indicates the end of the interface definition.

6. the above member variables have been defined as public, which is rare in development. Here, they are written for the convenience of exercises. Generally, the member variables are defined as private and then get is defined, set Method to operate on member variables

In this way, the encapsulation is started. Do not put your hands into the class directly, and operate the member variables of the class through the methods provided by the class.

 

 

[Email protected] Implementation

The extension of some files is. m. The code for implementation is as follows:

12345678910111213141516 #import "Student.h" @implementation Student// Greeting- (void) sayHello{    NSLog(@"Hello! I am % @. I am % d years old this year. I like % @! ", studentName, age, hobby);} // Implement eating behavior- (void) eat{    NSLog(@"% @ You have to eat too! ",studentName);} @end

Code Description:

1. In the implementation file, first import the corresponding class interface file # import "student. H", introduce the system file with <FILENAME>, and introduce the custom file with "FILENAME ";

2. Use the compiler command @ implementation to declare the implementation of class methods.

[Email protected] And @ end are also paired.

Code specification:

1. The first letter of the class name should be capitalized.

2. Use the camper name for method naming

 

3. Create and use objects

A class is defined and can be used only after it is instantiated. Of course, static classes can be used without instantiation. Objects are class entities and classes are abstract objects. Therefore, classes must be instantiated.

The instantiation code is as follows:

123456789101112131415161718192021222324 #import <Foundation/Foundation.h> // Introduce the defined class#import "Student.h" int main(int argc, const char * argv[]){     @autoreleasepool {        // Create an object, complete object declaration, memory allocation, and initialization        Student *student = [[Student alloc] init];                 // For convenience, assign values to the member variables directly, provided that the member variables are public        student->studentName = @"ludashi";        student->age = 20;        student->[email protected]"";                 // Call the member Method        [student sayHello];        [student eat];             }    return 0;}

? ? Code Description:

? ? ? ? 1. to instantiate a class in a class, first introduce the class interface definition file above # import "student. H ";

? ? ? ? 2. The class instantiation method in OC is student * student = [[STUDENT alloc] init]. It can be understood that the student class inherits the alloc method in the nsobject class. The alloc method is used

Instantiated object? Init is the default constructor.

? ? ? ? 3. In oC, the methods in object calling are implemented through [], and [Object Name and method name];

? ? Syntax for defining objects:

? ? ? ? Class Name? * Object name = [[class name alloc] init]; or

? ? ? ? Class Name? * Object name = [class name New];

? ? Assign values to the object's member variables and call the object as follows:

? ? ? ? Object Name-> member variable name = specific value;

? ? ? ? [Object Name and method name];

 

? I. Class and object Methods

? ? As mentioned above, the method starting with a minus sign is an object method, which needs to be instantiated and called through an object. Can object Methods call object methods and object variables? The method starting with the plus sign is a class method, which can be called directly through the class.

? ? The following are some rules for method calling:

? ? ? ? 1. Class methods can call class methods;

? ? ? ? 2. Class methods cannot call object methods;

? ? ? ? 3. The class method cannot use object variables. The class method can use self (self is equivalent to this in Java );? ? ?

? ? ? ? 4. Class methods can be called through classes, but objects cannot call class methods.

? ?

? ? 1. object initialization

? ? ? ? You can override the method init in the parent class to initialize the object, which is equivalent to the constructor in Java. The rewrite code is as follows:

1234567891011 // Override the init method and add the constructor for this class-(id) init{    if (self =[super init])    {        studentName = @"dashi";        age = 18;        hobby = @"hehe";    }    return self;}

? ? ? Code Description:

? ? ? ? ? 1. Because init is an inherited method, you do not need to declare it in the interface. Simply rewrite it in implementation;

? ? ? ? ? 2. The return type of init is ID, and ID is all the parent classes in OC. In object-oriented systems, the parent class can declare subclass variables.

? ? ? ? ? 3. [Super init] is used to initialize the member variables of the parent class. The returned value is a subclass object. If nil is returned, it indicates that the parent class is not successful in alloc, that is, it cannot be a subclass object in alloc.

 

? ? 2. Convenient initialization functions

? ? ? The custom convenient initialization function allows you to initialize the objects instantiated by the user. The convenient initialization function starts with init. You can customize convenient initialization functions in the class. Because the convenience initialization function is self-built. ? So you need to declare it in @ interface, so that the initialization function can be reloaded.

? ? ? Run the following code in @ implementation:

123456789101112131415161718 // Convenient initialization method 1- (id) initWithName:(NSString *)sName iAge:(int)anAge{    if (self = [super init]) {        studentName = [sName copy];        age = anAge;    }    return self;} // Convenient initialization method 2- (id) initWithName:(NSString *)sName{    if (self = [super init]) {        studentName = [sName copy];    }    return self;}

? ? Code Description:

? ? ? ? 1. The colon following the function name is followed by the parameter list. The parameter defined in OC is as follows: (parameter type) parameter name second parameter alias: (parameter type) parameter name

? ? ? ? 2. As long as the convenient initialization method meets the function overload conditions, it can be reloaded.

? ? The Code is as follows:

123 // Call the convenient Initialization MethodStudent *s1 = [[Student alloc] initWithName:@"dashi1" iAge:19];[s1 sayHello];

 

 

? 3. Constructor

? The preceding convenient initialization method is cumbersome in class instantiation. to simplify the instantiation operation, you can customize a class method. Class methods are used to instantiate classes and initialize parameters at the same time, and return the object

? ? The implementation code of the constructor is as follows:

123456 // Implement the constructor, instantiate the class, and call initwithname+ (id) studentWithName:(NSString *)name age:(int)sAge{    Student *student = [[Student alloc] initWithName:name iAge:sAge];    return student;}

?

? ? The constructor is used as follows:

12 // Call the constructor to initialize the objectStudent *s2 = [Student studentWithName:@"dashi2" age:20];

? ? ? ?

 

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.