preface

Short step without thousands of miles, not small streams into rivers and seas. Learning is like rowing upstream; not to advance is to drop back. I’m a hauler who drifts from platform to platform. Today I share with you the interview questions that I have sorted out in the last half month. You have everything you want. Nonsense not to say, directly to everyone dry goods, I hope to help you, excellent people have been praised.

1: Talk about your understanding of KVC

KVC can access attributes of an object directly through a key or assign values to attributes of an object, which can be accessed or modified dynamically at run time

**setValue: ** forKey: @ “name” when calling the code: **setValue: ** forKey: @ “name”

  • 1. Program priority callset<Key>:Property value method, code throughA setter methodThe Settings are complete. Notice, here<key>Is the name of a member variableKVCThe following is the same naming rule
  • 2, if not foundElegantly-named setName:Method, the KVC mechanism checks+ (BOOL)accessInstanceVariablesDirectlyDoes the method returnYESBy default, this method returnsYESIf you override the method to return NO, then in this stepKVCWill performSetValue: forUndefinedKey:Method, but most developers don’t do that. So the KVC mechanism will search the class for names<key>, regardless of whether the variable is defined at the interface of the class or at the implementation of the class, and regardless of what access modifier is used, only exists when<key>KVC can assign a value to a named variable.
  • 3. If the class does not existSet < key > :Method, no_<key>Member variables, KVC mechanism will search_is<Key>A member variable of.
  • 4. As above, if the class has neither set: methods nor _ and _is member variables, the KVC mechanism continues to search for and is member variables. And I’m going to assign them.
  • 5. If none of the methods or member variables listed above exists, the system will execute the objectSetValue: forUndefinedKey:Method, which by default throws an exception.

If you want to disable KVC, rewrite + (BOOL) accessInstanceVariablesDirectly method to return NO, so if the KVC had not found the set < Key > : For attribute names, the setValue: forUndefinedKey: method is used directly.

When calling valueForKey: @ “name” code, KVC searches forKey in a different way than setValue: forKey: @ “name”. The search method is as follows:

  • 1. Press firstget<Key>,<key>,is<Key>The sequential method lookup ofgetterMethod is called directly if found. If it isBOOLorIntThe equivalent type will be wrapped as aNSNumberobject
  • 2, if the abovegetterI couldn’t find it.KVCWill findcountOf<Key>,objectIn<Key>AtIndexor<Key>AtIndexesFormat methods. ifcountOf<Key>Method and one of the other two methods are found, and a collection of proxies that can respond to all of NSArray’s methods is returned (it isNSKeyValueArray, it isNSArraySubclass), calls the methods of the proxy collection, or sends a class ofNSArray“, will be toObjectIn countOf < Key >, < the Key > AtIndex or < Key > AtIndexesCall in the form of a combination of these methods. There’s another optionget<Key>:range:Methods. So if you want to redefine some of the functionality of KVC, you can add these methods. Be careful that your method names follow KVC’s standard naming methods, including method signatures.
  • 3. If the above method is not found, both methods are searchedEnumeratorOf countOf < Key >, < the Key >, memberOf < Key >Format methods. If all three methods are found, then a collection of proxies that can respond to the methods of the NSSet is returnedEnumeratorOf countOf < Key >, < the Key >, memberOf < Key >Call in the form of a combination.
  • 4. If not, check the class method again+ (BOOL)accessInstanceVariablesDirectly, if returnYES(default behavior), then, as previously set, will press_<key>,_is<Key>,<key>,is<Key>This is not recommended because direct access to instance variables breaks encapsulation and makes the code more vulnerable. If you override the class method+ (BOOL)accessInstanceVariablesDirectlyreturnNOIf so, it will be called directlyvalueForUndefinedKey:Method, which by default throws an exception

2. Resolution of conflicts caused by reference to multiple third-party libraries in iOS projects

There may be many partners are not quite clear, dynamic and static library development, here recommend a blog: iOS- production. A static library SDK and use. A static library

Duplicate Symbol _OBJC_IVAR_$_xxxx in: duplicate Symbol _OBJC_IVAR_$_xxxx in:

The fastest way to do it right now is to.frameworkSelected,taggert MembershipIf the check box is unchecked, the compilation is fine, but other problems may occur later

