NSObject of iOS development

Source: Internet
Author: User

NSObject is the root class of most objective-c class inheritance systems. This class follows the NSObject protocol and provides some common methods by which objects inherit NSObject, which allows them to inherit access to the runtime interface and to have the object's basic ability to objective-c objects. We will introduce nsobject in detail below.

First, the use of detailed 1. Loading and initializing classes
/** runtime load class or classification calls this method, each class will only be called once */+ (void) Load {}/** class instantiation needs to be initialized before use, a class call once, if the subclass does not implement the method will call the parent class method */+ (void) Initialize {}

Comments:
The difference between load ' and ' Initialize ' is that ' load ' is called whenever a file of the class is referenced, and ' Initialize ' is called before the first method of the class or its subclasses is called. So if the class is not referenced into the project, there will be no ' load ' calls, but even if the class file is referenced but not used, then ' Initialize ' is not invoked; ' Load ' is called only once, and ' initialize ' is called only once, However, if the subclass does not implement the ' Initialize ' method, the method of the parent class is called, so the ' initialize ' method as the parent class may be called multiple times.

2. Allocating memory space and initializing objects
Lxstudent *student =  [lxstudent new]; Lxstudent *student2 = [[Lxstudent alloc] init]; Lxstudent *student3 = [[Lxstudent allocwithzone:nil] init];

notes:
When creating a new object, first call ' Alloc ' to allocate memory space for the object, and then invoke ' init ' initialization object, such as ' [[[NSObject alloc] init] ', and the ' new ' method first allocates space for the new object and initializes the object, so ' [NSObject new] ' equivalent to ' [[NSObject alloc] init] '; about the ' Allocwithzone ' method, the official document explains that the method's parameters are ignored, and the correct practice is to pass nil or null parameters to it.

3. Send message to Object (execution method)

(1) Direct call

Call no parameter no return value method (example) [student running];
Call the parameter no return value method (example) [Student readingwithtext:@ "Hello world!"];
The call has the parameter return value method (for example) nsnumber *sum = [student sumwithnum:@ (2) num2:@ (3)];

Comments:
We usually use this method of direct invocation to send messages to the object execution methods. This method is called at compile time to automatically verify the method, the parameters, the return value is correct. Therefore, we must declare the use of the method in the header file.

(2) Execute with ' Performselector '

