IOS martial arts esoteric article summary

Writing in the front

As explored in the previous chapters, we have successfully made the transition from objects to classes. This article will tell the instance out of the instance object class and class structure.

A possible secret Demo for this section

First, the nature of classes

① The nature of classes

objcPrepare code under source codeusingclangwillOC fileThe outputThe CPP file. (xcrun -sdk iphonesimulator clang -arch arm64 -rewrite-objc main.m -o main-arm64.cpp)

The discovery class is used at the bottomClassReceive and then start looking for a needle in a haystack (open eye mode)ClassThe definition of

Objc_class is nowhere to be found, but it feels like it used to be. Perhaps inspiration can be found in objC’s source code

“Objc_class :”, “objc_class {“

We found thatobjc_classInheritance inobjc_object Conclusion: The essence of a class is an objc_class structure. Objc_class inherits from ObjC_Object, so everything is an object

Objc_class & Objc_Object, objC_Object and NSObject

Objc_object and NSObject

Wait, why inheritanceobjc_objectJust meetEverything is an objectA??? seenNSObjectWe know the definition ofYou can see that if you compare it carefullyNSObjectandobjc_objectThere is a relationship that cannot be explained

  • Actually,NSObjectisobjc_object“, andobjc_objectThe definition is the same, and is compiled at the bottomobjc_object
  • In the same wayNSObject classisOCVersion of theobjc_class

objc_class & objc_object

The main. M file has been compiled using clang. You can see the c++ source code below in the compiled c++ file

  • NSObjectThe underlying compilation ofNSObject_IMPLThe structure of the body
    • Among themClassisisaThe type of pointer is defined byobjc_classType defined
    • whileobjc_classIt’s a structure. In iOS, all of themClassAre based onobjc_classCreated for the template

  • Search the objC4 source code for the objC_class definition, which has two versions

    • The old version inruntime.h, has been abolished
    • The new inobjc-runtime-new.hThis is,Objc4-818.2 -The latest optimization, and our subsequent class structure analysis is based on the new versionAs you can see from the new version definitionobjc_classThe structure type is inherited fromobjc_object.
  • Search the objC4 source for objc_object or objc_object {, of which there are also two versions

    • A is located in theobjc.h, has not been abolished from compilationmain-arm64.cppAs you can see, this version is usedobjc_object
    • The other one is locatedobjc-privat.h

So what does objc_class have to do with objc_Object? Through the above source search and the underlying source code compiled in main-arm64.cpp, there are the following points:

  • Structural typeobjc_classInherited fromobjc_objectType, whereobjc_objectIt’s also a structure, and there’s aisaProperty, soobjc_classAlso has theisaattribute
  • mian-arm64.cppIn the underlying compilation file,NSObjectIn theisaAt the bottom is made up ofClassWhereclassThe underlying code comes fromobjc_classType, soNSObjectAlso has theisaattribute
  • NSObjectIs a class that initializes an instance objectobjc.objcmeetobjc_objectThat is, there areisaAttributes), mainly becauseisaIs made up ofNSObjectobjc_classInherited, andobjc_classInherited fromobjc_object.objc_objectisaProperties. SoObjects have an ISA.isaRefers to the point from the currentobjc_object
  • objc_objectStructure is currentThe root objectAll objects have this propertyobjc_objectThat hasisaattribute

The relationship between objC_object and objects

  • All of theobjectAre based onobjc_objectAs a templateinheritanceCome over
  • All objects are fromNSObject (OC)But the real bottom line is oneObjc_object (C/C + +)Struct type of
  • objc_objectobjectIs the relationship betweenInheritance relationships

(3) the Class isa

Isa isa isa isa isa isa isa isa isa isa isa

  • Everything is an object, which is inherited fromobjc_objecttheClassReception is ok
  • Strong rotation, convenientisaReturns the type of the class in bitwise

(4) summarize

  • All of theObject + class + metaclassThere areisaattribute
  • All of theobjectAre made ofobjc_objectinherited
  • The short answer isEverything is an objectEverything comes fromobjc_objectThere are two conclusions as follows:
    • All toobjc_objectCreated for the templateobject, there areisaattribute
    • All toobjc_classCreated for the templateclass, there areisaattribute
  • At the structural level, it can be popularly understood asThe upper OCThe underlyingThe butt of:
    • The lowerIs through theThe structure of the bodyThe definition of theThe template, e.g.Objc_class, objc_object
    • The upperIt’s through the bottom layerThe template to createSome types of, e.gTCJPerson

Objc_class, objC_object, ISA, Object, NSObjectAs shown in the figure below

Pointer memory offset

Before analyzing the class structure, you need to understand the memory offset because it is used when accessing the class information

① Common pointer-value copy

Let’s look at the code above, although integer variablesaandbThey’re all assigned 10, butaandbMemory addresses are not the same, and this approach is calledCopy the value.

② Object-pointer copy or reference copy

The result shows that obj1 and obj2 objects not only have different memory addresses, but also the memory addresses of the objects they point to. This method is called pointer copy or reference copy.

We can summarize the two examples above with a picture:

③ Use array pointer to derive – memory offset

It can be seen from the running results:

  • &aand&a[0]Is the same address. The first address represents the address of the first element in the array.
  • Address of the first element0x7ffeefbff400And the second element address0x7ffeefbff404So it’s 4 bytes off, which is 4 bytesintOf the 4 bytes as they areSame data type.
  • d,d+1,d+2The Pointers here add up tooffsetAddress plus 1 is the offset, which is the size of the element in which one digit is offset.
  • You can retrieve the value of the corresponding address from the address.

Third, the structure of class

Objc_class has four attributes: ISA, superclass, Cache, and bits

(1) Class ISA

There are ISA Pointers to instance objects as well as isa Pointers to class objects associated with metaclasses

Class itself is a pointer and takes up 8 bytes

(2) Class superclass

Superclass is of Class type, so it takes 8 bytes

(3) cache_t cache

While this property is a bit unfamiliar (more on this later), cache in English means cache. Cache_t is a structure whose memory size is determined by its elements: _bucketsAndMaybeMask is of type long, which is a pointer and takes up 8 bytes; As a uint32_t type, _mask takes up 4 bytes; Uint16_t is the alias of the uint16_t unsigned short, so _occupied occupies 2 bytes. 2 bytes for _flags => 16 bytes for cache_t

(4) class_data_bits_t bits

Another strange property, but apple engineers are friendly, and this is where the data is stored

So the question is, where are the property methods of a class? Is in thecacheOr in thebits? In fact, there is a diu-Diu mentioned in the previous articleobjc_classThere was aclass_rw_t *data()methods

As you can see from the previous analysis, to get the contents of bits, simply shift the first address of the class by 32 bytes.

Class_rw_t is generated at runtime in realizeClass, which contains class_ro_t. It finally inserts classified methods and protocols into its own method list, protocol list, in map_images of the dyLD callback in the _objc_init method. It does not contain the list of member variables, which is determined at compile time and is only stored in class_ro_T. However, class_rw_t contains a pointer to class_ro_t.

Class attribute methods

forTCJPersonaddhobbyMember attributes,tcj_nameAttribute variable,sayNBClass methods,sayHelloInstance methods

① Class attributes

x/4gx clsPrints the current class structure

Bits is the first memory address of the class + The memory size of ISA, superclass, and cache => 0x1000082B0 +32 bytes = 0x1000082d0

poIf you can’t print it, type strong printbitsMemory address of

According to class_rw_t *data() {return bits.data(); } print bits. The data ()

The print of the $4 pointer shows the information stored in bits, which is of type class_rw_t, also a structure type. But we still don’t see property lists, method lists, etc., so we need to explore further.

By looking at theclass_rw_tDefined source code discovery,The structure of the bodyThere areprovideThe correspondingmethodsTo obtainProperty list, method listEtc., as shown belowSo let’s keep exploringbitsThe following is a list of properties inLLDBThe process of exploration

So where did our Hobby go? Should MY TCJPerson class only have “nationality” and not “name”? Leave me alone…

Property_list in class_rw_t contains only properties, but no member variables. The difference between properties and member variables is that there are no set and get methods. If there are, they are properties; if not, they are member variables.

After a fierce operation like a tiger (open eye), foundclass_rw_tThere is a propertyclass_ro_t.

Class_ro_t is generated at compile time. It stores properties, methods, and protocols that are determined at compile time for the current class. There are no methods and protocols defined in the class.

Output at the consolero, withclass_ro_tThe structure type is exactly the same.

And our member variable is inrotheivarsInside. I’m looking forward to it

Get hobby and TCj_name as desired, but tcj_name looks a little different. If you think about it, the compiler will automatically generate a member of the attribute variable _tcj_name (_ prefix + attribute variable).

Summary:

  • through{}A defined member variable is stored in the classbitsProperty, throughbits --> data() -->ro() --> ivarsGets a list of member variables, including member variables as well as those defined by the property
  • through@propertyDefined properties are also stored inbitsProperty, throughbits --> data() --> properties() --> listGets the property list, whereInclude only attributes

② Method of class

  • classtheInstance methodsStored in theClass to the bits propertythroughbits --> methods() --> listTo obtainList of instance methods, e.g.TCJPersongOf the classExample method sayHelloIt is stored in theTCJPerson type bitsProperty, classMethods listIn addition to includingInstance methods, as well as theProperty to the set methodThe get methodAnd the system adds one at the bottomC++. Cxx_destruct method.Let’s print the verification side

  • classtheClass methodStored in theThe bits property of the metaclassthroughBits --> methods() --> listTo obtainList of class methods, e.g.TCJPersonIn theClass methods sayNBIt is stored in theTCJPerson classtheThe metaclass(The name is alsoTCJPerson)bitsProperty. Print to verify

  • The class methods of a class can be understood as instance methods of a metaclass object and therefore exist in a metaclass.

(3) conclusion

  • Member variables are storedivar
  • Property storepropertyAnd also save a copy of itivarAnd generatesetter,gettermethods
  • Object methods are storedclassinside
  • Class methods are storedThe metaclassinside

(4) API authentication

Exploit the underlying openAPIThe above conclusions can be verified

5. Ask questions

How many classes exist?

Since there is only one copy of a class’s information in memory, there is only one copy of a class object.

② Relationship between objc_Object and objects
  • All of theobjectAre based onobjc_objectAs a templateinheritanceCome over
  • All objects are fromNSObject (OC)But the real bottom line is oneObjc_object (C/C + +) struct type
  • objc_objectobjectIs the relationship betweenInheritance relationships
③ What are attributes & Member variables & Instance variables?
  • attribute(property) :OCIs through@propertyThe beginning is defined and is bandUnderline member variable + setter + getterMethod variables
  • Member variables(ivar) :OCIn the class{} is definedandNo underlineThe variables of
  • The instance variables: Indicates that the value is available based on the current object typeInstantiated variables, it is a kind ofSpecial member variables, e.g.NSObject, UILabel, UIButtonEtc.
④ What are the differences between member variables and instance variables?
  • The instance variables(i.e.Member variablesIn theObject variablesisThe instance variables) : instantiated by instance object, is a kind ofSpecial member variables
  • NSStringconstantType, because you can’t add attributes if{} defined in a classIs,Member variables
  • Member variablesremoveBasic data type, NSStringEverything elseThe instance variables(i.e.You can add attributestheMember variables), the instance variable is mainlyDetermine if it is an object
⑤ Understanding of isKindOfClass and isMemberOfClass

This is a case involvingisaGo bitmap interview questions, bold guess the resultsSo let’s exploreisKindOfClassandisMemberOfClassThe implementation of theI have done a detailed analysis in the figure above. So what is the implementation?

With breakpoint debugging, the flow of isMemberOfClass’s class methods and instance methods is normal and will go to the source code analyzed above, while isKindOfClass will not go to the source code analyzed above at all (!! Notice here, this is a pitfall), and instead go to the source code below, where the class methods and instance methods go to the objc_opt_isKindOfClass method

  • Assembly calls are as follows

  • objc_opt_isKindOfClassThe method source is as follows

Why is that? Mainly because of theLLVMThis is done at compile time inOptimization of processing.so callobjc_opt_isKindOfClassThe actual logic is shown in the figure

And then the combinationisaThe first four printed results can be obtained by bitmap (solid line is the direction of parent class) :

  • The NSObject metaclass is not equal to the NSObject class. The parent of the NSObject metaclass (pointing to the NSObject class) is equal to the NSObject class — YES
  • NSObject metaclass is not equal to NSObject class — NO
  • The TCJPerson metaclass is not equal to the TCJPerson class and the parent of the TCJPerson metaclass is not equal to the TCJPerson class — NO
  • TCJPerson metaclass is not equal to TCJPerson class — NO

The following four results are analyzed as follows:

  • NSObject is equal to NSObject — YES
  • NSObject is equal to NSObject — YES
  • TCJPerson class is equal to TCJPerson class — YES
  • TCJPerson class is equal to TCJPerson class — YES

Sixth, supplement knowledge

Strong, copy, and weak Underlying analysis

In clang-compiled CPP files you can see that the strong & copy & weak modified properties differ in the compiled underlying code

  • inTCJPersonWe define two attributes in thecopyandstrongmodified
  • withclangwillmain.mFile compiled intomain-arm64.cppAnd found thatcopystrongOf the attribute modifiedsetThere is a difference in methods

Copy attributes use objc_setProperty, but strong attributes do not.

  • inLLVMIn the searchobjc_setPropertyFind the followinggetOptimizedSetPropertyFnmethods

As you can see here, the returns are different for different modifiers

  • If it isatomic & copyDecorate,nameforobjc_setProperty_atomic_copy
  • If it isatomicNo copyDecorate,nameforobjc_setProperty_atomic
  • If it isnonatomic & copyDecorate,nameforobjc_setProperty_nonatomic_copy
  • Other remaining combinations, i.eNonatomic, nonatomic & Strong, nonatomic & weak, etc.nameforobjc_setProperty_nonatomic

A few of the abovenamecorrespondingObjc4-818.2 -The following method in the source code

And then through assembly debugging, you find that you end up at objc_storeStrong

  • copyModified property assembles debugging results

  • strongModified property assembles debugging results

  • Source searchobjc_storeStrong, there are the following source code, mainly alsoretainThe new value,releaseThe old value

  • llvmCompile source code searchobjc_storeStrongTo findEmitARCStoreStrongCallMethod, as shown in the figure below, is foundcopystrongDecorated properties enforce inconsistent policies

  • llvmIn the searchEmitARCStoreStrongCallMethods,GenerateCopyHelperFunctionMethod is called, and found herestrongweakDifferent treatments of

Among themBlockCaptureEntityKindThere are the following enumerated values and their meanings

  • If it isweakEmbellish, performEmitARCCopyWeakMethod, as shown below,weakThe underlying call isobjc_initWeak
  • If it isstrongEmbellish, performEmitARCStoreStrongCallmethods

conclusion

  • copyandstrongModified attributes are inconsistent in the underlying compilation, mainly orllvmThe results of different processing in.copyThe assignment is throughobjc_setPropertyAnd thestrongIs passed when the value ofSelf + memory translation(That is, the pointer is shifted toname, and then assign), and then restore tostrongtype
  • strong & copyCall at the bottomobjc_storeStrongIs essentially a new valueretain, the old valuerelease
  • weakCall at the bottomobjc_initWeak

② Type Encoding & Property Type String

Type Encoding- Official document Property Type String- Official document

Method signatures in CLang

Type encodingclangWhat do these characters in the method list mean when compiled?

@ @ 0:8 16, for example

  • @ 16Indicates return string occupation16 bytes– the second@8 bytes.sel8 bytes
    • The first one@saidThe return value
    • 16Indicates the total number of bytes occupied16 bytes
    • The second@: The first parameter
      • id@Forward type
      • typedef struct objc_object *id
    • 0Starting from 0 0 to 8Account for8 bytes
    • :sel, method number
    • 8Starting from the eight 8-16Account for8 bytes
  • whileV24 @ 0:8 @ 16In thev -- voidThere is no return value

See the list below for more information

Attribute of the clang compiled attribute

clangThe compiler outputs the propertyattribute, can also passproperty_getAttributesMethods to obtain

  • Tsaidtype
  • @saidVariable types
  • Csaidcopy
  • Nsaidnonatomic
  • VsaidvariableThe underline variable_tcj_name

See the list below for more information

Write in the back

Study harmoniously without being impatient. I’m still me, a different color of fireworks.