What I’m trying to say is that open-source source code like this should not be included in lib, and if you do, you should change the name. But there is no way now that the others include, we have to think of a way to separate

  • Mkdir armv7: creates a temporary folder
  • Lipo libALMovie. A -thin armv7 - Output armv7/armv7.a: Fetch armv7 platform package
  • Ar-t armv7/armv7.a: View the list of files contained in the library
  • CD armv7&& ar xv armv7.a: Decompress object file
  • Rm albutton. o: Find the conflicting package and delete it (this step can be repeated)
  • CD... && ar RCS armv7.a armv7/*. O: Repackage the object file
  • For multi-platform SDKS, you need to do step 4 several times. After the operation is complete, merge the files on multiple platforms into one file.lipo -create armv7.a arm64.a -output new.a
  • Drag the modified file to the original folder and replace the original file.

3: GCD implements multiple read and single write

For example, if a piece of data is maintained in memory, it may be manipulated in several places at the same time. How can data security be ensured? This topic is summarized to meet the following three points:

  • 1. Read and write are mutually exclusive
  • 2. Write mutually exclusive
  • 3. Read and write
@implementation KCPerson
- (instancetype)init
{
    if (self = [super init]) {
       _concurrentQueue = dispatch_queue_create("com.kc_person.syncQueue", DISPATCH_QUEUE_CONCURRENT);
       _dic = [NSMutableDictionary dictionary];
    }
    return self;
}
- (void)kc_setSafeObject:(id)object forKey:(NSString *)key{
    key = [key copy];
    dispatch_barrier_async(_concurrentQueue, ^{
       [_dic setObject:object key:key];
    });
}

- (id)kc_safeObjectForKey::(NSString *)key{
    __block NSString *temp;
    dispatch_sync(_concurrentQueue, ^{
        temp =[_dic objectForKey:key];
    });
    return temp;
}
@end
Copy the code
  • First we need to maintain a GCD queue, preferably not global queue, after all, we all know that global queue encounter fence function is pit point, here will not analyze!

  • Because the consideration of performance deadlock jams does not consider serial queues, use custom concurrent queues! _concurrentQueue = dispatch_queue_create(“com.kc_person.syncQueue”, DISPATCH_QUEUE_CONCURRENT);

  • First let’s look at the read operation :kc_safeObjectForKey we can’t use asynchronous function because of multithreading! Description:

    • Thread 2 gets:nameThread 3 fetchage
    • What would have been read if there was confusion due to asynchronous concurrencynameAnd I readage
    • We allow multiple tasks in at the same time! But the read operation needs to return synchronously, so we choose:Synchronization function  (Read and write)
  • Let’s take a look at the write operation. The key is copied during the write operation. Insert a quote from the reference to explain this:

The function caller is free to pass an NSMutableString key and can modify it after the function returns. So we must copy the string passed in to make sure the function works correctly. If the string passed in is not mutable (that is, the normal NSString type), calling copy is essentially a null operation.

  • Dispatch_barrier_async = dispatch_barrier_async;

    • Fence function task: all previous tasks are completed, and no other tasks are executed until the task after it starts, so it is better to encourage write operations one after another (write mutually exclusive), no mess!
    • Why not an asynchronous function? It should be easy to analyze, after all, it creates chaos!
    • Why not use a synchronization function? If both the read and write operations are performed, then it is possible to use the synchronization function: I need to wait for the read operation to return to execute, obviously this is not reasonable!

4: Talk about the implementation mechanism of atomic; Why can’t we guarantee absolute thread-safety (preferably in context)?

A: Atomic implementation mechanism

  • atomicispropertyOne of the modifiers of, meaning atomic, used as@property(atomic)int age; The compiler generates it automaticallygetter/setterMethod will eventually be calledobjc_getPropertyandobjc_setPropertyMethod to access properties.
  • If the property is usedatomicThe modifier is used inside both methodsos_unfair_lockTo lock, to ensure the atomicity of read and write. Locks inPropertyLocksThe locks will be initialized before they are used. When they need to be used, the address of the object plus the offset of the member variable iskeyTo go toPropertyLocksTo get in. Because the same lock is used to access the property, atomic can guarantee thread-safe access to the property.
  • Note: Since locks are finite, it is possible to read different properties using the same lock without using objects

B: Why can’t atomic guarantee absolute thread safety?

  • atomicingetter/setterMethod is only thread-safe at access, assuming that our property is@property(atomic)NSMutableArray *array; With mutable containers, there is no guarantee that changes to the container will be thread-safe.
  • Automatically produced in the compilergetter/setterMethod will eventually be calledobjc_getPropertyandobjc_setPropertyMethod access properties inside this method ensure thread-safe reading and writing when we overridegetter/setterMethod, can only rely on their owngetter/setterTo ensure thread safety

5. What is the data structure used by Autoreleasepool? Is the AutoreleasePoolPage structure understood?

  • AutoreleasepoolIs composed of multipleAutoreleasePoolPageIn the form of a bidirectional linked list.
  • AutoreleasepoolThe basic principle of each auto release pool is created in the currentAutoreleasePoolPageSets a marker bit during which an object is calledautorelsease, the object is addedAutoreleasePoolPageIn the
  • If the current page is full, a new page is initialized, then linked with a bidirectional table, and the newly initialized page is set tohotPageWhen the pool pop is automatically released, each object’s pop is called from the bottom upreleaseMethod until the flag bit is encountered.

AutoreleasePoolPageStructure is as follows

class AutoreleasePoolPage { magic_t const magic; id *next; Pthread_t const thread; //AutoreleasePoolPage thread AutoreleasePoolPage * const parent; // AutoreleasePoolPage *child; // Uint32_t const depth; Uint32_t hiwat; // Uint32_t hiwat; }Copy the code

6: How many ways to introspect in iOS? What is the difference between the class method and the objc_getClass method?

  • 1: What is introspection?

In computer science, introspection refers to the ability of a computer program to check the type of an Object at Run time, often referred to as runtime type checking. Introspection should not be confused with reflexes. Taking introspection one step further, reflection refers to the ability of a computer program to access, detect, and modify its own state or behavior during Run time.

  • 2: How many methods of introspection in iOS?

IsMemberOfClass // Is the object of a certain type isKindOfClass // Is the object of a certain type or a subclass of a certain type isSubclassOfClass // Is the object of a certain type a subclass of another type IsAncestorOfObject // Whether an object of a class is a parent of another type respondsToSelector // Whether a method responds to conformsToProtocol // whether it follows a protocol

  • 3: What is the difference between the class method and object_getClass method?

    • The instanceclassMethod returns directlyobject_getClass(self)
    • classclassMethod returns directlyselfAnd theobject_getClass(class object), returns a metaclass

7: What is the difference between classification and extension? What can be used for? What are the limitations of classification? What are the members of the classification structure?

  • 1: Classification is mainly used to add methods, attributes and protocols for a class (I usually use it to extend methods for the class of the system or to separate the functions of a complex class into different files)
  • 2: Extensions are mainly used for member variables, attributes, and methods that a class does not already have. Note: Methods are declarations only (I usually declare private properties with extensions, or override read-only properties of.h to be read and write)

The difference between classification and extension:

  • Classification merges classification information into class information at run time, whereas extension merges information into the class at compile time
  • Attributes declared by a class are only generatedgetter/setterMethod declaration, does not automatically generate member variables andgetter/setterMethod, while the extension will
  • Classes cannot be used to add instance variables to classes, whereas extensions can
  • A classification can add implementations of methods to a class, whereas an extension can only declare methods, not implement them

Limitations of classification:

  • Note: The memory management of the associated object does not have weak, so you need to pay attention to the problem of wild Pointers. You can implement it through other methods. For details, please refer to the iOS weak keyword ramblers
  • A classified method with the same name as the original implementation of the class overwrites the implementation of the original method. Note: This is not true overwriting
  • Methods of multiple classes have the same name, and the implementation of the last compiled class is called

What members are in the structure of the classification

struct category_t { const char *name; // name classref_t CLS; Struct method_list_t *instanceMethods; Struct method_list_t *classMethods; Struct protocol_t *protocols; Struct property_list_t *instanceProperties; Struct property_list_t *_classProperties; // Class attribute list};Copy the code

8: Can you briefly describe the implementation mechanism of Dealloc

The Dealloc implementation mechanism is the focus of the content management part, to understand this point, for a comprehensive understanding of memory management is just very necessary.

**1.Dealloc invokes the process **

  • 1. First call _objc_rootDealloc()

  • 2. Next call rootDealloc()

  • 3. At this time, they will judge whether they can be released based on five main criteria

    • NONPointer_ISA
    • weakly_reference
    • has_assoc
    • has_cxx_dtor
    • has_sidetable_rc
  • 4-1. If it is isTaggedPointer, it returns directly

  • 4-2. If any of the above five methods exists, the object_Dispose () method is called for further processing.

  • 4-2. If there is no one of the previous five cases, then the free operation can be performed, the C function free().

  • 5. No further action is required.

2. Object_dispose () invokes the process.

  • 1. Direct callobjc_destructInstance().
  • 2. Then call the C function free().

3.objc_destructInstance()Calling process

  • 1. The first judgmenthasCxxDtorIf there is C++ related content, to callobject_cxxDestruct() Destroy C++ related content.
  • 2. Judge againhasAssocitatedObjects, if any, to callobject_remove_associations()To destroy the associated object.
  • 3. Then callclearDeallocating().
  • 4. The execution is complete.

4. ClearDeallocating () calls the process.

  • 1. The first is carried outsideTable_clearDellocating().
  • 2. Perform againweak_clear_no_lockIn this step, the weak reference pointer to the object is set tonil.
  • 3. Perform the following operationstable.refcnts.eraser()To erase the object’s reference count from the reference count table.
  • 4. So far,DeallocThe execution process is complete.

9: Difference between HTTPS and HTTP

HTTPS = HTTP + SSL/TLS

  • SSLIs the full name ofSecure Sockets LayerThe Secure Socket Layer protocol (SSL) is a security protocol that provides security and data integrity for network communication.
  • TLS stands for TLSTransport Layer Security, the Secure Transport Layer protocol.

That HTTPS is secure HTTP.

HTTPS: Hyper Text Transfer Protocol Secure HTTPS: Hyper Text Transfer Protocol Secure HTTPS: Hyper Text Transfer Protocol Secure This is provided by TLS (SSL)! That’s probably what a library called openSSL provides. HTTPS and HTTP are both application Layer and are based on TCP (and UDP) protocols, but they are completely different. TCP uses port 80 and HTTPS uses port 443. (It is worth mentioning that Google invented a new protocol called QUIC that is not based on TCP but uses port 443, also for HTTPS. Google is awesome.) In general, HTTPS is similar to BUT more secure than HTTP.

10: TCP why three handshakes, four waves?

Three handshakes:

  • The client initiates a request link to the server, sending it firstSYNMessage,The SYN = 1, seq = xAnd the client entersSYN_SENTstate
  • After receiving the request link, the server replies to the client and sends a response packet.The SYN = 1, seq = y, ACK = 1, ACK = x + 1And the server entersSYN_RCVDstate
  • After receiving the acknowledgement packet, the client sends the acknowledgement packet to the server.ACK = 1, ACK = y + 1When the client entersESTABLISHEDAfter receiving the confirmation packet from the client, the server also logs inESTABLISHEDThe link is successfully created

Four waves:

  • The client initiates a close link to the server and stops sending data
  • When the server receives the request to close the link, it sends a response to the client, I know, and then stops receiving data
  • When the server ends sending data, it sends a close link to the client and stops sending data
  • When the client receives the request to close the link, it sends a response to the server, I know, and then stops receiving data

Why you need three handshakes:

In case an error occurs when an invalid connection request segment is suddenly sent to the server, assume that the connection request segment is already invalid. However, after the server receives the invalid connection request packet segment, it mistakenly thinks it is a new connection request sent by the client. Then the client sends a confirmation message to agree to establish a connection. Assuming that the “three-way handshake” is not used, a new connection is established as soon as the server sends an acknowledgement. Since the client does not send a connection request, it ignores the server’s confirmation and does not send data to the server. However, the server assumes that the new transport connection has been established and waits for data from the client. As a result, many of the server’s resources are wasted.

Why you need four waves:

In full-duplex communication, TCP may send data to the client when receiving the request to close the link. Therefore, it cannot respond to the request to close the link at the same time

11. What is the difference between symmetric encryption and asymmetric encryption? Which algorithms are implemented respectively?

Symmetric encryption, in which encryption and decryption of encryption use the same key.

  • Asymmetric encryption: a public key and a private key are used for encryption and decryption. The public key is available to all. After obtaining the public key of the receiver, the sender can use the public key to encrypt the communication, and the receiver uses the private key to decrypt the communication.
  • Symmetric encryption algorithm commonly used to implement AES,ChaCha20,DES, but DES is considered to be insecure; Asymmetric encryption algorithm to achieve RSA, ECC

12. HTTPS handshake process? Why should asymmetric encryption be used for key transfer? Two-way authentication understand?

The HTTPS handshake flow is shown below, taken from the diagram HTTP

  • 1: The Client sends a Client Hello packet to start SSL communication. The packet contains the SSL version supported by the client and the list of encryption components.
  • 2: The Server responds with a Server Hello packet. Like the client, the packet contains the SSL version supported by the client and a list of encryption components. The server’s encryption component content is filtered from the received client encryption component
  • 3: The server sends a Certificate packet. The message contains a public key certificate.
  • 4: The Server sends a Server Hello Done packet to notify the client that the INITIAL SSL handshake negotiation is complete
  • 5: After the first SSL handshake, the Client uses the Client Key Exchange packet as the conference. The packet contains a random password string called pre-master secret, which is used in communication encryption
  • 6: The client sends a Change Cipher Space packet. The packet prompts the server that the communication after the second packet is encrypted with the pre-master secret key
  • 7: The client sends a Finished packet. The packet contains the overall checksum of all packets linked so far. The success of the handshake negotiation depends on whether the server can disclose the text correctly
  • 8: The server also sends a Change Cipher Space packet.
  • 9: The server also sends a Finished packet.
  • 10: After exchanging Finished packets between the server and client, the SSL connection is established and HTTP communication starts. All communication contents are encrypted using pre-master Secret. Then start sending the HTTP request
  • 11: The application layer sends an HTTP response after receiving an HTTP request
  • 12: A client disconnects at last

Why should asymmetric encryption be used for key transfer?

Asymmetric encryption is used for the security of the pre-master secret key generated by the client. It can be seen from the above steps that the step of the server sending the public key certificate to the client may be intercepted by others. If symmetric encryption is used, When the client sends the pre-master secret to the server, if it is intercepted by a hacker, the secret key can be decoded using the public key, and the security of the pre-master secret key cannot be guaranteed

Two-way authentication understand?

The HTTPS communication process only verify the server’s identity, and the server did not verify the identity of the client, two-way authentication is the service side is also to ensure the identity of the client, probably process is the client in after checking the server’s certificate, will send your public key to the server, and then generate a new key is encrypted with the public key of a service, to the client, The client then decrypts it with the private key, which is then used for symmetrically encrypted communication

13. How to use Charles to capture HTTPS packet? What are the principles and processes?

Process:

  • Start by installing the Charles certificate on your phone
  • Enable SSL Proxying in proxy Settings
  • Then add the address of the server to be captured

Principle:

Charles acts as a middleman, masquerading as a server to the client and as a client to the server. In a nutshell:

  • Intercepts THE HTTPS request from the client and sends the REQUEST to the server disguised as a middleman client
  • The receiving server returns and sends the data content to the client disguised as a man-in-the-middle server with its own certificate.

The detailed process is as follows: Describe HTTPS unidirectional authentication, bidirectional authentication, packet capture principle, and anti-packet capture policy

14. What is a man-in-the-middle attack? How to avoid it?

A man-in-the-middle attack is a man-in-the-middle attack that intercepts client requests and server responses. For example, Charles captures HTTPS packets.

Avoid: The client can pre-bury the certificate locally and then compare the certificate to see if it is a match

15. Do you understand the compilation process? What are the steps?

1: precompilation: Mainly deals with precompiled instructions starting with “#”.

2: compile:

  • Lexical analysis: The division of character sequences into a series of tokens.
  • Parsing: Generates a syntax tree based on parsing generated tokens.
  • Semantic analysis: analyzing the semantics of the syntax tree, matching, converting, identifying and so on.
  • Intermediate code generation: The source-level optimizer converts the syntax tree into intermediate code and performs source-level optimizations, such as 1+2 to 3. Intermediate code makes compilers divided into front end and back end. Different platforms can use different compiler back end to convert intermediate code into machine code to achieve cross-platform.
  • Object code generation: The subsequent process is at the back end of the compiler. The code generator converts intermediate code into object code (assembly code), which is then optimized by the object code optimizer, such as adjusting addressing, using displacement instead of multiplication, removing redundant instructions, adjusting instruction order, and so on.

3: Assembly: The assembler converts assembly code into machine instructions.

  • Static linking: The linker links together object files that have been compiled into machine instructions and relocates them to output an executable file.
  • Load: Loads the executable and the shared objects it depends on.
  • Dynamic linking: The dynamic linker corrects the locations in executable files and shared objects that need to be relocated.
  • Finally, control of the process is transferred to the program entry, and the program is finally running.

16. Static links? What is the difference between static and dynamic libraries?

  • Static linking is the merging of multiple object files into a single executable, which intuitively feels like merging segments of all object files. It should be noted that the structure of the executable file is basically the same as that of the object file, the difference is whether it is “executable”.
  • Static library: complete copy to executable file when linking, multiple use of multiple redundant copies.
  • Dynamic library: link does not copy, program run by the system dynamically loaded into memory, for program call, the system only loaded once, multiple programs shared, saving memory.

17. What are the optimization strategies for App network layer?

  • Optimize DNS resolution and caching
  • Compress the transmitted data to reduce the transmitted data
  • Use caching to reduce the number of requests
  • Use strategies to reduce the number of requests made, such as not making new requests until the last one has hit the ground
  • Avoid network jitter and provide retransmission mechanism

18: [self class] and [super Class]

@implementation Son : Father
- (id)init
{
    self = [super init];
    if (self)
    {
        NSLog(@"%@", NSStringFromClass([self class]));
        NSLog(@"%@", NSStringFromClass([super class]));
    }
return self;
}
@end
Copy the code

Difference between self and super:

  • selfIs a hidden argument of the class. The first argument of each method implementation isself.
  • Instead of hiding arguments, super is really just a ** “compiler identifier” **, which tells the compiler that when a method is called, to call the method of the parent class instead of the method in this class.

When calling [super Class], the Runtime will call objc_msgSendSuper instead of objc_msgSend

OBJC_EXPORT void objc_msgSendSuper(void /* struct objc_super *super, SEL op, ... */ ) /// Specifies the superclass of an instance. struct objc_super { /// Specifies an instance of a class. __unsafe_unretained id receiver; /// Specifies the particular superclass of the instance to message. #if ! defined(__cplusplus) && ! __OBJC2__ /* For compatibility with old objc-runtime.h header */ __unsafe_unretained Class class; #else __unsafe_unretained Class super_class; #endif /* super_class is the first class to search */ }Copy the code

In the objc_msgSendSuper method, the first argument is an objc_super structure that has two variables, the receiver for the message and the super_class, the parent of the current class.

That’s why the first question on the admission exam was wrong. Mistaken[super class]Is called[super_class class].

objc_msgSendSuperIt should work like this:

  • fromobjc_superThe structure points tosuperClassThe list of methods in the parent class starts looking for selector,
  • Found inobjc->receiverTo call this one in the parent classselector. Notice that the last caller isobjc->receiverRather thansuper_class!