Determine if the object can invoke the method, and then execute the call method if ([Student Respondstoselector: @selector (running)]) {     //Call no parameter no return value method     [student Performselector: @selector (running)];} if ([Student Respondstoselector: @selector (readingwithtext:)]) {     //call with parameter no return value method     [student performselector:@ Selector (readingwithtext:) withobject:@ "Hello World";} if ([Student Respondstoselector: @selector (sumwithnum:num2:)]) {     //call with parameter return value method     NSNumber *sum = [student Performselector: @selector (sumwithnum:num2:) withobject:@ (2) withobject:@ (8)];}

Comments:
Using ' Performselector: ' is the runtime system that is responsible for finding methods that do not validate at compile time, so you must first use ' Respondstoselector: ' To check if the object can invoke the method, or a run crash may occur. ' Performselector: ' is commonly used to invoke a method that is added at runtime, that is, a method that does not exist at compile time, but is present at runtime. It is also important to note that the ' Performselector: ' system provides a method that accepts up to two parameters, and the parameters and returns are ' ID ' types and do not support the underlying data type (e.g. int, float, etc.).

(3) Call with IMP pointer
//create Selsel Runsel = @selector (running); SEL Readsel = nsselectorfromstring (@ "Readingwithtext:"); SEL Sumsel = nsselectorfromstring (@ "sumwithnum:num2:"); Call no parameter no return value method imp rumimp = [student Methodforselector:runsel];void (*RUNFUNC) (ID, SEL) = (void *) Rumimp;runfunc (student, R Unsel); Call the parameter without return value method imp readimp = [[Student class] Instancemethodforselector:readsel];void (*SPEAKFUNC) (ID, SEL, NSString *) = (v OID *) Readimp;speakfunc (student, Readsel, @ "Hello world"); Call the method with the return value of the parameter imp sumimp = [student Methodforselector:sumsel]; NSNumber * (*SUMFUNC) (ID, SEL, nsnumber *, nsnumber *) = (void *) Sumimp; NSNumber *sum3 = Sumfunc (student, Sumsel, @ (6), @ (6)); 

Note: ' SEL ' is the index of the method. IMP is a function pointer that points to the address of the method. The ' SEL ' and ' IMP ' are one by one corresponding relationships, so we can modify the corresponding relationship to achieve the purpose of the runtime method Exchange.
two ways to create a ' SEL ' object :
1. Create with ' @selector () '
2. Create with ' nsselectorfromstring () '
There are two ways to get the method ' IMP ' pointer :
1, '-(IMP) Methodforselector: (SEL) Aselector; ' Instance method
2, ' + (IMP) Instancemethodforselector: (SEL) Aselector; ' Class method

4. Copying objects
Two source array Nsarray *sourcearrayi = [Nsarray arraywithobjects:@ "I", @ "I", nil]; Nsmutablearray *sourcearraym = [Nsmutablearray arraywithobjects:@ "M", @ "M", nil]; Two x Copynsarray *copyarrayi = [sourcearrayi copy]; Nsarray *copyarraym = [Sourcearraym copy]; Two x Mutablecopynsmutablearray *mutablearrayi = [Sourcearrayi mutablecopy]; Nsmutablearray *mutablearraym = [Sourcearraym mutablecopy];

Note: ' Copy ' Copy is an immutable object, ' mutablecopy ' copy is a mutable variable, ' copy ' and ' mutablecopy ' can be understood as copying a new object. While ' Copy ' is only a reference count plus 1 for a static object, it does not affect our use of objects before and after replication. It is important to note that for container objects, these two methods simply copy the container itself, and the object contained in the container is simply a pointer reference and does not have a deep copy.

5. Get class
Get class CurClass1 = [Student class]; Class CurClass2 = [Lxstudent class]; Get the parent class SupClass1 = [student superclass]; Class supClass2 = [lxstudent superclass];
6. Judgment method
Initialize object Lxperson *person = [Lxperson new]; Lxstudent *student = [lxstudent new]; Lxstudent *student2 = student; Determines whether an object inherits Nsobjectif ([student IsProxy]) {NSLog (@ "Student object is an inherited NSObject class");}//Determine if two objects are equal if ([Student isequal:student 2] {NSLog (@ "Student object is equal to Student2 object")}//Determines whether the object is a specified class if ([Person Iskindofclass:[zmperson class]]) {NSLog Like the Zmperson class ");} Determines whether the object is a specified class or subclass if ([Student Iskindofclass:[zmperson class]]) {NSLog (@ "Student object is a subclass of the Zmperson class");}//Determine if it is a subclass of another class if ([ Lxstudent Issubclassofclass:[zmperson class]) {NSLog (@ "Lxstudent class is a subclass of the Zmperson class");}//Determine if the object conforms to the protocol if ([Student Confor Mstoprotocol: @protocol (nsobject)]) {NSLog (@ "Student object follows NSObject protocol");}//Determine if the class complies with the given protocol if ([Lxstudent Conformstoprotocol: @protocol (nsobject)]) {NSLog (@ "Lxstudent class follows NSObject protocol");}//Determine if the object can invoke the given method if ([Student Respondstoselector: @selector (running)]) {NSLog (@ "Student object can call ' running ' method")}//Determine if the instance can invoke the given method if ([Lxstudent   Instancesrespondtoselector: @selector (running)]) { NSLog (@ "Lxstudent class can call ' running ' method");} 
Second, NSObject.h detailed
nsobject.h//lxheaderfile////Created by cheyin on 2018/9/4.//Copyright? 2017 Cheyin. All rights reserved.////detailed nsobject.h//Version iOS 10.3//#ifndef _objc_nsobject_h_#define _objc_nsobject_h_ #if __OBJC_ _ #include <objc/objc.h> #include <objc/NSObjCRuntime.h> @class nsstring, Nsmethodsignature, nsinvocation; #pragma the Mark-Protocol section @protocol NSObject/** to determine whether two objects are equal, such as equal return Yes, otherwise returns no */-(BOOL) IsEqual: (ID) object;
/** gets the object hash value, two objects equal hash value also equal/@property (readonly) Nsuinteger hash; /** gets the parent class of the object */@property (ReadOnly) class superclass;
/** gets the class of the current object */-(Class) class objc_swift_unavailable ("Use ' type (of:anobject) ' instead");
/** gets the current object */-(Instancetype) self; /** sends the specified message to the object, returning the message execution result (equivalent to a method call) */-(ID) performselector: (SEL) Aselector;
/** sends a message with one parameter to the object, returning the message execution result (equivalent to a method call) */-(ID) performselector: (SEL) Aselector withobject: (ID) object;
/** sends a message with two parameters to the object, returns the result of the message execution (equivalent to a method call) */-(ID) performselector: (SEL) Aselector withobject: (ID) object1 withobject: (ID) Object2; /** determines whether the object inherits NSObject */-(BOOL) IsProxy; /** determines whether the object is a given class or an instance of a given class subclass */-(BOOL) Iskindofclass: (Class) AClass;
/** determines whether an object is an instance of a given class */-(BOOL) Ismemberofclass: (Class) AClass;
/** determines whether the object conforms to the given protocol */-(BOOL) Conformstoprotocol: (Protocol *) Aprotocol; /** determines whether an object can invoke a given method */-(BOOL) Respondstoselector: (SEL) Aselector; /** object reference count plus 1, use */-(instancetype) retain objc_arc_unavailable under MRC;
/** object reference count minus 1, using */-(OneWay void) release objc_arc_unavailable under MRC;
/** object reference count is automatically reduced by 1 in deferred mode, using */-(instancetype) autorelease objc_arc_unavailable under MRC;
/** gets the object reference count, using */-(Nsuinteger) Retaincount objc_arc_unavailable under MRC;
/** gets the object storage space and uses the */-(struct _nszone *) zone objc_arc_unavailable under MRC; /** Gets the object description information */@property (readonly, copy) NSString *description;
@optional
/** Gets the description information of the object in the debugger */@property (readonly, copy) NSString *debugdescription; @end #pragma mark-class section objc_available (10.0, 2.0, 9.0, 1.0) Objc_root_classobjc_export@interface NSObject <nsobject > {class ISA objc_isa_availability;}/** runtime load class or classification calls the method, and each class calls only once */+ (void) load;
/** class instantiation needs to be initialized before it is used, a class is called once, and if the subclass does not implement the method, the parent class method */+ (void) initialize is called;
/** Initialization Object */-(instancetype) init
#if ns_enforce_nsobject_designated_initializerns_designated_initializer#endif; /** allocates memory space for the new object and initializes it, equals [[NSObject alloc] init] */+ (instancetype) New Objc_swift_unavailable ("Use object initializers instead ");
/** allocates memory space for new objects, parameters are nil */+ (instancetype) Allocwithzone: (struct _nszone *) zone objc_swift_unavailable ("Use Object initializers instead ");
/** allocates memory space for new objects */+ (instancetype) alloc objc_swift_unavailable ("Use object initializers instead");
/** releases the object, which calls this method */-(void) dealloc objc_swift_unavailable ("Use ' deinit ' to define a De-initializer") when the object's reference count is 0;
The/** garbage collector calls this method before it processes the memory it uses. */-(void) Finalize objc_deprecated ("Objective-c garbage collection is no longer supported"); /** copy for immutable object */-(ID) copy;
/** Copy to Variable object */-(ID) mutablecopy; /** is copied as an immutable object on the specified memory space, using */+ (ID) copywithzone under MRC: (struct _nszone *) zone objc_arc_unavailable;
/** is copied as a Mutable object on the specified memory space, using */+ (ID) mutablecopywithzone under MRC: (struct _nszone *) zone objc_arc_unavailable; /** Determines whether an instance can invoke a given method */+ (BOOL) Instancesrespondtoselector: (SEL) Aselector;
/** determines whether the class complies with the given protocol */+ (BOOL) Conformstoprotocol: (Protocol *) Protocol;
/** gets the pointer to the method implementation IMP */-(IMP) Methodforselector: (SEL) Aselector;
/** gets the pointer to the instance method implementation IMP */+ (IMP) Instancemethodforselector: (SEL) Aselector;
/** cannot find the function implementation will call this method throws an exception */-(void) Doesnotrecognizeselector: (SEL) Aselector; /** returns a message that was first forwarded by the object, the object does not find the SEL's IML when it executes the call to the method */-(ID) forwardingtargetforselector: (SEL) Aselector objc_available (10.5, 2.0, 9.0, 1.0);
/** Methodsignatureforselector: The method is called without nil, you can override the method to forward the SEL to another object */-(void) Forwardinvocation: (Nsinvocation *) Aninvocation objc_swift_unavailable ("");
/** gets the method signature, the object does not find the SEL's IML when it executes the call to the method, you can override the method to throw a function signature, and then by Forwardinvocation: Go to execute */-(nsmethodsignature *) Methodsignatureforselector: (SEL) Aselector objc_swift_unavailable (""); /** Get instance method signature */+ (Nsmethodsignature *) Instancemethodsignatureforselector: (SEL) Aselector objc_swift_unavailable (""); /** allows weak reference scalars, and for all classes that return no for all allowsweakreference methods, you must never use the __weak modifier */-(BOOL) allowsweakreference Unavailable_attribute;
/** retains the weak reference variable, which uses the "nil" */-(BOOL) retainweakreference when the Retainweakreference method of the Assigned object returns no if the variable using the __weak modifier is returned. Unavailable_attribute; /** determines if it is a subclass of another class */+ (BOOL) Issubclassofclass: (Class) AClass; /** dynamic parsing of a class method */+ (BOOL) Resolveclassmethod: (SEL) SEL objc_available (10.5, 2.0, 9.0, 1.0);
/** dynamically parses an instance method that calls the method when the object does not find the SEL's IML, you can override the method to add the required sel */+ (BOOL) Resolveinstancemethod to the object: (SEL) sel objc_available ( 10.5, 2.0, 9.0, 1.0); /** gets the object hash value, two objects equal hash value is equal */+ (Nsuinteger) hash;
/** gets the parent class of the object */+ (Class) superclass;
/** gets the class */+ (Class) class objc_swift_unavailable ("Use ' aclass.self ' instead");
/** Gets the object description information */+ (NSString *) description;
/** Gets the description information of the object in the debugger */+ (NSString *) debugdescription; @end #endif #endif







NSObject of iOS development

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.