OBJECTIVE-C 2.0 Basic Point induction

Source: Internet
Author: User


The basic conditions of reading in this article are:
    • Basic knowledge of C + +, understanding object-oriented features
    • Read "OBJECTIVE-C 2.0 Program Design (second edition)", "objective-c Program design 6th Edition" or related Foundation OC Books
Reference resources:


1. "Effective objective-c2.0"
2. "OBJECTIVE-C 2.0 Program Design (second edition)"/"Objective-c Programming 6th Edition"
3. http://www.cnblogs.com/pengyingh/articles/2354709.html
4. HTTP://WWW.CSDN.NET/ARTICLE/2015-07-06/2825133-OBJECTIVE-C-RUNTIME/1
5. http://www.cocoachina.com/ios/20141218/10679.html
6. http://www.cnblogs.com/chijianqiang/archive/2012/06/22/objc-category-protocol.html



Summary mode of Knowledge Essentials: Ask questions and give detailed explanations (Q&A)
PS: Will extend the way to introduce some knowledge points


List of issues:


Q1. Objective-c features and differences from C + +?
62ω What are the characteristics of attributes, the difference between instance variables, and the use of precautions?
Q3. Class inheritance, the concept and use of protocols and classifications, and the issues needing attention?


Content details: Q1. Objective-c features and differences from C + +?


A: Objective-c (OC) is a superset of C, which is based on the dynamic language of object-oriented and message-forwarding mechanism (inheriting the classical idea of object-oriented Smalltalk language) in C language. In addition to the compiler, a runtime system is needed to dynamically create classes and objects for message sending and forwarding , and the runtime system is a C language to write the dynamic link library (libobjc.a.dylib), the library provides the OC language required by the various dynamic characteristics of support.



OC uses message passing (Messaging) to pass a message to an object rather than a method call. such as: [Receiver message], the compiler does not immediately execute the object's message method, but sends a message to the receiver object, the compiler converts it to Obj_msgsend ( Runtime and object Model detail implementation See Foundation Framework Essentials Induction ) and their associated function calls, which are implemented according to Obj_msgsend when the program is running.



In a nutshell, the OC program does not specifically determine the method implementation at compile time, but uses the dynamic binding of the runtime system to implement the method, and implements the category of the search method through Obj_msgsend, and then calls the method implementation. The object-oriented polymorphism is implemented by the runtime system (different classes have the same method name).



PS: C + + is also an extension of the object-oriented nature of C, which allows simple analysis of the differences between C + + and OC from an object-oriented three attributes (encapsulation, inheritance/derivation, polymorphism) angle.
Encapsulation: OC and C + + all have their own style of class structure syntax definition way. The OC member variable defaults to protected, which is an attribute of OC that encapsulates the data in the object. C + + defaults to private. OC can be extended by classification to the original class, without destroying the class encapsulation attribute on the basis of the method to add the class, but cannot increase the member variable (property can).



Inheritance: C + + can inherit multiple parent classes at the same time. OC can only inherit by itself, but it effectively increases the flexibility and diversity of inheritance, and compensates for the disadvantage of single inheritance.



Polymorphic: That is, the same class has a function (method) with the same name, but the corresponding function (method) can be distinguished by category. The difference between C + + and OC is that its object takes function invocation, and the binding of classes and functions in the compilation phase (except for the dynamic binding mechanism of virtual functions), which is obviously different from OC, and OC is a runtime system to find the specific class method and realize it.



Moreover, C + + can implement function overloading functions, OC does not have this function.


Q2. Characteristics of attributes, and the difference between instance variables, the use of points?


A: property is a feature of OC that encapsulates the data in an object. OC stores the data required for an object by defining an instance variable and is accessed through the Access method (Access Method,setter,getter). The above concepts are molded and become part of OC 2.0 through the "Properties" feature.



Using "attributes" instead of defining traditional instance variables and access methods allows the compiler to automatically synthesize access methods to improve program performance (you can tell the compiler not to implement the instance variables and access methods that the property uses by @dynamic keywords). The introduction of dot Syntax (dot syntax) improves program readability ("."). The syntax is actually compiled into a message delivery model [receiver message]).



Property has some special-purpose keywords (traits), generally divided into three categories: atomicity, accessor control, memory management
(1) atomicity
Atomic (default): Only one thread is allowed to access instance variables, thread safety is inefficient
Nonatomic: Can be accessed by multithreading, high Efficiency
(2) Read and Write permissions
ReadWrite (default): When a property is implemented through @synthesize, the compiler automatically generates setter and Getter methods
ReadOnly : The compiler will only synthesize the Get method when the property is implemented by @synthesize, only the getter does not have a setter
(3) memory management
Displays the memory management policy
Assign (default): For value types, such as Int,float, Nsinteger, such as a simple copy of the
retain: In the Setter method, the incoming object needs to be referenced to count +1, that is, the object has ownership, the object will not be freed
Strong: and retain the same meaning, and produce the same Code, But more semantically, the object has an operation in the
Weak:setter method that does not reference the incoming object by +1, that is, there is no ownership of the incoming object, when the object reference count is 0 o'clock, the object is disposed, and the declaring instance variable points to nil
unsafe_unretained : Same as assign, but it applies to "object type", non-owning relationship, when the target object is cleared, the property is not emptied (nil, and weak is different), access causes a crash.
Copy: is similar to strong, but differs in that it has ownership over the object's copy rather than the object itself, and is commonly used in the NS String * type to protect its encapsulation.