thenobjc_msgSendSuperAnd then finally, it turns into theta

objc_msgSend(objc_super->receiver, @selector(class))
 
+ (Class)class {
    return self;
}
Copy the code

18. IsKindOfClass and isMemberOfClass

What does the following code output?

@interface Sark : NSObject
 @end
 
 @implementation Sark
 @end
 
 int main(int argc, const char * argv[]) {
@autoreleasepool {
    BOOL res1 = [(id)[NSObject class] isKindOfClass:[NSObject class]];
    BOOL res2 = [(id)[NSObject class] isMemberOfClass:[NSObject class]];
    BOOL res3 = [(id)[Sark class] isKindOfClass:[Sark class]];
    BOOL res4 = [(id)[Sark class] isMemberOfClass:[Sark class]];
 
   NSLog(@"%d %d %d %d", res1, res2, res3, res4);
}
return 0;
}
Copy the code

First to analyze the source code of the two functions of the object

+ (Class)class { return self; } - (Class)class { return object_getClass(self); } Class object_getClass(id obj) { if (obj) return obj->getIsa(); else return Nil; } inline Class objc_object::getIsa() { if (isTaggedPointer()) { uintptr_t slot = ((uintptr_t)this >> TAG_SLOT_SHIFT) & TAG_SLOT_MASK; return objc_tag_classes[slot]; } return ISA(); } inline Class objc_object::ISA() { assert(! isTaggedPointer()); return (Class)(isa.bits & ISA_MASK); } + (BOOL)isKindOfClass:(Class)cls { for (Class tcls = object_getClass((id)self); tcls; tcls = tcls->superclass) { if (tcls == cls) return YES; } return NO; } - (BOOL)isKindOfClass:(Class)cls { for (Class tcls = [self class]; tcls; tcls = tcls->superclass) { if (tcls == cls) return YES; } return NO; } + (BOOL)isMemberOfClass:(Class)cls { return object_getClass((id)self) == cls; } - (BOOL)isMemberOfClass:(Class)cls { return [self class] == cls; }Copy the code

First, NSObject and Sark call the class method, respectively.

  • + (BOOL)isKindOfClass:(Class)clsInside the method, it will get firstobject_getClassClass, andobject_getClassTo call the current classobj->getIsa()And finally theISA()Obtained from the methodmeta classThe pointer.
  • Then, inisKindOfClassThere is a loop inclassWhether is equal to themeta class, and continue the loop to determine whether it equalssuper classDon’t wait to continue to takesuper classAnd so on.

  • [NSObject class]Called after executionisKindOfClassFirst judge first judgeNSObject 和 NSObjectthemeta classWhether it’s the same or notmeta classI put a very detailed picture on it, and as you can see from the picture,NSObjectthemeta classNot equal to itself.
  • And then the second loopNSObjectwithmeta classthesuperclassIs it equal? Again, we can see from the picture:Root class(meta) 的superclassisRoot class(class), that is,NSObjectItself. So the second cycle is the same, so the first rowres1The output should beYES.
  • In the same way,[Sark class]Called after executionisKindOfClassThe first time,forCycle,SarktheMeta Classwith[Sark class]No, second timeThe for loop.Sark Super Class of Meta ClassPoints to theNSObject Meta Class, andSark ClassIs not equal.
  • The third for loop,NSObject Meta Classthesuper classPoints to theNSObject Class, andSark ClassIs not equal. The fourth cycle,NSObject Classthesuper classPoint to thenil, andSark ClassIs not equal. After the fourth loop, it exits the loop, so the third rowRes3 output is NO.
  • If I change Sark here to its instance object,[sark isKindOfClass:[Sark class], then it should outputYES. Because in theisKindOfClassFunction to determine sarkmeta classIs its own metaclassSarkThe first for loop outputsYES.
  • isMemberOfClassThe source code implementation is to get your ownIsa pointerCompare it with yourself.
  • The second lineisaPoint to theNSObject 的 Meta Class, so,NSObject ClassIs not equal. In the fourth row,isaPoint to theSarktheMeta Class, andSark ClassIt’s not equal. So row 2res2And the fourth rowres4All output NO.

Class and memory address

The following code will?Compile Error/Runtime Crash/NSLog... ?

@interface Sark : NSObject
@property (nonatomic, copy) NSString *name;
- (void)speak;
@end
@implementation Sark
- (void)speak {
    NSLog(@"my name's %@", self.name);
}
@end
@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    id cls = [Sark class];
    void *obj = &cls;
    [(__bridge id)obj speak];
}
@end
Copy the code

There are two difficulties in this problem.

  • The difficulties in a:objcallspeakMethod, whether or not it will crash.
  • Difficulty two: ifspeakWhat should be output if the method does not crash?

First, we need to talk about hiding the arguments self and _cmd. When the [Receiver Message] method is called, the system surreptitiously passes in two hidden arguments, self and _cmd, dynamically at run time. These are called hidden arguments because they are not declared and defined in the source code. Self already knows that, so let’s talk about _cmd. _cmd represents the currently invoked method, which is essentially a method selector SEL.

  • Difficulty one, can callspeakMethods?
id cls = [Sark class]; 
void *obj = &cls;
Copy the code

The answer is yes. Obj is converted to a pointer to Sark Class and then converted to the objc_Object type using id. Obj is now an instance object of type Sark. Of course you can call the speak method next.

  • Difficulty two, if you can callspeakAnd what does it output?

Many people might expect sarK-related information to be printed. That’s the wrong answer.

The correct answer is printed

my name is <ViewController: 0x7ff6d9f31c50>

The memory address is different every time you run it, but it must be the ViewController. According to?

Let’s change the code to print out more information.

- (void)viewDidLoad { [super viewDidLoad]; NSLog(@"ViewController = %@, address = %p", self, &self); id cls = [Sark class]; NSLog(@"Sark class = %@ address = %p", CLS, &cls); void *obj = &cls; NSLog(@"Void *obj = %@ address = %p", obj,&obj); [(__bridge id)obj speak]; Sark *sark = [[Sark alloc]init]; NSLog(@"Sark instance = %@ address = %p", Sark,&sark); [sark speak]; }Copy the code

We print out the address of the pointer to the object. Output result:

ViewController = <ViewController: 0x7fb570e2ad00>, address = 0x7ffF543f5aa8 Sark class = Sark address = 0x7ffF543f5a88 Void *obj = <Sark: 0x7ffF543f5a88 > address = 0x7ffF543f5a80 My name is <ViewController: 0x7FB570e2ad00 > Sark instance = 0x7FB570D20B10 > address = 0x7ffF543f5a78 My name is (null)Copy the code

Objc_msgSendSuper2 interpretation

// objc_msgSendSuper2() takes the current search class, not its superclass.
OBJC_EXPORT id objc_msgSendSuper2(struct objc_super *super, SEL op, ...)
    __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_2_0);
Copy the code

The objc_msgSendSuper2 method entry is an objc_super *super.

/// Specifies the superclass of an instance. struct objc_super { /// Specifies an instance of a class. __unsafe_unretained id receiver; /// Specifies the particular superclass of the instance to message. #if ! defined(__cplusplus) && ! __OBJC2__ /* For compatibility with old objc-runtime.h header */ __unsafe_unretained Class class; #else __unsafe_unretained Class super_class; #endif /* super_class is the first class to search */ }; #endifCopy the code

So when you do viewDidLoad, the variables are pushed from top to bottom self, _cmd, self.class, self, obj.

  • The first oneselfAnd the second_cmdIs a hidden parameter.
  • The thirdself.classAnd the fourthselfis[super viewDidLoad]Method at execution time.
  • In the callself.nameIs, in essenceselfPointer Offsets a pointer to a higher address in memory. Under 32 bits, oneA pointer is 4 bytes =4*8bit=32bit.(64-bit is different but the idea is the same)
  • And as we can see from the print,objisclsThe address. inobjUpward migration32bitit0x7fff543f5aa8This happens to beViewControllerThe address.

So the output is my name is<ViewController: 0x7fb570e2ad00>.

What exactly are objects in Objc at this point?

The object in Objc is a variable pointing to the address of ClassObject, id obj = &classobject, and the instance variable void *ivar = &obj + offset(N).

To clarify the above statement, what does this code output?

- (void)viewDidLoad { [super viewDidLoad]; NSLog(@"ViewController = %@, address = %p", self, &self); NSString *myName = @"halfrost"; id cls = [Sark class]; NSLog(@"Sark class = %@ address = %p", CLS, &cls); void *obj = &cls; NSLog(@"Void *obj = %@ address = %p", obj,&obj); [(__bridge id)obj speak]; Sark *sark = [[Sark alloc]init]; NSLog(@"Sark instance = %@ address = %p", Sark,&sark); [sark speak]; } ViewController = <ViewController: 0x7ffF44404AB0, address = 0x7ffF56a48a78 Sark class = Sark address = 0x7fff56a48a50 Void *obj = <Sark: 0x7ffF56a48a50 > address = 0x7fff56a48a48 My name is halfrost Sark instance = 0x6080000233E0 > address = 0x7ffF56a48a40 My Name is (null)Copy the code

[(__bridge ID)obj speak]; [(__bridge id)obj speak]; This sentence will output “My name is Halfrost”

Again, the reasons are similar. When executing viewDidLoad, the variables are pushed from top to bottom: self, _cmd, self.class, self, myName, obj. Obj is offset by 32 bits, which is the myName string, so the output becomes the output myName.

Bubble sort, select sort, insert sort, quick sort (two way, three way) can write what?

Here under the simple said the difference between several quick sort, random fast row, is orderly, in order to solve the approximate time complexity will degenerate into O (n ^ 2), dual fast row is in order to solve the quick sort in the case of a large amount of data repeat, time complexity will degenerate into O (n ^ 2), three way fast row is in a large amount of data under the condition of repetition, An optimization of double – channel fast row.

  • Bubble sort
extension Array where Element : Comparable{ public mutating func bubbleSort() { let count = self.count for i in 0.. <count { for j in 0.. <(count - 1 - i) { if self[j] > self[j + 1] { (self[j], self[j + 1]) = (self[j + 1], self[j]) } } } } }Copy the code
  • Selection sort
extension Array where Element : Comparable{ public mutating func selectionSort() { let count = self.count for i in 0.. <count { var minIndex = i for j in (i+1).. <count { if self[j] < self[minIndex] { minIndex = j } } (self[i], self[minIndex]) = (self[minIndex], self[i]) } } }Copy the code
  • Insertion sort
extension Array where Element : Comparable{ public mutating func insertionSort() { let count = self.count guard count > 1 else { return } for i in 1.. <count { var preIndex = i - 1 let currentValue = self[i] while preIndex >= 0 && currentValue < self[preIndex] { self[preIndex + 1] = self[preIndex] preIndex -= 1 } self[preIndex + 1] = currentValue } } }Copy the code
  • Quick sort
extension Array where Element : Comparable{
    public mutating func quickSort() {
        func quickSort(left:Int, right:Int) {
            guard left < right else { return }
            var i = left + 1,j = left
            let key = self[left]
            while i <= right {
                if self[i] < key {
                    j += 1
                    (self[i], self[j]) = (self[j], self[i])
                }
                i += 1
            }
            (self[left], self[j]) = (self[j], self[left])
            quickSort(left: j + 1, right: right)
            quickSort(left: left, right: j - 1)
        }
        quickSort(left: 0, right: self.count - 1)
    }
}
Copy the code
  • Random fast row
extension Array where Element : Comparable{ public mutating func quickSort1() { func quickSort(left:Int, right:Int) { guard left < right else { return } let randomIndex = Int.random(in: left... right) (self[left], self[randomIndex]) = (self[randomIndex], self[left]) var i = left + 1,j = left let key = self[left] while i <= right { if self[i] < key { j += 1 (self[i], self[j]) = (self[j], self[i]) } i += 1 } (self[left], self[j]) = (self[j], self[left]) quickSort(left: j + 1, right: right) quickSort(left: left, right: j - 1) } quickSort(left: 0, right: self.count - 1) } }Copy the code
  • Dual fast row
