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
objc
Prepare code under source codeusingclang
willOC file
The outputThe CPP file
. (xcrun -sdk iphonesimulator clang -arch arm64 -rewrite-objc main.m -o main-arm64.cpp
)
The discovery class is used at the bottomClass
Receive and then start looking for a needle in a haystack (open eye mode)Class
The 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_class
Inheritance 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_object
Just meetEverything is an object
A??? seenNSObject
We know the definition ofYou can see that if you compare it carefullyNSObject
andobjc_object
There is a relationship that cannot be explained
- Actually,
NSObject
isobjc_object
“, andobjc_object
The definition is the same, and is compiled at the bottomobjc_object
- In the same way
NSObject class
isOC
Version 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
NSObject
The underlying compilation ofNSObject_IMPL
The structure of the body- Among them
Class
isisa
The type of pointer is defined byobjc_class
Type defined - while
objc_class
It’s a structure. In iOS, all of themClass
Are based onobjc_class
Created for the template
- Among them
-
Search the objC4 source code for the objC_class definition, which has two versions
- The old version in
runtime.h
, has been abolished - The new in
objc-runtime-new.h
This 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_class
The structure type is inherited fromobjc_object
.
- The old version in
-
Search the objC4 source for objc_object or objc_object {, of which there are also two versions
- A is located in the
objc.h
, has not been abolished from compilationmain-arm64.cpp
As you can see, this version is usedobjc_object
- The other one is located
objc-privat.h
- A is located in the
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 type
objc_class
Inherited fromobjc_object
Type, whereobjc_object
It’s also a structure, and there’s aisa
Property, soobjc_class
Also has theisa
attribute mian-arm64.cpp
In the underlying compilation file,NSObject
In theisa
At the bottom is made up ofClass
Whereclass
The underlying code comes fromobjc_class
Type, soNSObject
Also has theisa
attributeNSObject
Is a class that initializes an instance objectobjc
.objc
meetobjc_object
That is, there areisa
Attributes), mainly becauseisa
Is made up ofNSObject
从objc_class
Inherited, andobjc_class
Inherited fromobjc_object
.objc_object
有isa
Properties. SoObjects have an ISA
.isa
Refers to the point from the currentobjc_object
objc_object
Structure is currentThe root object
All objects have this propertyobjc_object
That hasisa
attribute
The relationship between objC_object and objects
- All of the
object
Are based onobjc_object
As a templateinheritance
Come over - All objects are from
NSObject (OC)
But the real bottom line is oneObjc_object (C/C + +)
Struct type of objc_object
与object
Is 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 from
objc_object
theClass
Reception is ok - Strong rotation, convenient
isa
Returns the type of the class in bitwise
(4) summarize
- All of the
Object + class + metaclass
There areisa
attribute - All of the
object
Are made ofobjc_object
inherited - The short answer is
Everything is an object
Everything comes fromobjc_object
There are two conclusions as follows:- All to
objc_object
Created for the templateobject
, there areisa
attribute - All to
objc_class
Created for the templateclass
, there areisa
attribute
- All to
- At the structural level, it can be popularly understood as
The upper OC
与The underlying
The butt of:The lower
Is through theThe structure of the body
The definition of theThe template
, e.g.Objc_class, objc_object
The upper
It’s through the bottom layerThe template to create
Some types of, e.gTCJPerson
Objc_class, objC_object, ISA, Object, NSObject
As 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 variablesa
andb
They’re all assigned 10, buta
andb
Memory 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:
&a
and&a[0]
Is the same address. The first address represents the address of the first element in the array.- Address of the first element
0x7ffeefbff400
And the second element address0x7ffeefbff404
So it’s 4 bytes off, which is 4 bytesint
Of the 4 bytes as they areSame data type
. d
,d+1
,d+2
The 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 thecache
Or in thebits
? In fact, there is a diu-Diu mentioned in the previous articleobjc_class
There 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
forTCJPerson
addhobby
Member attributes,tcj_name
Attribute variable,sayNB
Class methods,sayHello
Instance methods
① Class attributes
x/4gx cls
Prints 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
po
If you can’t print it, type strong printbits
Memory 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_t
Defined source code discovery,The structure of the body
There areprovide
The correspondingmethods
To obtainProperty list, method list
Etc., as shown belowSo let’s keep exploringbits
The following is a list of properties inLLDB
The 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_t
There 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_t
The structure type is exactly the same.
And our member variable is inro
theivars
Inside. 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 classbits
Property, throughbits --> data() -->ro() --> ivars
Gets a list of member variables, including member variables as well as those defined by the property - through
@property
Defined properties are also stored inbits
Property, throughbits --> data() --> properties() --> list
Gets the property list, whereInclude only attributes
② Method of class
-
class
theInstance methods
Stored in theClass to the bits property
throughbits --> methods() --> list
To obtainList of instance methods
, e.g.TCJPersong
Of the classExample method sayHello
It is stored in theTCJPerson type bits
Property, classMethods list
In addition to includingInstance methods
, as well as theProperty to the set method
和The get method
And the system adds one at the bottomC++. Cxx_destruct method
.Let’s print the verification side -
class
theClass method
Stored in theThe bits property of the metaclass
throughBits --> methods() --> list
To obtainList of class methods
, e.g.TCJPerson
In theClass methods sayNB
It is stored in theTCJPerson class
theThe metaclass
(The name is alsoTCJPerson
)bits
Property. 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 stored
ivar
- Property store
property
And also save a copy of itivar
And generatesetter
,getter
methods - Object methods are stored
class
inside - Class methods are stored
The metaclass
inside
(4) API authentication
Exploit the underlying openAPI
The 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 the
object
Are based onobjc_object
As a templateinheritance
Come over - All objects are from
NSObject (OC)
But the real bottom line is oneObjc_object (C/C + +
) struct type objc_object
与object
Is the relationship betweenInheritance relationships
③ What are attributes & Member variables & Instance variables?
attribute
(property
) :OC
Is through@property
The beginning is defined and is bandUnderline member variable
+setter
+getter
Method variablesMember variables
(ivar
) :OC
In the class{} is defined
andNo underline
The variables ofThe 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, UIButton
Etc.
④ What are the differences between member variables and instance variables?
The instance variables
(i.e.Member variables
In theObject variables
isThe instance variables
) : instantiated by instance object, is a kind ofSpecial member variables
NSString
是constant
Type, because you can’t add attributes if{} defined in a class
Is,Member variables
Member variables
removeBasic data type, NSString
Everything elseThe instance variables
(i.e.You can add attributes
theMember variables
), the instance variable is mainlyDetermine if it is an object
⑤ Understanding of isKindOfClass and isMemberOfClass
This is a case involvingisa
Go bitmap interview questions, bold guess the resultsSo let’s exploreisKindOfClass
andisMemberOfClass
The 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_isKindOfClass
The method source is as follows
Why is that? Mainly because of theLLVM
This is done at compile time inOptimization of processing
.so callobjc_opt_isKindOfClass
The actual logic is shown in the figure
And then the combinationisa
The 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
- in
TCJPerson
We define two attributes in thecopy
andstrong
modified - with
clang
willmain.m
File compiled intomain-arm64.cpp
And found thatcopy
和strong
Of the attribute modifiedset
There is a difference in methods
Copy attributes use objc_setProperty, but strong attributes do not.
- in
LLVM
In the searchobjc_setProperty
Find the followinggetOptimizedSetPropertyFn
methods
As you can see here, the returns are different for different modifiers
- If it is
atomic & copy
Decorate,name
forobjc_setProperty_atomic_copy
- If it is
atomic
且No copy
Decorate,name
forobjc_setProperty_atomic
- If it is
nonatomic & copy
Decorate,name
forobjc_setProperty_nonatomic_copy
- Other remaining combinations, i.e
Nonatomic, nonatomic & Strong, nonatomic & weak
, etc.name
forobjc_setProperty_nonatomic
A few of the abovename
correspondingObjc4-818.2 -
The following method in the source code
And then through assembly debugging, you find that you end up at objc_storeStrong
-
copy
Modified property assembles debugging results -
strong
Modified property assembles debugging results -
Source search
objc_storeStrong
, there are the following source code, mainly alsoretain
The new value,release
The old value -
llvm
Compile source code searchobjc_storeStrong
To findEmitARCStoreStrongCall
Method, as shown in the figure below, is foundcopy
和strong
Decorated properties enforce inconsistent policies -
llvm
In the searchEmitARCStoreStrongCall
Methods,GenerateCopyHelperFunction
Method is called, and found herestrong
和weak
Different treatments of
Among themBlockCaptureEntityKind
There are the following enumerated values and their meanings
- If it is
weak
Embellish, performEmitARCCopyWeak
Method, as shown below,weak
The underlying call isobjc_initWeak
- If it is
strong
Embellish, performEmitARCStoreStrongCall
methods
conclusion
copy
andstrong
Modified attributes are inconsistent in the underlying compilation, mainly orllvm
The results of different processing in.copy
The assignment is throughobjc_setProperty
And thestrong
Is passed when the value ofSelf + memory translation
(That is, the pointer is shifted toname
, and then assign), and then restore tostrong
typestrong & copy
Call at the bottomobjc_storeStrong
Is essentially a new valueretain
, the old valuerelease
weak
Call at the bottomobjc_initWeak
② Type Encoding & Property Type String
Type Encoding- Official document Property Type String- Official document
Method signatures in CLang
Type encoding — clang
What do these characters in the method list mean when compiled?
@ @ 0:8 16, for example
@ 16
Indicates return string occupation16 bytes
– the second@
占8 bytes
.sel
占8 bytes
- The first one
@
saidThe return value
16
Indicates the total number of bytes occupied16 bytes
- The second
@
: The first parameterid
—@
Forward typetypedef struct objc_object *id
0
—Starting from 0
0 to 8
Account for8 bytes
:
–sel
, method number8
—Starting from the eight
8-16
Account for8 bytes
- The first one
- while
V24 @ 0:8 @ 16
In thev -- void
There is no return value
See the list below for more information
Attribute of the clang compiled attribute
clang
The compiler outputs the propertyattribute
, can also passproperty_getAttributes
Methods to obtain
T
saidtype
@
saidVariable types
C
saidcopy
N
saidnonatomic
V
saidvariable
The 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.