Main points of use of property
1. In implementation, if you do not use @synthesize, the attribute can be used through _name (the compiler hides the @synthesize name = _name;) or self.name, [self name] access, the dot operator and the The effect is the same as the default getter method.
2. However, if you customize the getter or setter method, you can not use self in the method implementation, you need to use _name to access the instance variable, otherwise you will enter the dead loop, the following demo code is reflected in
3. If you use @synthesize, you can use the variable name directly


// ------ AClass.h ------
#import <Foundation / Foundation.h>
@interface AClass: NSObject
// property
@property (nonatomic, strong) NSString * aName;
// print
-(void) print;
// self-defined getter & setter
// Mainly compare with the custom getter method, through the restrictions
-(NSString *) aName;
@end

// ------ AClass.m ------
@implementation AClass

// @ synthesize aName = _aName; // system hidden
// @ synthesize aName;

// print
-(void) print
{
    // call instance variable
    NSLog (@ "Internal Print method directly calls instance variable% @", _aName);
    // call custom getter function
    NSLog (@ "Internal Print method gets property% @", self.aName) through access method;
    NSLog (@ "Internal Print method gets attribute% @" through access method, [self aName]);
}

// getter
-(NSString *) aName
{
    if ([_aName isEqualToString: @ "King"]) {// self.aName will enter an endless loop
        return _aName;
    }
    else {
        return @ "Not King ~";
    }
}
@end