extension Array where Element : Comparable{ public mutating func quickSort2() { func quickSort(left:Int, right:Int) { guard left < right else { return } let randomIndex = Int.random(in: left... right) (self[left], self[randomIndex]) = (self[randomIndex], self[left]) var l = left + 1, r = right let key = self[left] while true { while l <= r && self[l] < key { l += 1 } while l < r && key < self[r]{ r -= 1 } if l > r { break } (self[l], self[r]) = (self[r], self[l]) l += 1 r -= 1 } (self[r], self[left]) = (self[left], self[r]) quickSort(left: r + 1, right: right) quickSort(left: left, right: r - 1) } quickSort(left: 0, right: self.count - 1) } }Copy the code
  • Three way fast row
// Extension Array where Element: Comparable{ public mutating func quickSort3() { func quickSort(left:Int, right:Int) { guard left < right else { return } let randomIndex = Int.random(in: left... right) (self[left], self[randomIndex]) = (self[randomIndex], self[left]) var lt = left, gt = right var i = left + 1 let key = self[left] while i <= gt { if self[i] == key { i += 1 }else if self[i] < key{ (self[i], self[lt + 1]) = (self[lt + 1], self[i]) lt += 1 i += 1 }else { (self[i], self[gt]) = (self[gt], self[i]) gt -= 1 } } (self[left], self[lt]) = (self[lt], self[left]) quickSort(left: gt + 1, right: right) quickSort(left: left, right: lt - 1) } quickSort(left: 0, right: self.count - 1) } }Copy the code

21. Encryption methods in iOS development

IOS encryption-related algorithm framework: CommonCrypto.

1: symmetric encryption:DES, 3DES, AES

  • Encryption and decryption use the same key.

  • Encryption and decryption process:

    • Plaintext -> key encryption -> ciphertext.
    • Ciphertext -> Key decryption -> plaintext.
  • Advantages: open algorithm, less computation, fast encryption speed, high encryption efficiency, suitable for mass data encryption;

  • Disadvantages: The two parties use the same key. The key transmission process is insecure and easy to crack. Therefore, the key needs to be changed frequently to keep it secret.

AES: The Advanced Encryption Standard (AES) is the next generation encryption algorithm standard. It supports encryption with 128, 192, and 256-bit keys. The encryption and decryption keys are the same. IOS generally uses ECB mode with 16-byte 128-bit key.

AES algorithm mainly includes three aspects: round change, turn number and key expansion.

  • Advantages: High performance, high efficiency, flexible and easy to use, high security level.
  • Disadvantages: Encryption and decryption of the same key, so the use of AES encryption, how to safely save the key becomes a problem.

DES: indicates the Data encryption standard. The entry parameters of the DES algorithm are Key, Data, and Mode.

  • Key is the working Key of the DES algorithm, consisting of 7 bytes and 56 bits. Data is 8 bytes and 64 bits, which is the Data to be encrypted or decrypted. Mode Indicates the working Mode of DES, including encryption and decryption.
  • Disadvantages: Less security than AES.

3DES: 3DES is a mode of the DES encryption algorithm. It uses three 64-bit keys to encrypt data for three times. DES is the encryption algorithm to AES transition, is a more secure transformation of DES. It takes DES as the basic module and designs a packet encryption algorithm by combinatorial packet method.

Asymmetric encryption :RSA encryption

  • Asymmetric encryption algorithms require two keys in pairs, public keys (publickey) and private keys (privatekey).
  • ** Encryption and decryption process: ** For a private key, there is only one corresponding public key. The generator is responsible for generating the private and public keys, saving the private keys, and publicizing the public keys.

Public key encryption, private key decryption; Or private key digital signature, public key authentication. Public and private keys are paired and decrypt each other.

  • Features:

    • 1). ** Keeps information confidential to prevent the middle man attack: ** encrypts the plaintext through the receiver’s public key and transmits it to the receiver. Because only the receiver has the corresponding private key, others cannot have or calculate the private key through the public key, so the transmission process cannot be intercepted by the middle man. Only the recipient with the private key can read it. This method is typically used to exchange symmetric keys.
    • 2). * * authentication and prevent tampering with: * * permissions with its own private key to encrypt a dog license expressly, and will authorize plaintext and encrypted cryptograph, as well as the public key along with, the receiver will need only through the public key cipher decryption and authorization after clear contrast are consistent, can determine whether expressly on the way to be tampered with. This method is used for digital signatures.
  • ** Advantages: ** encryption strength is small, long encryption time, often used for digital signature and encryption key, very high security, to solve the security problem of symmetric encryption to save the key.

  • ** Disadvantages: ** encryption and decryption speed is much slower than symmetric encryption, not suitable for mass data encryption.

3. Hash algorithm encryption:MD5 encryption,The SHA encryption,HMAC encryption

  • Hash algorithm encryption is used to encrypt data using the hash algorithm. The encrypted result is irreversible, that is, the encrypted data cannot be decrypted.
  • ** Features: ** irreversible, open algorithm, the same data encryption results.
  • ** Function: ** Information summary, information “fingerprint”, used to do data identification. For example, user password encryption, file verification, digital signature, and authentication protocol.

MD5 encryption: ** Encrypts different data to result in fixed-length 32-bit characters.

SHA encryption: ** Secure hash algorithm, mainly applicable to the digital signature algorithm (DSA) defined in the Digital Signature Standard (DSS). For messages less than 2^64 bits in length, SHA1 produces a 160-bit message digest. When a message is received, the message digest can be used to verify data integrity. As the data is likely to change during transmission, different message digests will be generated. Of course, there are SHA256 and SHA512 in addition to SHA1.

**HMAC encryption: ** Given a key, do two hashes on plaintext encryption, and the result is still a 32-bit string.

4. Base64 encryption

  • An encoding method that is not, strictly speaking, an encryption algorithm. Its function is to encode binary data into text, convenient network transmission.

  • Encoding in Base64 increases the length of the data by about a third, but the benefit is that the encoded data can be displayed directly in emails and web pages.

  • Although Base64 can be used as encryption, but base64 can be reversed, very insecure!

  • Base64 encoding has a very distinctive feature, the ‘=’ sign at the end.

  • Principle:

    • 1). Convert all characters to ASCII code;
    • 2). Convert ASCII code to 8-bit binary;
    • 3). Divide a group of binary three bits into a group of six bits for a total of four groups;
    • 4). Add two 0 to eight bits in front of the 6-bit binary;
    • 5). Convert the binary after the complement of 0 to decimal;
    • 6). Finally, Base64 encoding corresponding to decimal is obtained from Base64 encoding table.

22. App security, digital signature, App signature, re-signature

Because the application is actually a shell IPA file, but may be cracked or jailbroken phone download IPA package is directly unshell, can be directly decompiled, so do not store critical information in plist files, static files in the project. Therefore, sensitive information is stored symmetrically encrypted or stored in the keychain. And the encryption key should be changed regularly.

Digital signatures are implemented using HASH algorithms and RSA encryption. We send the plaintext data to the other party together with the HASH value ** encrypted by RSA. The other party can decrypt the data and take out the HASH value for verification. This encrypts HASH data using RSA and is called a digital signature.

App signature

  • 1. Generate a pair of public key and private key on the Mac development machine. This pair is called public key L and private key L(L: Local).
  • 2. Apple has a fixed pair of public and private keys. The private key is in the Apple background, and the public key is on each iOS device. Public key A and private key A(A: Apple).
  • 3. Upload public key L from the development machine to the Apple background and use the private key A of the Apple background to sign public key L. Get a certificate that contains the public key L and its signed data.
  • 4. Apply for an AppID on the apple background and configure itDevice ID ListandPermissions that the APP can usePlus step 3certificate, composed of data usedThe private key is ASignature, the data and signature together to form aProvisioning ProfileDescription file, download toLocal Mac development machine.
  • 5. During development, after compiling an APP, useLocal private key LSign the APP and add step 4 to theProvisioning ProfileThe description file is packaged into the APP. It’s calledembedded.mobileprovisionInstall the APP on your phone.
  • 6. During the installation, the iOS system obtains the certificate and passesBuilt-in public key ATo verify theembedded.mobileprovisiontheA digital signatureIf it is correct, the certificate signature will be checked again.
  • 7. Make sureembedded.mobileprovisionThe data are apple authorized after, can take out the data inside, do all kinds of verification, including with public key L verify APP signature, verify device ID is on ID list, AppID is on due, Entitlements switch/with APP corresponding.

OC data type

① Basic data types

  • C basic data types (such as short, int, float, etc.) are not objects in OC, but a certain amount of memory space for storing values. They do not have the characteristics of objects, and no attribute methods can be called.

  • Basic data types in OC:

    • NSInteger(equivalent to long integer),
    • NSUInteger(equivalent to an unsigned long integer),
    • CGFloatDouble on 64-bit systems, float on 32-bit systems, etc.
    • They are not classes, they just usetypedefBasic data types have been redefined,They are still basic data types.
    • ** Enumeration types: ** are essentially unsigned integers.
    • **BOOL type: ** is the macro definition, OC is the underlying signed char to represent BOOL.

② Pointer data type

Pointer data types include class and ID.

  • Class class: NSString,NSSet,NSArray,NSMutableArray,NSDictionary,NSMutableDictionary,NSValue,NSNumber (inherit NSValue)And so on, are class, after creation is object, inheritanceNSObject.

OC provides NSValues and NSNumbers to encapsulate basic C types so that we can make them object-oriented.

  • Id: idIs a pointer to an Objective-C object, equivalent to Cvoid*, can map any object pointer to it, or map it to any other object. A common id type is the delegate property of a class.

Set NSSet differs from array NSArray:

  • Both store addresses of different objects;
  • But ns sarray is an ordered set, NSSet is an unordered set, and they can be converted to each other.
  • NSSet automatically removes duplicate elements.
  • A set is a hash table that uses a hash algorithm to find elements in a set faster than an array, but it has no order.

③ Tectonic type

** Construction types include: ** structure, commonwealth

  • Structure: structTo combine variables of multiple basic data types into a whole. Internal members of a structure are accessed using the dot operator.
  • Union (common body) : unionThere are some similar structuresstructA data structure of a consortium (union) and structures (struct) can also contain many data types and variables.

The difference between a structure and a union:

  • All variables in a struct are “coexisting”; each member has a value at the same time, and sizeof is the sum of all members.

    ** advantages: ** is “tolerant”, comprehensive;

    ** Disadvantages: ** is a struct memory space allocation is extensive, regardless of use, all

Allocation, will cause memory waste.

  • Variables in a union are mutually exclusive. Only one member has a value at a time, and its sizeof is the sizeof the longest member.

    ** Advantages: ** is more precise and flexible memory use, but also save memory space.

    ** Disadvantages: ** is not “inclusive” enough, modify one member will overwrite the original member value;

24. Property and attribute modifiers

The essence of @property is ivAR + setter + getter.

What happens internally each time we add an attribute:

  • 1. The system will be thereivar_listAdd a description of a member variable to
  • In 2.method_listaddsetter 与 getterDescription of the method;
  • 3. Add an attribute description to the attribute list.
  • 4. Calculate the offset of the property in the object.
  • Given 5.setter 与 getterMethod corresponding to the implementation, insetterMethod from the position of the offset, ingetterMethod to start at the offset. The pointer type of the system object’s offset is typed strong so that the correct number of bytes can be read.

Decorator:

  • MRC:  Assign, retain, Copy, ReadWrite, ReadOnly, Nonatomic, atomicAnd so on.
  • The ARC under: Assign, strong, weak, Copy, ReadWrite, ReadOnly, Nonatomic, Atomic, NonNULL, NULlable, NULl_RESETTable, and _Null_unspecifiedAnd so on.

