Objective-C learning 02-encapsulation, objective-c02 Encapsulation

Source: Internet
Author: User

Objective-C learning 02-encapsulation, objective-c02 Encapsulation

Three main features of object-oriented: encapsulation, inheritance, and Polymorphism

The purpose of encapsulation is to hide the data. Only the method (Interface) of this class can be used to access or set the data in it. It is not allowed to directly modify or access the data in it, the method is usually used to encapsulate a class, and eventually this class achieves the goal of High Cohesion and low coupling.

Coupling refers to the degree of closeness between modules of a software structure macro. The more precise the relationship between modules, the stronger the coupling, the coupling between modules depends on the complexity of interfaces between modules, the method of calling information and the information transmitted.

Cohesion refers to the degree of closeness between elements in a single module. A high cohesion is a software module that consists of highly correlated Code and is only responsible for one task.

 

1. Implementation of Setter and getter Methods

SetterFunction: provides a method to set the value of member variables for the outside world. In the end, it is a method that can be called externally and assigned values to member variables.

Naming rules:

1. It must be an object method, starting "-".

2. the return value type must be void.

3. The method name must be: set + instance variable name remove the underline "_", and the first letter is capitalized, for example: To _ age write setter method, setAge:

4. You must receive a parameter. Otherwise, how can you assign a value? The parameter type must be the same as the instance variable type. The parameter name is the instance variable name that removes the underscore "_", for example,-(void) setAge :( NSInteger) age;

SetterBenefits of the method: (1) preventing data from being exposed, ensuring data security; (2) filtering the Set Data

Setter method declaration:

// _ Age setter method-(void) setAge :( NSInteger) age; // _ gender setter method-(NSInteger) gender;

 

Setter method implementation:

// _ Age setter method-(void) setAge :( NSInteger) age {// if a value is assigned to age, if (age <0) is returned directly) {return;} // assign the value of the input content to the instance variable _ age = age;} // setter method of _ gender-(void) setGender :( NSString *) gender {_ gender = gender ;}

  Accessors getter Method

The getter method is used to return the instance variables in the object for the caller.

Naming rules:

1. It must be an object method, starting "-"

2. There must be a return value and the return value type must be consistent with the instance variable type

3. Method Name: Without get, you can directly use the instance variable name to remove the underline and write it as follows: _ age's getter method is: age

4. This method does not need to receive any parameters

Getter method declaration:

// _ Age's getter method-(NSInteger) age; // _ gender's getter method-(NSString *) gender;

Implementation of the getter method:

// _ Age's getter method-(NSInteger) age {// return the instance variable to return _ age;} // _ gender's getter method-(NSString *) gender {// return the instance variable return _ gender ;}

Note: In the actual development process, if the internal instance variables, such as the student ID, can only be read from the outside but cannot be modified, you only need to provide the get method instead of the set method. therefore, not all setter and getter methods are provided.

Complete example:

Create a Person class and implement the setter and getter methods for its instance variables.

Person. h

@ Interface Person: NSObject // modifier of the instance variable {@ public // visibility of the instance variable. As described below, NSString * _ name is not required for the moment; // name
@ Protected NSInteger _ age; // age
@ Private NSString * _ gender; // gender} // setter and getter methods of _ age-(void) setAge :( NSInteger) age;-(NSInteger) age;
// _ Gender's setter and getter methods-(void) setGender :( NSString *) gender;-(NSString *) gender; @ end

Person. m

@ Implementation Person // _ age setter getter method-(void) setAge :( NSInteger) age {if (age <0) {return ;}// content imported from outside, assign the value to the instance variable _ age = age;}-(NSInteger) age {// return the instance variable to return _ age ;}

// Setter getter method of _ gender-(void) setGender :( NSString *) gender {_ gender = gender;}-(NSString *) gender {// return the instance variable return _ gender;} @ end

 

2. Visibility of instance variables

1. There are three main types of visibility modifiers for instance variables:

Internal subclass of the visibility modifier class

@ Public: direct access and direct access

@ Protected: direct access and direct access

@ Private: direct access, not direct access

Default instance variable visibility modifier: @ protected

The range of the modifier of the visibility of the instance variable, from the row where it is located to the end of braces, or the end of the next visibility modifier;

@ Public

Although the variable modified by @ public can be directly accessed outside the class, it looks very convenient, but destroys the class encapsulation feature. Therefore, @ public is not recommended.

@ Public: the public, public, and modified instance variables can be accessed not only inside the class, but also outside the class;

 

Internal access: directly use the instance variable name, for example, _ age.

External access method: Object> instance variable name, for example, p> _ age

Person * p = [[Person alloc] init];

// Call the setter method of _ name p-> _ name = @ "Zhang San"; // for external access, use->
// Call the getter method of _ name
NSLog(@"%@", p->_name);

 

@ Protected

@ Protected: It is protected and cannot be directly accessed outside the class, but can be directly accessed inside the class and inside the subclass. This is the default visibility of instance variables in the system.

// Internal access: directly use the instance variable name

// External access: the value assignment must be accessed by setter. The value can be accessed by getter.

// Call the setter method of _ age: [p setAge:-10]; // call the getter method of _ age NSInteger age = [p age];

 

@ Private

@ Private: external access is not allowed. Internal access is allowed. In subclass access is not allowed, but access is allowed through methods.

Internal access: Use the instance variable name

Class External: access through the seter and accesser

// Call the setter method of _ gender [p setGender: @ "male"]; // call the NSLog (@ "% @", [p gender]) of _ gender.

 

Exercise: Define a Student type. The instance variables use three kinds of visibility and modify the three instance variables. Use the protect and private modified variables to write the setter and getter methods.

Student. h file declares:

@ Interface Student: NSObject {@ public NSString * _ name;
@ Protected NSInteger _ number;
@ Private CGFloat _ score;} // The setter getter method of _ number-(void) setNumber :( NSInteger) number;-(NSInteger) number; // _ score setter getter method-(void) setScore :( CGFloat) score;-(CGFloat) score; @ end

Implementation in Student. m file:

@ Implementation Student // _ number setter method-(void) setNumber :( NSInteger) number {_ number = number;} // _ number getter method-(NSInteger) number {return _ number;} // setter method of _ score-(void) setScore :( CGFloat) score {_ score = score ;} // _ score getter method-(CGFloat) score {return _ score ;}@ end

Return to main and call the setter and getter methods of various instance variables:

// Create a Student object stu: Student * stu = [[Student alloc] init];
// The instance variable _ number modified by @ protected // call the setter method of _ number [stu setNumber: 123456];
// Call the getter method NSLog of _ number (@ "% ld", [stu number]);

// @ Private modified _ score // call the setter method of _ score [stu setScore: 80.0];
// _ Score the getter method NSLog (@ "%. 2f", [stu score]);

Point syntax

If an instance variable implements the setter and getter methods for it, you can use the dot syntax. Therefore, the premise of using the dot syntax is that the setter and getter methods are used for this instance variable.

Point syntax is only a quick call to the setter and getter methods.

 

Stu. number = 12315; // It is equivalent to [stu setNumber: 12315]; NSLog (@ "% ld", stu. number); // It is equivalent to [stu number];

Point syntax usage Summary: if there is a value assignment operator (=) Next, this is equivalent to the setter method of this instance variable; there is no value assignment operator next, this is equivalent to calling the getter method of this instance variable

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.