Objective-c Learning article 02-Encapsulation

Source: Internet
Author: User

Three Object-Oriented Features: Encapsulation, Inheritance, and Polymorphism

The purpose of encapsulation is to hide the data.The outside world can only access or set the data inside through the methods (interfaces) of this class.It cannot directly modify or access the data inside.The methods are usually used to achieve the purpose of encapsulating a class. In the end, this class achieves the purpose of high cohesion and low coupling.

Coupling is the degree to which each module of a software structure macro is closely related to each other.The more precise the connection between modules, the stronger the coupling.The level of coupling between modules depends on the complexity of the interface between the modules. , The method of calling information and the information passed.

Cohesion refers to the closeness of the combination of various elements in a single module.The so-called high cohesion is that a software module is composed of highly relevant code and is only responsible for one task.

 

An implementation of Setter and getter methods

The role of the setter Setter: Provide a method for setting the value of member variables for the outside world, in the final analysis, it is a method that can be called from the outside world and assign values to member variables.

  Naming conventions:

1. Must be an object method, beginning with a minus sign "-"

2. The return value type must be void

3. The method name must be: set + instance variable name without the underscore "_", and the first letter is capitalized, for example: setter method for _age, setAge:

4. Must receive a parameter, otherwise how to assign? The parameter type must be the same as the type of the instance variable, the parameter name is the instance variable name without the underscore "_" For example:-(void) setAge: (NSInteger) age;

的 The benefits of the Setter method (1) do not let the data be exposed and ensure the security of the data; (2) filter the set data

Setter method declaration:

// setter method of _age

-(void) setAge: (NSInteger) age;

// _gender's setter method

   -(NSInteger) gender;
 

实现 Setter implementation:

// setter method of _age
-(void) setAge: (NSInteger) age {
    // If it is detected that the age is assigned a value, then return directly
    if (age <0) {
        return;
    }
    // Assign the content passed in to the instance variable
    _age = age;

}

// _gender's setter method
-(void) setGender: (NSString *) gender {
    _gender = gender;
}
Accessor getter method

The role of the getter method: return the instance variable inside the object for the caller

  Naming conventions:

1. Must be an object method, starting with "-"

2. There must be a return value and the return value type must be the same as the instance variable

3. Method name: Without get, write the instance variable name without the underscore. For example, the getter method of _age is: age

4. This method does not need to receive any parameters

Getter method declaration:

// _age getter method
-(NSInteger) age;

// _gender's getter method
-(NSString *) gender;
实现 getter method implementation:

// _age getter method
-(NSInteger) age {
    // Just return the instance variable
    return _age;
}

// _gender's getter method
-(NSString *) gender {
    // return instance variable
    return _gender;
}
Note: In the actual development process, if the internal instance variables, such as the student number, are only allowed to be read and not modified, then only the get method is provided instead of the set method. Therefore, it is not necessarily a setter and getter. Methods are provided.

Full example:

Create a Person class and implement setter and getter methods on its instance variables

Person.h

@interface Person: NSObject
// instance variable
{
    @public // Modifier of instance variable visibility.
    NSString * _name; // Name
   
Protect @protected
    NSInteger _age; // age

    @private
    NSString * _gender; // Gender
}

// _age's setter and getter methods
-(void) setAge: (NSInteger) age;
-(NSInteger) age;

// _gender's setter and getter methods
-(void) setGender: (NSString *) gender;
-(NSString *) gender;

@end
Person.m

@implementation Person
// _age's setter getter method
-(void) setAge: (NSInteger) age {
    if (age <0) {
        return;
    }
    // Assign the content passed in to the instance variable
    _age = age;
}

-(NSInteger) age {
    // Just return the instance variable
    return _age;
}


// _gender's setter getter method

-(void) setGender: (NSString *) gender {
    _gender = gender;

}

-(NSString *) gender {
    // return instance variable
    return _gender;
}
@end
 

Visibility of instance variables

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

  Visibility modifiers are internal subclasses of the class

 Public @public can be accessed directly can be accessed directly

  Protect @ protected can be accessed directly can be accessed directly

 Pri @private can be accessed directly, not directly

  System default instance variable visibility modifier: @protected

The scope of the visibility modifier of the instance variable, from the line in which it is located, to the end of the braces, or the end of the next visibility modifier;

@public

  Although @public modified variables can be accessed directly outside the class, it seems convenient, but it destroys the encapsulation characteristics of the class, so it is not recommended to use @public

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

 

  Internal access method: directly use the instance variable name Example: _age

  External access method: Object-> Instance variable name Example: p-> _ age

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

// call the setter method of _name
p-> _ name = @ "张三"; // external access, use->
// call the getter method of _name
NSLog (@ "% @", p-> _ name);
 

@protected

       @protected is protected and does not allow direct access outside the class, but can be accessed directly inside the class and inside the subclass, which is the system's default instance variable visibility.

// Internal access: directly use the instance variable name

// External access: Assignment needs to be accessed through the setter setter, and value access is accessed through the accessor getter

    // Call the setter method of _age:
    [p setAge: -10];

    // Call the getter method of _age
    NSInteger age = [p age];
 

@private

      @private Private, not directly accessible externally, directly accessible internally, not directly accessible in subclasses, but accessible via methods

      Internal access: by using instance variable names

      Outside the class: access via setters and accessors

    // call the setter method of _gender
    [p setGender: @ "男"];

    // call _gender's getter method
    NSLog (@ "% @", [p gender]);
 

Exercise: Define a Student type, use three types of visibility for instance variables, and modify its three instance variables. Use protect, private decorated variables to write setter and getter methods

The Student.h file states:

@interface Student: NSObject
{
    @public
    NSString * _name;

    @protected
    NSInteger _number;

    @private
    CGFloat _score;
}

// _number setter getter method
-(void) setNumber: (NSInteger) number;
-(NSInteger) number;


// _score setter getter method
-(void) setScore: (CGFloat) score;
-(CGFloat) score;

@end
Implemented in Student.m file:

@implementation Student

 // _number setter method
-(void) setNumber: (NSInteger) number {
    _number = number;
}

// _number getter method
-(NSInteger) number {
    return _number;
}

// _score setter method
-(void) setScore: (CGFloat) score {
    _score = score;
}

// _ score getter method
-(CGFloat) score {
    return _score;
}
@end
Back to main, call the setter and getter methods of each instance variable:

     

 // Create a Student object stu:
    Student * stu = [[Student alloc] init];

// instance variable modified by @protected _number
    // call the setter method of _number
[Stu setNumber: 123456];

    // call the getter method of _number
    NSLog (@ "% ld", [stu number]);


// _score modified by @private
    // call the setter method of _score
    [stu setScore: 80.0];

    // _score getter method
    NSLog (@ "%. 2f", [stu score]);
Dot syntax

      If an instance variable implements setter and getter methods on it, dot syntax can be used. Therefore, the premise of using dot syntax is to use setter and getter methods on the instance variable.

      Dot syntax is just a quick call to setter and getter methods

 

    stu.number = 12315; // is equivalent to [stu setNumber: 12315];

    NSLog (@ "% ld", stu.number); // equivalent to [stu number];
      Summary of dot syntax usage: If there is an assignment operator (=) at the back, it is equivalent to the setter method of this instance variable at this time; if there is no assignment operator at the back, this is equivalent to calling the getter method of this instance variable

Objective-C Learning Article 02—Encapsulation

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.