Here are the explanations

  • assign: for basic data types, without changing the reference count. If you modify objects (objects are freed manually in the heap, primitive data types are freed automatically in the stack system), you will result in wild Pointers that are not set to nil after the object is freed.
  • retainAs with strong, the old object is released, and the reference count of the new object passed in is +1. It comes in pairs with release in MRC.
  • strong: used in ARC, telling the system to leave the object on the heap until there are no Pointers to it and ARC does not need to worry about reference counting, the system will release it automatically.
  • weak: Keep the reference count as long as possible until it is strongly referenced. Weak reference is a weak reference, you don’t own it; It essentially allocates an unheld property, and when the referrer is destroyed (dealloc), the weak reference pointer is automatically set to nil.Circular references can be avoided.
  • copy: is commonly used to modify immutable type attribute fields, such as:NSString,NSArray,NSDictionaryAnd so on. The copy modifier protects the object property from external influencesNSMutableStringAssigned toNSString, changing the former causes the value of the latter to change accordingly. There areblockThe copy modifier is often used, but in ARC the compiler automatically copies blocks, which has the same effect as strong. But in MRC, the block inside the method is in the stack, and you can use copy to put it in the heap.
  • readwrite: Can read and write; The compiler automatically generates setter/getter methods.
  • readonly: read only; Tells the compiler not to automatically generate setter methods. Attribute cannot be assigned.
  • nonatomic: non-atomic access. Using nonatomic means that variables can be accessed by multiple threads, making the reader thread unsafe. But it improves execution performance.
  • atomic: Atomic access. The compiler automatically generates mutex locks for setter and getter methods to ensure thread-safe property assignment and atomicity operations, but not mutable property operations and access. For example, it is not atomic’s responsibility to add or remove objects from an array, so adding or removing objects from an atomic array is not thread-safe.The disadvantage of atomic access is that it can consume performance and result in slow execution.
  • nonnull: Setting property or method parameters cannot be null, used specifically to modify Pointers, and cannot be used for primitive data types.
  • nullable: Setting property or method parameters can be null.
  • null_resettableGet cannot return null. Set can be assigned to null.
  • _Null_unspecified: Sets the property or method parameter to be null.

The last four attributes should mainly be used to improve the development specification, indicating what values should be passed by the user, and warning if the specification values are violated.

Weak is automatically set to nil when the weak object is released.

The Runtime maintains a weak table that stores all the weak Pointers to an object. The weak table is a hash table where Key is the address of the object and Value is the address array of the weak pointer (the address Value is the address of the object).

The implementation principle of weak can be summarized in three steps:

  • 1. Initialization:runtimeWill be calledobjc_initWeakThe weak function initializes a new weak pointer to the address of the object.
  • 2. Add a reference:objc_initWeakThe function will callobjc_storeWeak()The function,objc_storeWeak()Update pointer pointer to create the corresponding weak reference table.
  • 3, release when calledclearDeallocatingFunction.clearDeallocatingThe function first retrieves all objects based on their addressweakArray of pointer addresses, and then iterate through that array and set the data in that array tonilFinally, delete the entry from the weak table, and clear the record of the object.

25. Member variablesivarAnd attributespropertyAnd the role of different keywords

** Member variables: The default modifiers for ** member variables are @protected. Set and GET methods are not generated automatically. They need to be implemented manually.

** attributes: The ** attributes generate underlined member variables and setter/getter methods by default. They can be called using dot syntax, but actually call set and get methods.

Note: Attributes added to categories are not automatically generatedsetter/getterMethod must be added manually.

** Instance variable: **class to instantiate the object is the instance object keyword:

  • Access scope keyword
  • @public: declares public instance variables that can be accessed directly from anywhere.
  • @private: declares private instance variables that can only be accessed directly in the object methods of the current class. Subclasses need to call the get/set methods of their parent class to access them.
  • @protected: can be accessed directly in the object methods of the current class and its subclasses (system default).
  • @package: Can be accessed directly under the same package, such as within the same framework.
  • The keyword
  • @propertyProperty declaration: automatically generates a member variable _propertyName(modified with @private by default) starting with an underscore, declaration of property setter and getter methods, and implementation of property setter and getter methods. ** Note: ** in@ agreement protocolOnly declarations of getter and setter methods are generated in, so you need to manually implement getter and setter methods as well as manually define variables.
  • @sythesize: Change the name of the _propertyName member variable automatically generated by @property,@synthesize propertyName = newName;.
  • @dynamic: tells the compiler that setter and getter methods for a property are implemented by the user and not automatically generated. ** Use caution: ** If you assign a value to a property, it will compile successfully, but if you run it, the program will crash. This is often referred to as dynamic binding.
  • @interfaceClass: statement
  • @implementation: class implementation
  • @selecterCreate an SEL, class member pointer
  • @protocol: Declaration agreement
  • @autoreleasepool: Automatic release pool in ARC
  • @end: the end of the class

26. The class cluster

Class clustering is a widely used design pattern in the Foundation framework. A class cluster groups private concrete subclasses under a common abstract superclass. Grouping classes in this way simplifies the common visible architecture of an object-oriented framework without reducing its functionality richness. Class clusters are based on abstract factory design patterns.

Common class clusters are NSString, NSArray, NSDictionary, etc. ** The class after alloc is __NSPlaceholderArray regardless of whether the host is an immutable or an immutable array. When we init an immutable empty array, we get __NSArray0; If there is one and only one element, it is __NSSingleObjectArrayI; Those with more than one element are called __NSArrayI; Init produces a mutable array, all __NSArrayM.

Advantages:

  • You can hide the complex details behind the abstract base class.
  • Programmers don’t have to remember various concrete class implementations to create objects, simplifying development costs and improving development efficiency.
  • Facilitate encapsulation and componentization.
  • Reduced extensibility code like if-else.
  • Adding new functionality does not affect other code.

Disadvantages:

  • Existing class clusters are very difficult to extend.

The scenario where we apply class clusters:

    1. When a bug occurs, you can quickly locate the bug by using the class cluster keyword in the crash report.
    1. When implementing something that is fixed and does not require constant modification, you can efficiently choose a class cluster to implement it. Ex. :
      • For different versions and models, you can choose to use class clusters.
      • The Settings page of the app, which does not need to be modified very often, can use class clusters to create a lot of repetitive layout code.

27. Design patterns

Create mode:

  • ** Singleton pattern: ** One resource is shared throughout the application. Ensure that during program running, a class has only one instance, and the instance provides only one global access point for external access, so as to conveniently control the number of instances and save system resources.

    ** advantages: ** provides controlled access to a unique instance, is extensible, and avoids the performance impact of frequent creation and destruction of objects.

    The disadvantages of ** are: ** extends the declaration cycle, has been occupying memory. If two singleton loop dependencies can cause deadlocks, try not to create dependencies between singletons.

  • ** Factory method pattern: ** Creates an abstract product through class inheritance, creates a product, subclasses the creator and overrides the factory method to create a new product.

  • ** Abstract Factory pattern: ** To create abstract products through object composition, multiple family products can be created, and the interface of the parent class must be modified to support new products.

Structural mode:

  • ** proxy mode: The ** proxy is used to handle event listening and parameter passing.@requiredThe modifier must implement the protocol method method,@optionalEmbellishment is an optional implementation. When using a method, it is best to determine whether the method is implementedrespondsToSelector: “, to avoid finding a way to crash.

The advantages and disadvantages of **delegate, block, and Notification are as follows: ** Delegate and Block communicate one-to-one, and block is simpler and clearer than delegate. However, if there are too many communication events, the running cost of the delegate is lower and it is not easy to cause circular references. Notice is suitable for one-to-many communication, the code is clear and simple, but it is difficult to find the source of the problem, and the registered notice should be removed at the appropriate time to avoid sending messages to wild Pointers and causing crashes (** Note: **iOS9 uses __unsafe_unretained references as a reminder of what happened across different versions.

  • ** Class cluster: ** see above
  • Decorator mode: dynamically extends the functionality of an object without changing the original class files and using inheritance. Such as: classification.
  • ** Share mode: Use shared objects to reduce the number of objects created in the same class. For example: **UITableviewCell reuse.

Behavioral patterns:

  • ** Observer model: ** is essentially aPublish-subscribeA model used to remove coupling between objects with different behaviors through which different objects can work together. Such as:KVO.
  • Command mode:Is a design pattern that encapsulates method calls as objects, implemented in iOS asNSInvocation. Below forNSInvocationThe implementation code.
- (void)viewDidLoad { NSMethodSignature *signature = [ViewController instanceMethodSignatureForSelector:@selector(sendMessageWithPhone:WithName:)]; A method signature; / / to get the method return type and parameter types NSInvocation * invocation = [NSInvocation invocationWithMethodSignature: signature]; invocation.target = self; / / target: receiving a message object invocation. The selector = @ the selector (sendMessageWithPhone: WithName:); // Selector: the method to be sent must be the same as the method in the signature. NSString *phone = @"13512345678"; // Note: The invocation cannot start from 0 because 0 is used by self and 1 is used by _cmd. // Parameters: You can add any number of parameters. NSString *name = @"Dezi"; [invocation setArgument:&name atIndex:3]; /* Invocation invoke (NSInvocation invocation) will invoke the invocation from the NSInvocation object and pass the invocation argument */ [Invocation invoke]; } - (void)sendMessageWithPhone:(NSString*)phone WithName:(NSString*)name {NSLog(@" phone number =%@, name =%@",phone, name); } // Phone number =13512345678, name DeziCopy the code
  • MVC and MVVM are architectures.
28. Architecture design

* * the MVC:

  • M is the data Model, which is responsible for processing data and sending Notification (Notification, KVO) when data changes. Model and View cannot communicate directly, which will violate the MVC design pattern.

  • V is a View View, which is used to display the interface and interact with the user. In order to understand the coupling, the data model in the data layer will not be directly held or operated (it can be decoupled through action-target, delegate, block, etc.).

  • C is the Controller Controller used to adjust the interaction between Model and View. It can directly communicate with Model and View, operate Model to update data and refresh View.

    Advantages: View, Model low coupling, high reuse, easy maintenance.

    Disadvantages: The code of Controller is too bloated. Direct interaction between View and Model will lead to large coupling between View and Model, and network logic will aggravate the bloat of Controller.

MVVM: model-view-viewModel

  • MVVMDerived fromMVCIs an evolution of MVC that promotes the separation and extraction of UI code and business logicControllerThe display logic inViewModelThe inside.
  • M:The data modelModel.
  • V:isViewandControllerTogether as a componentView. Neither View nor Controller can refer directly to the Model. Instead, it can refer to the ViewModel. The ViewController tries not to involve the business logic and lets the ViewModel do the work. The ViewController is just a middleman who receives events from the View, calls methods from the ViewModel, and responds to changes to the ViewModel.
  • VM: ViewModelResponsible for encapsulating business logic, network processing and data caching. Using the ViewModel slightly increases the amount of code, but overall reduces the complexity of the code.ViewModelThere can be dependencies.

Matters needing attention:

  • ViewreferenceViewModel, but not the other way around, because if VM is coupled to V, it is not easy to reuse. Is not inviewModelThe introduction of#import UIKit.hAny reference to the view itself should not be placedviewModel(Note: Basic requirements must be met).
  • ViewModelYou can referenceModelBut not the other way around.

Advantages:

Low coupling, reusable, clear data flow, and COMPATIBLE with MVC, easy to transplant code, and ViewModel can be detached from independent development, convenient testing.

Disadvantages: More classes, larger viewModels, more complex calls, and bidirectional binding of data can make problem debugging difficult.

Conclusion:

  • MVVMIt’s actually a variant of MVC.MVVMJust trying to helpMVCIn theControllerSlim down and separate some logical code from network requests. Don’t let the Controller handle more stuff, don’t get bloated,MVVMandMVCFlexible selection can be made based on actual requirements.
  • MVVMIn use, bidirectional binding technology is often used to makeModelChanges,ViewModelWill automatically update, andViewModelChanges,ViewIt also changes automatically. Reactive programming can be implemented in OC using the **RAC(ReactiveCocoa)** functional reactive framework.

29. Application, advantages and disadvantages of ReactiveCocoa

ReactiveCocoa, RAC for short, is a functional responsive programming framework because it has the characteristics of both functional and responsive programming.

  • Because the framework programming ideas, it has a charm of function, it can realize the traditional design patterns, and event listeners can realize the function, such as KVO, notification, block the callback, the action, agreement, etc., it isn’t it the most superior characteristics of comprehensive, RAC most worth showing off, it provides a unified messaging system, This mechanism makes its code more concise, less code blocks of the same function, which is exactly in line with our programming ideas: high aggregation, low coupling, it is very suitable for the development of MVVM design pattern.
  • It’s not a complete replacement for traditional coding, however, and RAC still presents some headaches when it comes to multiplayer development and code maintenance.

** Advantages: ** is flexible and convenient to use, simple code, clear logic

** Disadvantages: ** high maintenance cost, difficult problem tracing

Use:

RAC’s unified messaging mechanism requires signals (SIGAL) for all actions.

  • 1). Signal creation, sending and receiving
// Create a cold signal, RACSignal *signal = [RACSignal createSignal:^RACDisposable *(id<RACSubscribersubscriber) {// Send signal [subscriber SendNext :@"oh my God "]; Return [RACDisposable disposableWithBlock:^{NSLog(@" Signal completed ");}];}]; // Signal subscribeNext:^(id x) {NSLog(@"singalContent:%@", x);}];Copy the code
  • 2). The RAC ControlEventsThis method can easily implement the listening operation, and the logic behind itblock, and can also add gestures and listen.
