Member variables vs Property

Clang

Clang is a lightweight C/C++/OC compiler written by Apple and based on LLVM. It is mainly used for low-level compilation. It outputs some files to C++ files, such as main.m to main.cpp. Its purpose is to better observe the underlying structure and implementation of some logic, easy to understand the underlying principles.

explore

The difference between member variables and attributes Basic data types(int, float nsstrings *)Called member variables.imp: the actual implementation of the method, the pointer to the function.cmd: Indicates the method number.SEL: Name of the method.

First let’s explore the underlying structure of property and member variables

Clang -rewrite-objc main.m -o main. CPP Output main.m as main. CPP by clang

We can see all of this in the above source codepropertyThere’s a correspondingset/getHow, but whyhobbythesetThe method is to assign the value by means of memory offset, andyyyNameIs through theobjc_setPropertyImplemented? Then we go to look at the source of LLVM, research below whysetYyyNameWill be calledobjc_setPropertyThe following figure is the source code creation of LLVMsetPropertyThe function ofSo let’s go back and find where it was calledGetPropertySetFunction

It can be seen from the figure above that discovery was made byswitch strategy.getKind()To determine if it’s neededsetProperty Finally found after a search when it iscopythepropertyThe time,strategyThe assignment isGetSetProperty.so whycopythesetThe method is calledsetPropertyThe reason why.

explore

When is objc_getProperty generated?

Change the project to MRC, we will find the following pattern

Atomic: use objc_getProperty assign: store use memory offset (do not need to do retain, release) retain: Store using objc_setProperty (ensure old value is released, new value is retained)Copy the code

From the source code analysis,LLVMDo these things withobjc_setPropertyobjc_getPropertyIn general, if the value is, isautomic, you need toobjc_getPropertyIf you need to do memory when setting the valuecopy.retain.releaseOperation is requiredobjc_setProperty.

coding

By looking at the source code, you will see some strange symbols, such as in the figure abovecodingCan be achieved by@encode()The encode symbol () function gets an encode symbol for all types

char *buf1 = @encode(int **);
char *buf2 = @encode(struct key);
char *buf3 = @encode(Rectangle);
Copy the code

API

Get class methods, instance methods, from the API in #import

class_getInstanceMethod
class_getClassMethod
class_getMethodImplementation
Copy the code

class_getMethodImplementationExplore, why do we sometimes not implement a method, but when calledclass_getMethodImplementationWhat if it doesn’t return empty? Because it’s going to play a default.

extension