// ------ main.m ------
int main (int argc, char const * argv [])
{
    @autoreleasepool {
        AClass * a = [[AClass alloc] init];
        a.aName = @ "King";
        NSLog (@ "Property access via dot operator:% @", a.aName);
        // setter to call accessor method
        [a setAName: @ "King2"];
        NSLog (@ "Property access via access method:% @", [a aName]);
        NSLog (@ "----------------------------------------");
        [a print];
        return 0;
    }
}
OutPut:
Property access via dot operator: King
Property access via access method: Not King ~
----------------------------------------
The internal Print method directly calls the instance variable King2
The internal Print method obtains the property Not King through the access method ~
The internal Print method obtains the property Not King through the access method ~ `
Q3. Class inheritance, the concept and use of protocols and classifications, and the issues needing attention?


Scattered Knowledge points Summary (maybe you need it or learn something important):


    • [ inherit ] OC is an object-oriented language, and the inheritance mode and C + + have obvious differences that is single inheritance, without C + + inheritance. However, multi-protocol makes up for the defects that cannot inherit more. How you can inherit from a subclass
      A. Add a new method/or instance variable,
      B. Special interface encapsulation of classes,
      C. Overwrite one or more methods to change the default behavior of a class

    • [polymorphic, dynamic type and dynamic binding]
      Polymorphic: Different class objects define the same name
      Dynamic type ID Type: The class of the owning object is determined until run time, and the generic object type is defined as:
      typedef struct OBJC_OBJECT *id;
      (The ID variable cannot use the dot operator)
      Dynamic binding: The runtime determines the actual object method to invoke

    • [Category-Category]
      Provides a simple way to modularize a class definition into a group or category of related methods. Generally, if the main class is B, the classification header file and the implementation file name are: B+subclass.h, B+SUBCLASS.M
      From the invocation angle, classification is an extension of the original class
      More readable classification from a procedural point of view

Classification file format
#import "SuperClassName.h"
@interface Fraction (Mathop)
@end


class extension :


If you create an unnamed classification, it is called an extension of the class, which is not allowed when there is a named taxonomy. Unlike named classifications, unnamed classifications are implemented primarily in the main implementation area, rather than separating the implementation area. Methods and properties, or instance variables, that do not name a taxonomy extension can be private only by the class itself.


Category Usage Scenarios:


A. Classes that have already been defined need to add new method features
B. There are many different types of methods in a class that need to be implemented by different teams to facilitate task assignment


Note the problem:


A. Category can access the original class method, but cannot add variables, adding variables can be implemented by creating subclasses (inheritance)
B. Category can overload the original method, resulting in the inability to access the original method, creating subclasses to implement overloaded overrides
C. Different from normal interface, classification implementation file can not implement all the Declaration method

    • Agreement
      A protocol is a list of methods that are shared by multiple classes, and the methods listed in the protocol do not have a corresponding implementation, and the methods of using the protocol can be implemented by means of documentation.


A list of methods that are not part of any class, where the declared method can be implemented by any class. This mode is called proxy mode. Implement different patterns in different scenarios. Apple employs a number of proxy models to achieve the decoupling of view and Controller in MVC.



The most commonly used is the principal-agent model, which is used extensively in the cocoa framework to decouple data and UI: All events generated by UIView are delegated to the Controller for completion



The suffix of delegate in the frame is Protocol


@protocol nscopying
-(ID) Copywithzone: (Nszone *) zone;
@end
(can be defined in a separate. h header file, or in a related class H file)
Use:
@interface Addressbook:nsobject


Ps:1. There is no need to declare the method of the Protocol in the interface section, but to define these methods in the implementation section
2. The following code can be used to check whether an object follows a protocol
ID currentobject;
if ([Currentobject conformstoprotocol: @protocol (Drawing)] = = YES) {
}
3. You can also use Respondstoselector: @selector () to check whether an optional method is implemented
Agent (delegation)
-(BOOL) Respondstoselector:selector is widely used to implement the definition of a delegate method
4. ID currentobject; Check for variable consistency with the compiler
5. As with the class name, the protocol name must be unique
6. The protocol is inheritable, has inherited attributes, and if protocol B inherits protocol A, implementing protocol B requires implementing all the methods of A and B


    • [Agent] Delegation
      A protocol is a definition of an interface between two classes, and a class that defines a protocol can be thought of as a proxy for the method that defines the protocol to the class that implements them. (The class that defines the protocol is called a proxy)
// ****** Test example: (covering some of the previous content, can be considered as a combination of ideas)
//******MTProtocol.h file, which is the defined protocol
@protocol Printing
// default
@required
-(void) printProtocol;
@optional
-(void) printProtocolOptional;
@end

//******A.h file, containing class A definition, using Printing protocol
#import <Foundation / Foundation.h>
#import "MTProtocol.h"
// Define instance variables at the interface, using protocol
@interface A: NSObject <Printing>
{
    int x;
}
@property (nonatomic, assign) int y;
-(void) initXY;
-(void) printXY;
@end

//******A.m file, contains class A implementation, pay attention to the problem of instance variables and property initialization (there is no overload of the init method here, so the template self = [super init] is not required ...)
#import "A.h"
@implementation A
-(void) initXY
{
    x = 1;
    self.y = 2;
}
-(void) printXY
{
    NSLog (@ "This is Class A:% i,% i", x, self.y);
}
-(void) printProtocol
{
    NSLog (@ "I am printProtocol Method form Printing!");
}
-(void) printProtocolOptional
{
    NSLog (@ "I am printProtocolOptional Method form Printing!");
}
@end

//******A+Op.h Class A classification interface for extension (feeling as extension, on the one hand, through subclasses, on the one hand, classification extension in the original class, or composite class, which is more exotic)
#import "A.h"
@interface A (Op)
-(void) printCategory;
@end

//******A+Op.m Class A implementation
#import "A + Op.h"
@implementation A (Op)
-(void) printCategory
{
    NSLog (@ "Op Category for Class A!");
}
@end

//******B.h Class B interface, class A subclass, in class B we try unnamed classification, that is, private method extension
#import "A.h"
@interface B: A
-(void) initXY;
-(void) printXY;
@end

//******B.m Class B implementation, pay attention to unnamed classification
#import "B.h"
@interface B ()
-(void) printNanNameCategory;
@end
@implementation B
-(void) initXY
{
    x = 10; // Instance variables are defined at the interface in class A and can be inherited
    super.y = 20; // Attributes or implementation-declared variables are private instance variables, which are obtained through the composite value method
}
-(void) printXY
{
    NSLog (@ "This is Class B:% i,% i", x, self.y);
}
-(void) printNanNameCategory
{
    NSLog (@ "I am Nan Name Category for B!");
}
@end


//******main.m implementation, pay attention to unnamed classification
#import "A + Op.h"
#import "B.h"
// ---------- main ----------

int main (int argc, const char * argv []) {
    @autoreleasepool {
        A * a = [[A alloc] init];
        B * b = [[B alloc] init];

        [a initXY];
        [b initXY];
        // define dynamic type id
        id tmp = a;
        [tmp printXY];
        [tmp printCategory];
        [tmp printProtocol];
        [tmp printProtocolOptional];

        tmp = b;
        [tmp printXY];

        [tmp printProtocolOptional];

        // test if tmp is category A
        // [tmp isKindOfClass: [A class]]? NSLog (@ "Yes"): NSLog (@ "No");
        // test if class A contains the printXY method
        // [A instancesRespondToSelector: @selector (printXY)]? NSLog (@ "Yes"): NSLog (@ "No");
        // test if object a contains init method
        // [a respondsToSelector: @selector (init)]? NSLog (@ "Yes"): NSLog (@ "No");
}
} 

Results analysis
This is Class a:1, 2
Op Category for Class A!
I am printprotocol Method form printing!
I am printprotocoloptional Method form printing!
This is Class b:10, 20
I am printprotocoloptional Method form printing!


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.



OBJECTIVE-C 2.0 Basic Point induction


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.