[[self.textField rac_signalForControlEvents:UIControlEventEditingDidBegin] subscribeNext:^(id x) {  
    NSLog(@"%@", x);  
}];  

UITapGestureRecognizer *tap = [UITapGestureRecognizer new];  
[[tap rac_gestureSignal] subscribeNext:^(id x) {  
    NSLog(@"three:%@", x);  
}];  
[self.view addGestureRecognizer:tap];  
Copy the code
  • 3.) the RAC KVO
[[self.textField rac_valuesAndChangesForKeyPath:@"text" options:NSKeyValueObservingOptionNew observer:self] subscribeNext:^(id x) {  
    NSLog(@"%@", x);  
}];  
Copy the code
  • 4). Notice of RAC
[[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIKeyboardDidShowNotification object:nil] SubscribeNext :^(id x) {NSLog(@" keyboard ");}];Copy the code
  • 5). RAC agreement
- (void)viewDidLoad { [super viewDidLoad]; Self.textfield. Delegate = self; [[self rac_signalForSelector:@selector(textFieldDidBeginEditing:) fromProtocol:@protocol(UITextFieldDelegate)] SubscribeNext: ^ (id) x {NSLog (@ "click to print information: % @", x);}]; } - (void) textFieldDidBeginEditing: (UITextField at *) textField {NSLog (@ "began to edit"); }Copy the code
  • 6). RAC traverses groups and dictionaries

Equivalent to enumeration traversal, but more efficient

NSArray *arr = @[@"1", @"2", @"3", @"4", @"5"];  
[arr.rac_sequence.signal subscribeNext:^(id x) {  
    NSLog(@"arr : %@", x);  
}];  
NSDictionary *dic = @{@"name":@"yangBo", @"age":@"19"};  
[dic.rac_sequence.signal subscribeNext:^(id x) {  
    NSLog(@"dic : %@", x);  
}];  
Copy the code
  • 7). RAC signal processing (MAP, Filter, Combine)

① Do not process the signal

[[self.textField rac_textSignal] subscribeNext:^(id x) {  
    NSLog(@"doNothing:%@", x);  
}];  
Copy the code

② Filter the signal to determine whether to process the signal condition.

[[[self.textField rac_textSignal] filter:^BOOL(NSString* value) { if (value.length 3) { return YES; } return NO;  }] subscribeNext:^(id x) { NSLog(@"filter:%@", x); }];Copy the code

The first block returns the id type. If it returns “map now”, it is a signal conversion. The second block prints the value of your return, “map now”.

[[[self.textField rac_textSignal] map:^id(NSString* value) { if (value.length 3) { return @"map now"; } return value;  }] subscribeNext:^(id x) { NSLog(@"map:%@", x); }];Copy the code

(4) Signal combination

RACSignal *firstCombineSignal = [self.textField rac_textSignal]; RACSignal *secondeCombineSignal = [tap rac_gestureSignal]; RAC(self.label, backgroundColor) = [RACSignal combineLatest:@[firstCombineSignal, secondeCombineSignal] reduce:^id(NSString *text, UITapGestureRecognizer * tap) {/ / here signal logic judgment and processing the if (text. Length = = 3 && tap. State = = UIGestureRecognizerStateEnded) { return [UIColor redColor]; } return [UIColor cyanColor]; }];Copy the code

⑤ Signal correlation

RAC(self.label, text) = [self.textField rac_textSignal];
Copy the code

30. Class inheritance, whether the class can inherit, whether the protocol can inherit

  • OC classes do not support multiple inheritance, only single inheritance.
  • Protocols can achieve multiple inheritance, just follow multiple protocols.
  • Message forwarding can also achieve multiple inheritance, but it is not recommended, and the maintenance cost is high.

What is the difference between inheritance and categories in implementation?

  • Categories can be added without knowing or changing the original code, and only methods can be added, not modified. If there is a name conflict between a category and a method in the original class, the category overrides the original method because the category has higher priority. A category does not affect the relationship of other classes to the original class.

  • Categories have three main functions:

    • (1) Split the implementation of the class into multiple different files or multiple different frameworks.
    • (2) Create forward references to private methods.
    • (3) Add informal protocols to objects.
  • Inheritance can add, modify, or delete methods, and can add attributes.

31. The difference between category and extension

  • 1). Realization principle of classification

After Category compilation, the underlying structure is struct category_t, which stores classified object methods, class methods, attributes, and protocol information. At runtime, the Runtime merges the Category data into the class information (class object, metaclass object).

  • 2). What is the difference between Category and Extension?

    • Class extensions can add private variables and methods to a class. They are written in the class’s source file and cannot be inherited by subclasses. When a class extension is compiled, its data is already contained in the class information.
    • Classes can add methods to classes and can be inherited by subclasses because classes merge data into class information at runtime. However, classification cannot add attributes directly and requires runtime association objects.
  • 3). Why can’t classification add member variables?

struct _category_t {
	const char *name;
	struct _class_t *cls;
	const struct _method_list_t *instance_methods;
	const struct _method_list_t *class_methods;
	const struct _protocol_list_t *protocols;
	const struct _prop_list_t *properties;
};
Copy the code
  • You can tell from the structure that there areProperty list, so classes can declare attributes, but only generate the corresponding of that attributeDeclarations for get and set, did not implement the method.
  • Structs do not have a list of member variables, so they cannot be declared.

32. How to implement Week

**weak: ** This attribute defines a non-owning relationship. When you set a new value for a property, the setting method neither holds the new value nor releases the old value.

Weak implementation principle:

    1. When an object is pointed to by the weak pointer, the weak pointer is stored as the key to the objectSideTable classtheweak_tableAn array of weak Pointers to the hash table.
    1. When an objectdeallocWhen the method is called,Runtimeinobjforkey, fromsideTabletheweak_tableIn the hash table, find the corresponding weak Pointers and set each of the weak Pointers tonil.

Key is the memory address of the weak object, and value is the table of all weak Pointers to this object.

33. Dictionary notes: The difference between setValue and Setobject

  • setObject:ForKeyIs:NSMutableDictionaryThe unique.
  • setValue:ForKeyIs:KVCThe main method of.
  • setobjectIn thekeyandvalueCan be anything other than nil.
  • setValueThe key can only be a string and the value can benilIt can also be empty[NSNull null]And all objects

34. Multithreading and locking

** process: ** is the basic unit of resource allocation. It is an instance of a program at execution time, created while the program is running.

** threads: ** is the smallest unit of program execution. It is the execution flow of a process. A process consists of multiple threads.

Multithreading:

The concurrent execution of multiple threads in a process is called multithreading. In a time slice, a CPU can only process one task in one thread. For a single-core CPU, executing tasks in different threads in different time slices creates the “illusion” that multiple tasks are being executed simultaneously.

Several ways of multithreading:

    1. pthread: that is,POSIX Thread, abbreviated aspthreadIs the POSIX standard for threads,Is a set of general-purpose multithreading apis.caninUnix/Linux/WindowsSuch as platformCross-platform use. It’s basically not used in iOS.
    1. NSThread:Apple encapsulates the object-oriented thread class, you can directly manipulate the threadCompared toGCD.NSThreadMore efficient,Created by the programmerWhen the task in the thread is finished, the thread will exit automatically.The programmer can also manually manage the thread lifecycle. Use frequency is low.
    1. GCDFull name:Grand Central Dispatch.Implemented by C language, it is a solution proposed by Apple for multi-core parallel computingCGD will automatically utilize more CPU cores,Automatically manages the life cycle of threads, the programmer only needs to tell the COMMUNIST party what tasks to perform,You don’t need to write any code to manage threads. GCD is also the most used multi-threading technology on iOS.
    1. NSOperation:Object-oriented multithreading based on GCD encapsulation is often used with NSOperationQueue, high frequency of use.

GCD is different from NSOperation

    1. GCDSupport onlyFIFO queue first in first out, does not support setting dependencies between asynchronous operations. whileNSOperationThe queue can be reprioritized to adjust the execution order of different operations.
    1. NSOperationsupportKVOTo observe the task execution status.
    1. GCDCloser to the bottom,GCDIt is fastest for low-level operations that seek performance.
    1. From transactionality between asynchronous operations, sequential rows, dependencies.GCDYou have to write more code to do that, andNSOperationThis support is already built in.
    1. If the process of asynchronous operations requires more interaction and UI presentation,NSOperationFor the better. In the underlying code, tasks are less interdependent and require more concurrency,GCDIs more advantageous.

Thread Pool Principle

  • When you use threads to perform tasks, you need to fetch threads from the thread pool for task assignment.
  • First, determine whether the thread pool size is smaller than the core thread pool size. If so, create a new thread to perform the task.
  • If the current small city size is greater than the core thread pool size, then start to determine if the work queue is full, and if not, submit the task to the work queue.
  • If the work queue is full, determine whether all the threads in the thread pool are working, and if there are idle threads that are not working, give it the task to perform.
  • If all the threads in the thread pool are working, then the saturation policy is left to execute.

There are four types of saturation strategies:

  • AbortPolicyDirect sellingRejectedExecutionExeceptionExceptions to prevent the normal operation of the system;
  • CallerRunsPolicyRollback the task back to the caller;
  • DisOldestPolicyDrop the most waiting task.
  • DisCardPolicyThe task is discarded.

Interthread communication

Add tasks to the task queue synchronously or asynchronously.

Messages are sent in the form of NSPort port to realize communication between different threads. Add NSPort to the thread RunLoop.

  • ** Direct messaging: ** passesperformSelectorA set of methods for executing tasks specified by one thread on another. Since the execution context of the task is the target thread, messages sent in this manner will be automatically serialized.
  • ** Global variables, shared memory blocks, and objects: ** Another simple way to pass information between two threads is to use global variables, shared objects, or shared memory blocks. Although shared variables are fast and easy, they are more fragile than direct messaging. Shared variables must be carefully protected using locks or other synchronization mechanisms to ensure correct code. Failure to do so may result in competitive conditions, data corruption, or crashes.
  • Conditional execution: A conditional is a synchronization tool that can be used to control when a thread executes a particular part of code. You can treat a condition as a lock and let the thread run only when the specified condition is met.
  • Runloop Sources: A custom Runloop source configuration allows specific application messages to be received on a thread. Because Runloop sources are event-driven, threads automatically go to sleep when there is nothing to do, increasing thread efficiency.
  • Port-based communication is a more sophisticated way to communicate between two threads, but it’s also a very reliable technique. More importantly, ports and sockets can be used to communicate with external entities, such as other processes and services. To improve efficiency, useRunloop sourceSo when there is no data waiting on the port, the thread will go to sleep.
  • ** Message queue: ** The traditional multiprocessing service is definedFirst in, first out (FIFO) queuesAbstract for managing incoming and outgoing data. Although message queues are simple and convenient, they are not as efficient as some other communication technologies.
  • **Cocoa Distributed Objects: ** Distributed objects are a Cocoa technology that provides an advanced implementation of port-based communication. Although it is possible to use this technique for interthread communication, it is strongly recommended not to do so because of the overhead involved. Distributed objects are better suited for communicating with other processes, although transactions between these processes are also expensive.

Thread safety means that only one thread can operate on the same data at a time. That’s where the lock comes in.

  • ** lock: ** is a thread-safe synchronization tool. Each thread acquires a lock before accessing a data resource, and then releases the lock after accessing it. If the lock is already occupied, other threads that want to acquire the lock wait until the lock is available again.
  • There are three kinds of locks in iOS: mutex, spin lock and semaphore. Mutex: In multithreaded programming, mutex prevents two threads from simultaneously reading or writing to the same common resource (such as a global variable).

Synchronized: It’s a recursive lock

  • callsynchronziedFor each object of,runtimeIt is assigned a recursive lock and stored in a hash table.
  • If thesynchronziedIf the internal object is freed or nil, it does something like thisobjc_sync_nilEmpty method of.
  • Be careful not to look likesynchronziedThe incomingnilThis will remove thread-safety from the code.

NSLock: follows the NSLocking protocol. The lock method is to lock. Unlock is to unlock, tryLock is to attempt to lock, and NO is returned if the lock fails. Note that the lock method cannot be called more than once, which will cause a deadlock.

Spin lock: * * * * thread will double checking the lock variable is available, the thread in the process execution, is a kind of busy waiting, once get the spin lock, thread will remain the lock, until explicitly release the spin lock, spin lock to avoid the process context scheduling overhead, so for thread will block the occasion of a very short time to be effective. Atomic is simply adding a spin lock through a set and get method.

Semaphore: dispatch_semaphore

Use:

  • 1.)dispatch_semaphore_create(value)Creates a semaphore, starting with 1.
  • 2). Wait for the semaphoredispatch_semaphore_waitLock and lock will make the semaphore -1.
  • 3). Send semaphoredispatch_semaphore_signal, which can be interpreted as unlocksignalSemaphore plus one.

The mutex is a special case where dispatch_semaphore is 0/1. Semaphores can have more value space for more complex synchronization, rather than just mutual exclusion between threads.

35. Notification, can cross thread

It cannot cross threads. Notifications sent in the same thread are received in the same thread. So you need to manually switch to the main thread to update the UI.

  • ** Test procedure: ** The notification thread decides to receive the notification processing code thread

Main thread sends notifications – Child threads listen for notifications: receive notification code is handled on the main thread

Child thread notification – The main thread listens for notifications: the receiving notification code is handled by the child thread

36. Network TCP, three-way handshake

Internet related interview questions

TCP is a transmission control protocol. It has the characteristics of connection-oriented, reliable transmission, point-to-point communication, and full-duplex service. TCP focuses on reliable transmission. UDP is a user datagram protocol. It has the characteristics of unconnected, unreliable, point-to-multipoint communication. UDP focuses on fast transmission.

TCP/IP: TCP/IP is not a protocol, but a protocol cluster. The network typically used is based on the TCP/IP protocol cluster. HTTP, DNS, FTP at the application layer, TCP(Transmission Control Protocol), UDP(User Datagram Protocol) at the transport layer, IP at the network layer, and so on, all belong to a subset of its internal.

Key fields of TCP packets: Serial number: Seq Serial number, consisting of 32 bits, which identifies the byte stream sent from the TCP source to the DESTINATION and is marked when the initiator sends data. Ack id: The Ack id is 32 bits. The Ack id field is valid only when the Ack flag bit is 1. Ack=Seq+1. Flag bits: a total of 6 flag bits, including URG, ACK, PSH, RST, SYN, and FIN, are defined as follows:

  • (A)URG: Urgent Pointer is valid.
  • (B)ACK: Confirm that the serial number is valid.
  • (C)PSH: The receiver should send the packet to the application layer as soon as possible.
  • (D)RST: Resets the connection.
  • (E)SYN: Initiates a new connection.
  • (F)FIN: Releases a connection.

TCP is a connection-oriented protocol that requires a three-way handshake: **

  • 1. First, the client willThe SYN flag bit is set to 1And then randomly generate oneThe serial number seq = J, the data packet is sent to the server, and the client entersSYN_SENTStatus waiting for confirmation from the server.
  • 2. After the server receives the data packet, theSign a SYN = 1Until the Client requests a connection, the Server willThe flag bit SYN and ACK are set to 1.Confirm the sequence number ACK =J+1, randomly generating oneThe serial number seq = KAnd sends the packet to the server to confirm the connection request, and the server entersSYN_RCVDState.
  • 3. After the client receives the confirmation, check itCheck whether the ack sequence number is J+1.Whether the flag bit ACK is 1, confirm the correct will beFlags ACK = 1andAck =K+1The packet is sent to the server, which checks itThe flag bit ACK is 1,Ack =K+1After success, the client and server enterESTABLISHED(Establishing a connection). The three-way handshake is complete. Data can be transferred at both ends.

TCP disconnection requires ** four waves: **

  • 1. The client sends a message to the serverRelease the FIN flag bit of the connection, the client entersFIN_WAIT_1Status waiting for confirmation from the server.
  • 2. The server receives the messageSign a FINAfter sendingConfirm flag bit ACKTo the client, confirm that the serial number isReceived serial number +1(Like SYN, a FIN occupies a sequence number.) The server entersCLOSE_WAITState.
  • 3. The server sends its ownRelease the FIN flag bit of the connection. Server AccessLAST_ACKState.
  • 4. The client receives the messageSign a FINAfter enteringTIME_WAITStatus, and then send oneConfirm flag bit ACKTo the server, confirm that the serial number isReceived serial number +1, the server entersCLOSEDState, complete four waves.

** The client enters the TIME_WAIT state instead of directly entering the CLOSED state because: ** We must assume that the network is unreliable. You cannot guarantee that the ACK packet you send will be received by the peer. Therefore, the peer SOCKET in the LAST_ACK state may resend the FIN packet because it fails to receive the ACK packet due to timeout. Therefore, the TIME_WAIT state is used to resend ACK packets that may be lost.

Why can’t we connect with two handshakes?

Since a three-way handshake is meant to let both parties know they are ready, a deadlock occurs if you change to a two-way handshake. Assuming the client send connection requests to the server, send confirmation of receipt of a service connection to the client, if two shake hands at this time will think of a service have established connections, can send data, but if confirmed connection data loss, the client also don’t know have established connection, confirm connection number will have been waiting for, cause data transmission timeout, The server repeatedly sends the same data, causing a deadlock.

Why four waves instead of three?

Because TCP is a full-duplex connection, the connection is closed only when the two-way confirmation is closed. Otherwise, one party can still send data.

37. HTTPS encryption principle

HTTPS is a transport protocol for secure communication over computer networks. It uses SSL/TLS to establish secure channels and encrypt data packets.

The server must have a digital certificate, which can be made by itself or applied to the organization. The difference is that the certificate issued by the user needs to be authenticated by the client before the user can continue to access the certificate, while the certificate applied by a trusted company does not display a prompt page. The certificate is actually a pair of public and private keys.

    1. The server sends the certificate (public key) to the client. The public key contains a lot of information, such as the certificate issuer, expiration time, the public key of the server, the signature of the third-party certificate Authority (CA), and the domain name information of the server.
    1. The client parses the certificate, verifies that it is correct, and encrypts a randomly generated value (the secret key) with the certificate. This part of the work is done by the TLS of the client. First, it verifies whether the public key is valid, such as the issuing authority, expiration time, and so on. If there is nothing wrong with the certificate, a random value (the secret key) is generated. The random value is then encrypted with a certificate.
    1. The client sends the encrypted secret key to the server. This part of the transmission is the secret key encrypted with the certificate. The purpose is to let the server get the secret key, and the communication between the client and the server can be encrypted and decrypted by the random value.
    1. The server uses the private key to decrypt the random value, and then encrypts the information symmetrically with the value. The server uses the private key to decrypt the secret key, obtains the private key sent by the client, and then encrypts the content symmetrically with the value.
    1. The encrypted information is encrypted with the private key on the server and can be restored on the client.
    1. Because it’s symmetric encryption, the client can decrypt the information and the client can decrypt the information sent by the server using the private key that was generated before, and then get the decrypted content.

What’s the difference between HTTP and HTTPS?

  • httpsThe agreement needs to apply for a certificate from CA. Generally, there are few free certificates and fees are required.
  • httpIt’s hypertext transfer protocol, information is in clear text,httpsIs a secure SSL encrypted transport protocol.
  • httpandhttpsThey’re using a completely different connection and they’re using a different port, 80, 443.
  • httpThe connection is simple and stateless.
  • HTTPSAgreement is madeSSL+HTTPProtocol A network protocol that supports encrypted transmission and identity authentication. It is more secure than HTTP

38. Differences between WebSocket and TCP Socket

  • A Socket is an abstraction layer, not a protocol, but a layer abstracts to facilitate the use of TCP or UDP. It is a set of interfaces between the application layer and the transport layer (TCP/UDP).

  • WebSocket, like HTTP, is an application layer protocol. It is a two-way communication protocol based on TCP connections and a technical solution to replace HTTP polling. HTTP is a full-duplex communication protocol. HTTP is one-way. Note that WebSocket and Socket are completely different concepts.

    • WebSocket establishes a connection over HTTP, but after the connection is established, HTTP is not required for actual transmission.

    • Compared with the traditional HTTP request-response mode that requires the client to establish a connection with the server, WebSocket is a TCP long-connection communication mode similar to Socket. Once the WebSocket connection is established, the subsequent data is transmitted in the form of frame sequence. Before the client disconnects from the WebSocket or the Server, the client and Server do not need to initiate a connection request again. In the case of massive concurrency and heavy load traffic between client and server, it greatly saves the consumption of network bandwidth resources and has obvious performance advantages. In addition, the client sends and receives messages on the same persistent connection, which has obvious real-time advantages.

    • WebSocket connection process – handshake process

      • 1. Establish a TCP connection between the browser and the server and shake hands three times. This is the basis of communication, the transport control layer, and if it fails, it doesn’t execute.
      • 2. After the TCP connection succeeds, the browser sends the TCP connection to the server through HTTPWebSocketInformation about supported versions. (HTTP handshake before starting)
      • 3. The server uses the handshake request from the clientHTTPProtocol returns data.
      • 4. After receiving a message indicating that the connection is successful, theTCPChannel for transmission and communication.
  • Socket.IO is a software library that provides real-time, bidirectional and event-based communication between browsers (clients) and servers.

Socket.IO separates data transmission into Engine.IO, internally encapsulates Polling and WebSocket, smoothen out some details and platform compatibility issues, and provides a unified API.

Note that socket. IO is not an implementation of WebSocket, but uses WebSocket to transfer data when necessary, with MetaData added on top of it. This is why the WebSocket client/server cannot communicate with the socket. IO server/client.

39. Event passing and response mechanisms

In iOS, only objects that inherit from UIResponder can accept and handle events.

Event passing: Events are passed from top to bottom (parent to child control)

  • After the touch event A is generated, the touch event is added to theUIApplicationIn the event queue managed (UIApplication receives the event first).
  • UIApplicationWill fetch the uppermost event (assume touch event A here) from the event queue, and willEvent objects are passed from top to bottom(UIApplicationkeyWindow– Parent control – child control), find the most appropriate control to handle the event
  • Whenever the event is passed to the control, its own is calledhitTest:withEvent:Method to find the view(which will be called internally) that best responds to the eventpointInside:withEvent:Determine if the touch point is on you).

Response mechanism: from bottom to top (up the responder chain: When an event is passed to a control but eventually hitTest:withEvent: no first responder is found, the event is traced back up the responder chain and discarded if neither UIWindow nor UIApplication instances can handle the event.

** Responder chain: ** The placement of views in iOS programs is contextual. A control can be placed above or below another control, so when the user clicks a control, it triggers the upper control or the following control. This sequence relationship constitutes a chain called responder chain. In other words, a responder chain is a chain connected by multiple responder objects.

  • If the parent control cannot accept touch events, then it is impossible for the child control to receive touch events

  • UIView cannot receive events in three cases:

    • Do not accept user interaction:userInteractionEnabled = NO
    • Hidden:hidden = YES
    • Transparency:Alpha < 0.01

Is it valid for a child view to click outside the parent view?

  • Invalid **(superview clipsToBounds=NO, so that subviews beyond the bound area of the superview are displayed), because the pointInside:withEvent: method of the superview returns NO and does not iterate down the subview.
  • But you can rewrite itpointInside:withEvent:To deal with.

40. runloop

Runloop: An object for event/message management through a loop maintained internally by the system. Runloop is actually a do… A while loop, which starts when there are tasks and sleeps when there are no tasks.

Its essence is throughmach_msg()Function receives and sends messages.

RunLoop’s relation to threads:

    1. RunLoopThe function is to manage threads, when threadsRunLoopAfter this function is enabled, the thread will be in a hibernation state after the execution of the task, waiting to accept new tasks, and will not exit.
    1. Only the main threadRunLoopIs enabled by default, other threadsRunLoopIt needs to be manually enabled. So when the program starts, the main thread will always run, never exit.

Runloop Internal flow of the event loop mechanism

RunLoop involves five classes:

CFRunLoop: RunLoop object,

CFRunLoopMode: five RunLoop modes

CFRunLoopSource: Input source/event source, including Source0 and Source1

CFRunLoopTimer: timing source, NSTimer,

CFRunLoopObserver: An observer that listens for runloops.

    1. CFRunLoop:RunLoop object
    1. CFRunLoopMode:There are five RunLoop modes:
    • kCFRunLoopDefaultMode: The default Mode in which the main thread is normally run.
    • UITrackingRunLoopMode: Interface tracking Mode, used for ScrollView tracking touch sliding, to ensure that the interface sliding is not affected by other modes.
    • UIInitializationRunLoopMode: The first Mode entered at the beginning of App startup will not be used after startup.
    • GSEventReceiveRunLoopMode: Accepts internal modes for system events, usually not needed.
    • kCFRunLoopCommonModes: is a pseudo-mode that can be run in modes marked CommonModes and which RunLoop will automatically return_commonModeItemsIn theSource,Observer,TimerSync to the Mode with this flag.
  1. CFRunLoopSource: input source/event source, including Source0 and Source1:

    • Source1: Based on mach_Port, handles events from the system kernel or other processes, such as clicking on the phone screen.
    • Source0 : Non-port-based processing events, i.e., application layer events, need to be manually flagged as pending and manual wake up RunLoop.
    • A simple example: An APP stands still in the foreground. When the user clicks the APP interface, the events on the screen surface will be wrapped firstEventtellsource1(mach_port).source1Wake up theRunLoopThe eventEventDistributed to thesource0By thesource0To deal with.
  2. CFRunLoopTimer: timing source, NSTimer. Wake up RunLoop at a preset point in time to perform a callback. Since it is runloop-based, it is not real-time (i.e. NSTimer is inaccurate). Because RunLoop is only responsible for distributing messages from the source. If the thread is currently working on a heavy task, the Timer may be delayed or executed less than once.

  3. CFRunLoopObserver: An observer that listens to the following points in time: CFRunLoopActivity

    • kCFRunLoopEntry: RunLoop ready to start
    • kCFRunLoopBeforeTimersRunLoop will handle some timer-related events
    • kCFRunLoopBeforeSourcesThe: RunLoop will handle some Source events
    • kCFRunLoopBeforeWaiting: RunLoop is going to hibernate, switching from user mode to kernel mode
    • kCFRunLoopAfterWaiting: RunLoop is woken up after switching from kernel mode to user mode
    • kCFRunLoopExit: RunLoop exit
    • kCFRunLoopAllActivities: Listens to all states

Connections between data structures:

  • 1:RunloopandthreadisOne to oneThe relationship between
  • 2:RunloopandRunloopModeisMore than a pair ofThe relationship between
  • 3:RunloopModeandRunloopSourceisMore than a pair ofThe relationship between
  • 4:RunloopModeandRunloopTimerisMore than a pair ofThe relationship between
  • 5:RunloopModeandRunloopObserverisMore than a pair ofThe relationship between

Why is main able to persist and never exit?

UIApplicationMain is called inside the main function, and the main thread runloop is launched inside the UIApplicationMain function, so that when there is a message processing, it can quickly switch from the kernel state to the user state, and immediately wake up processing. When there is no message processing, switch from user mode to kernel mode to enter the waiting state to avoid resource occupation. So main can always exist without exiting.

41. runtime

What is Runtime?

Runtime A set of APIS written in C, C ++, and assembly to provide runtime functionality for OC. The ability to defer the determination of data types from compile time to runtime.

Question 1: the nature of the method, question 2: the messaging mechanism of the Runtime

The essence of a method is to send a message.

Main process of sending messages:

    1. Quick find:objc_msgSendTo find thecache_tThe cache information
    1. Slow lookup: Recursively look up methods by itself and its parentlookUpImpOrForward
    1. Unable to find message, dynamic method parsing:resolveInstanceMethod
    1. Quick message forwarding:forwardingTargetForSelector
    1. Message slow forwarding: message signaturemethodSignatureForSelectorAnd distributeforwardInvocation
    1. Finally still not found message: program crash, reported a classic error messageunrecognized selector sent to instance xxx

What is SEL? What is IMP? What’s the connection?

  • SEL is the method number, or method name, that was loaded into the table in memory by the read_image method when dyLD loaded the image.

  • IMP is a function to achieve the pointer, looking for IMP is looking for the process of the function

  • The relationship between the two: SEL is equivalent to the title of the book’s table of contents, IMP is the page number of the book. To find a specific function is to read a specific chapter in the book:

    • 1). We first know what we want to see, that is, title-sel
    • 2). Then follow the directory corresponding page number – IMP
    • 3). Open the concrete content – the concrete implementation of the method

The runtime application:

  • 1. Method exchange: the interception system’s own Method call (Method Swizzling black magic) is applied specifically.
  • 2. Implementation adds attributes to the classification
  • 3. Realize dictionary model and automatic conversion
  • 4.JSPatch to replace the existing OC method, etc
  • 5. Aspect programming

Can I add instance variables to the compiled class? Can I add instance variables to classes created at run time? Why is that?

  • 1. You cannot add instance variables to compiled classes.
  • 2. You can add instance variables to classes created at run time.
  • 3. Because the compiled class is already registered in the Runtime, the class structureobjc_ivar_listA linked list of instance variablesandinstance_size Memory size of the instance variableIt’s been confirmed. MeanwhileruntimeWill be calledclass_setIvarLayoutorclass_setWeakIvarLayoutTo deal withstrong,weakReference, so you cannot add instance variables to an existing class.

Classes created at run time can add instance variables and call the class_addIvar function. But after calling objc_allocateClassPair, before objc_registerClassPair, for the same reason.

Add a distinction between attributes and member variables in a Category

    1. CategoryIts main purpose is to dynamically add methods to a class without changing the original class.
    1. The structure pointer to the classification has no property list, only method list. In principle, it can only add methods, not properties (member variables), but it can be associated with objects at run timeobjc_setAssociatedObject(self, @selector(name), name, OBJC_ASSOCIATION_COPY_NONATOMIC);,objc_getAssociatedObject(self,@selector(name));.
    1. The classification can be written@propertySetter /getter method declarations and implementations will not be generated, nor will private member variables be generated, which will compile, but references to variables will report errors.
    1. If there is a method with the same name as the original class in the classification, the method in the classification will be called first, that is to say, the method of the original class will be ignored. The priority of the method invocation is the parent class of the classification, because the method is placed in the method stack, following the principle of first in, last out.

42. The isa pointer

  • isaIs aThe Class typePointer, its source code structure isisa_tUnion, existing in a Class as a Class object, pointing to the address of the Class, size 8 bytes (64 bits).
  • Each instance object has oneisaPointer to the class of the object.ClassThere are aisaPointer tometeClass(metaclass). Metaclasses hold a list of class methods. When a class method is called, the metaclass looks for its implementation from itself. If not, the metaclass looks for the method from its parent. MeteClass is also a class, which is also an object and has isa Pointers.

The isa of the object points to the class, the ISA of the class points to the meta class, the metaclass ISA points to the root metaclass, and the ISA of the root metaclass points to itself, forming a closed inner loop. Isa can help an object find its method.

Isa points to the inheritance relation of the class in the diagram: LGTeacher -> LGPerson -> NSObject -> nil. The thing to notice here is that the parent of the root metaclass is NSObject, and the parent of NSObject is nil.

43. block

What is a Block A Block is an object that encapsulates a function and its execution context.

What is a Block call a Block call is a function call.

Several forms (types) of blocks

Blocks come in three forms, including:

  • GlobalBlock (_NSConcreteGlobalBlock) : When we declare a Block, if the Block does not capture external variables, then the Block is in the global (initialized data (.data) area).

  • Stack Block (_NSConcreteStackBlock) :

    • 1). ARC environment, when we declare and define a block, the system default use__strong modifierIf theBlockExternal variables are captured, essentially from__NSStackBlock__Shift to the__NSMallocBlock__“, but the system helped us to complete the copy operation, the block stack area to the heap area, prolong the block life cycle. forStack blockThe variable scope ends and the space is reclaimed.
    • 2). ARC environment, if we declare a block, use the__weakor__unsafe__unretained, then the system isNo copy operation, it isIt will not be migrated to the heap.
  • Heap Block (_NSConcreteMallocBlock) :

    • 1). In the MRC environment, we need to manually call the copy method to migrate blocks to the heap
    • 2). In the ARC environment,__strongModified (default) blocks capture external variables in the heap,NSMallocBlocksupportretain,release, the reference count is +1 or -1.
    • Only local variables – and defined properties are copied to the heap

1). Stored in the data area of the program, no external variables are referenced inside the block.

2). Blocks that use external variables and do not copy are stack blocks.

3). Copy stack blocks, that is, heap blocks. Copying a heap Block increases the reference count. Copy a global block, still a global block.

When should __block modifiers be used?

  • 1). The assignment operation of intercepted variables needs to be added__block qualifier(assignment! = use).
  • 2). Assignment of local variables (primitive data types and object types) is required__block qualifier. The inside is actually opposite to the__block objectCopy, so pass__blockYou can modify the value of an intercepted variable without interacting with external variables.
  • 3). Static local variables, global variables, static global variables are not needed__block qualifier.

Intercept variable properties of blocks?

A local variable Block of a primitive data type can intercept its value.

Local variables for object types are intercepted along with the ownership modifier.

Local static variables are intercepted as Pointers.

Blocks do not intercept global variables and static global variables.

Weak Breaks the Block loop reference principle

The internal operation of block is the pointer address of weakSelf, which is two different pointer addresses with self, that is, there is no direct holding of self, so weakSelf can break the cycle reference relation of self self-block-WeakSelf.

conclusion

That’s all for today’s sharing. No pains, no gains. I always believe in this truth, there will be pay to gain. Xiaobian is not easy, might as well help xiaobian one key three strikes, so that more people in need can see. Can also join my learning circle, exchange learning together, more information for oh!!

Benefits:Flutter goes from getting started to mastering video tutorials

Learning community