Introduction and analysis of IOS interview questions

Time:2021-9-4

The following is a review of the previous top, middle and bottom three interview questions, with answers.

As the saying goes, if the bottom is not firm, the earth will shake.

These answers are just for your reference. You can answer them in combination with your own understanding. Let’s take a look at them together, friends in need.

This article includes: official account [iOS advanced treasure book “iOS bottom interview dry cargo sharing (Supplement)]

Encryption 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: both parties use the same key, and the key transmission process is unsafe and easy to crack. Therefore, in order to keep secret, the key needs to be changed frequently.

AES: AES, also known as advanced encryption standard, is the next generation encryption algorithm standard. It supports 128, 192 and 256 bit key encryption. 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:Wheel changeNumber of turnsandKey extension

  • Advantages: high performance, high efficiency, flexibility and ease of use, high security level.
  • Disadvantages: the encryption and decryption keys are the same, so if the front and back ends use AES for encryption, how to save the key safely becomes a problem.

Des: data encryption standard. There are three entry parameters of DES algorithm:KeyDataMode

  • The key is 7 bytes and 56 bits in total, which is the working key of DES algorithm; Data is 8 bytes and 64 bits, which is the data to be encrypted or decrypted; Mode is the working mode of Des. There are two modes:Encryption and decryption
  • Disadvantages: compared with AES, the security is low.

3DES: 3DES is a mode of DES encryption algorithm. It uses three 64 bit keys to encrypt data three times. It is the encryption algorithm for the transition from des to AES and a more secure deformation of Des. It takes des as the basic module and designs the packet encryption algorithm through the combined packet method.

2. Asymmetric encryption: RSA encryption

  • Asymmetric encryption algorithm requires two keys in pairs, public keypublickey)And private key(privatekey) 。
  • Encryption and decryption process: for a private key, there is and only one corresponding public key. The generator is responsible for generating the private key and public key, saving the private key and disclosing the public key.

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

  • characteristic:

    1).Keep information confidential to prevent man in the middle attacks: the plaintext is encrypted through the receiver’s public key and transmitted to the receiver. Because only the receiver has the corresponding private key, others cannot own or calculate the private key through the public key, so it cannot be intercepted by the intermediary during the transmission process. Only recipients with private keys can read.This method is usually used to exchange symmetric keys

    2). Authentication and tamper protection: the authority dog encrypts a section of authorized plaintext with its own private key and sends the authorized plaintext, encrypted ciphertext and public key together. The receiver only needs to compare the decrypted ciphertext with the authorized plaintext through the public key to determine whether the plaintext has been tampered with halfway.This method is used for digital signature.

  • advantage: the encryption strength is small and the encryption time is long. It is often used for digital signature and encryption key. It has very high security and solves the security problem of symmetric encryption and saving key.
  • shortcoming: the encryption and decryption speed is much slower than symmetric encryption, which is not suitable for mass data encryption.

3. Hash encryption algorithm:MD5 encryption. Sha encryptionHMAC encryption

  • Hash algorithm encryption is to encrypt data through hash algorithm. The encrypted result is irreversible, that is, it can not be decrypted after encryption.
  • characteristic: irreversible, open algorithm, consistent encryption results of the same data.
  • effect: information summary, information “fingerprint”, used for data identification. Such as user password encryption, file verification, digital signature and authentication protocol.

MD5 encryption: the result of encrypting different data is fixed length 32-bit characters.

. Sha encryption: secure hash algorithm, mainly applicable to digital signature standard(DSS)It defines the digital signature algorithm (DSA). For lengths less than2^64Bit message,SHA1A 160 bit message summary is generated. When a message is received, the message digest can be used to verify the integrity of the data. In the process of transmission, the data is likely to change, so different message summaries will be generated at this time. Except, of courseSHA1alsoSHA256as well asSHA512Wait.

HMAC encryption: given a key, encrypt the plaintext and do “hashing” twice. The result is still a 32-bit string.

4. Base64 encryption

  • A coding method, which is not an encryption algorithm in the strict sense. Its function is to encode binary data into text to facilitate network transmission.
  • usebase64After encoding, the data length will increase by about 1 / 3, but the advantage is that the encoded data can be displayed directly in emails and web pages;
  • althoughbase64Can be used as encryption, butbase64Can inverse operation, very unsafe!
  • Base64 coding has a very significant feature, with a ‘=’ sign at the end.
  • Principle:
    1) . convert all characters to ASCII code;
    2) Convert ASCII code into 8-bit binary;
    3) . make up 0 for a group of binary three bits, a total of 24 bits, and then split it into a group of 6 bits, a total of four groups;
    4) . uniformly fill two 0-8 bits before the 6-bit binary;
    5) . convert the binary after 0 to decimal;
    6) Finally, obtain the base64 code corresponding to the decimal system from the base64 code table.

App security, digital signature, APP signature, re signature

Because the application is actually a shelled IPA file, but it may be shelled or even jailbroken. The IPA package downloaded by the mobile phone is directly shelled and can be decompiled directly, so don’tPlist file. in the projectStatic fileStore critical information in. So sensitive information is symmetrically encrypted or stored inkeychainInside. And the encryption key should be changed regularly.

Digital signature is throughHash algorithmandRSA encryptionTo achieve.We add plaintext dataadoptRSA encryptionDataHash valueIt is transmitted to the other party together, and the other party can decrypt itHash valueTo verify. This is encrypted by RSAHash valueData, we call it digital signature.

App signature

  • 1. Generate a pair of public key and private key on the MAC development machine, which is called public key L and private key L (L: local).
  • 2. Apple has a fixed pair of public and private keys,Private keyBehind apple,Public keyOn each IOS device. Here, it is called public key A and private key a (A: Apple).
  • 3. PutPublic key L on the development machineTo Apple backstage, withApple background private key aGo signPublic key L。 Get a containingPublic key LAnd itsautographData certificate.
  • 4. Apply for appid in apple background and configure itDevice ID listandPermissions available to app, plus the of step ③certificateData composed ofPrivate key aSignature, data and signature together to form aProvisioning ProfileDescription file, download toNative MAC development machine
  • 5. During development, after compiling an app, useLocal private key LSign the app and put the information obtained in step ④Provisioning ProfileThe description file is packaged into the app, and the file name isembedded.mobileprovision, install the app on the mobile phone.
  • 6. During installation, the IOS system obtains the certificate and passesSystem built-in public key a, to verifyembedded.mobileprovisionofdigital signature If it is correct, the certificate signature inside will be checked again.
  • 7. Ensureembedded.mobileprovisionAfter all the data in the app is authorized by apple, you can take out the data and do various verifications, including verifying the app signature with the public key L, verifying whether the device ID is in the ID list, whether the appid corresponds, and whether the permission switch corresponds to the entries in the app.

OC data type

Introduction and analysis of IOS interview questions

① Basic data type

  • Basic data types of C language (e.gshort、int、floatThey are not objects in OC, but a certain byte of memory space is used to store values. They do not have the characteristics of objects, and no attribute methods can be called.
  • Basic data types in OC:
    NSInteger(equivalent to a long integer)
    NSUInteger(equivalent to unsigned long integer)
    CGFloat(64 bit system is equivalent to double, 32-bit system is equivalent to float), etc.
    They are not classes, they just usetypedefThe basic data type is redefined,They are still just basic data types
  • Enumeration type: it is essentially an unsigned integer.
  • Bool type: is a macro definition, and the bottom layer of OC uses signed char to represent bool.

② Pointer data type

Pointer data types include: Classid

  • Class:NSStringNSSetNSArrayNSMutableArrayNSDictionaryNSMutableDictionaryNSValueNsnumber (inherits nsvalue)And so on. They are all classes. After creation, they are objects. InheritanceNSObject
    Provided in OCNSValueNSNumberTo encapsulate the basic types of C language, so that we can make them object-oriented.
  • id:idIs a pointer to an Objective-C object, which is equivalent to that in C languagevoid*, you can map any object pointer to him, or map it to other objects. The common ID type is the delegate attribute of the class.

Difference between set nsset and array nsarray:

  • Are addresses that store different objects;
  • However, nsarray is an ordered set and nsset is an unordered set. They can convert each other.
  • Nsset automatically removes duplicate elements.
  • Set is a hash table. Using hash algorithm, it is faster to find the elements in the set than array, but it has no order.

③ Construction type

Construction types include: structure, Consortium

  • Structure:struct, combine variables of multiple basic data types into a whole. Internal members in the structure are accessed with dot operators.
  • Consortium (Consortium):union, some similar structuresstructA data structure, Consortium(union)And structure(struct)It can also contain many data types and variables.

Difference between structure and consortium:

  • Structure(struct)All variables in are “coexisting”, and each member has a value at the same timesizeofFor the sum of all members.

advantage:It is “tolerance is great” and comprehensive;

Disadvantages:The allocation of struct memory space is extensive, regardless of whether it is used or not

Allocation will cause a waste of memory.

  • Consortium(union)Each variable in is mutually exclusive. Only one member has a value at the same timesizeofFor the longest membersizeof

advantage:It is more precise and flexible in memory use and saves memory space.

Disadvantages:It is not “inclusive”. When modifying one member, the original member value will be overwritten;

Property and property modifiers

@The nature of propertyyesIvar (instance variable) + setter + getter.

What do we do internally each time we add an attribute

  • 1. The system willivar_listAdd a description of a member variable to the;
  • 2. Inmethod_listMedium increasesetterAndgetterDescription of the method;
  • 3. Add an attribute description to the attribute list;
  • 4. Then calculate the offset of the attribute in the object;
  • 5. GivesetterAndgetterMethod, insetterMethod, starting from the position of the offsetgetterMethod starts from the offset. In order to read the correct number of bytes, the pointer type of the system object offset is forced.

Modifier:

  • Under MRC: assign、retain、copy、readwrite、readonly、nonatomic、atomicWait.
  • Under arc:assign、strong、weak、copy、readwrite、readonly、nonatomic、atomic、nonnull、nullable、null_resettable、_Null_unspecifiedWait.

The following are explained separately

  • assign: used for basic data types without changing the reference count. If you decorate an object (the object needs to release memory manually in the heap, and the basic data type automatically releases memory in the stack system), the pointer will not be set to nil after the object is released, and a wild pointer will appear.
  • retain: as with strong, release the old object, and the reference count of the new object passed in is + 1; Release appears in pairs in MRC.
  • strong: used in arc, it tells the system to keep this object on the heap until there is no pointer, and there is no need to worry about reference counting under arc, and the system will release it automatically.
  • weak: before being strongly referenced, keep it as much as possible without changing the reference count; A weak reference is a weak reference, and you don’t hold it; It essentially assigns an attribute that is not held. When the referent is dealloc, the pointer of the weak reference will be automatically set to nil.
    Circular references can be avoided.
  • copy: is generally used to modify immutable type attribute fields, such as:NSStringNSArrayNSDictionaryWait. Modifying with copy can prevent the attributes of this object from being affected by the outside worldNSMutableStringAssign toNSStringModifying the former will cause the value of the latter to change. alsoblockThe copy modifier is often used, but in fact, in arc, the compiler will automatically copy the block, which has the same effect as strong. However, in MRC, the block inside the method is in the stack area. You can put it in the heap area by using copy.
  • readwrite: can read and write; The compiler automatically generates setter / getter methods.
  • readonly: read only; Will tell the compiler not to automatically generate setter methods. Property cannot be assigned.
  • nonatomic: non atomic access. Using nonatomic means that multiple threads can access variables, which will lead to unsafe read and write threads. However, it will improve execution performance.
  • atomic: atomic access. The compiler will automatically generate mutexes and lock setter and getter methods to ensure that the atomic operation of attribute assignment and value is thread safe, but does not include the operation and access of variable attributes. For example, adding or removing objects to an array is not within the scope of atomic’s responsibility, so adding or removing objects to an array modified by atomic can’t ensure thread safety.The disadvantage of atomic access is that it will consume performance and lead to slow execution efficiency.
  • nonnull: setting property or method parameters cannot be null. They are specially used to decorate pointers and cannot be used for basic data types.
  • nullable: setting property or method parameters can be empty.
  • null_resettable: set the property. The get method cannot return null. The set method can be assigned null.
  • _Null_unspecified: setting a property or method parameter is not sure if it is empty.

The last four attributes should be mainly to improve the development specification and prompt the user what value to pass. If the requirements for the specification value are violated, there will be a warning.

The object release modified by weak is automatically set to nil. Implementation principle:

RuntimeMaintained aWeak tableTo store all data pointing to an objectWeak pointerWeak tableIt’s actually aHash tableKeyIs the address of the object in question,ValueyesweakThe address array of the pointer (the value of this address is the address of the object).

The implementation principle of weak can be summarized as follows:

  • 1. During initialization:runtimeWill callobjc_initWeakFunction to initialize a new weak pointer to the address of the object.
  • 2. When adding a reference:objc_initWeakThe function will callobjc_storeWeak()Function,objc_storeWeak()The function of is to update the pointer and create the corresponding weak reference table.
  • 3. When released, callclearDeallocatingFunction.clearDeallocatingThe function first gets all the information based on the object addressweakAn array of pointer addresses, and then traverse the array to set the data in it tonilFinally, delete the entry from the weak table, and finally clean up the records of the object.

Member variableivarAnd propertiespropertyAnd the role of different keywords

Member variables:The default modifier for member variables is@protected. set and get methods will not be generated automatically. They need to be implemented manually. Point syntax calls are not allowed because there are no set and get methods, so they can only be used->

Properties:Property generates underlined member variables and by defaultsetter/getterMethod can be called with point syntax. The actual calls are set and get methods.

Note: attributes added in classification will not be generated automatically **setter/getter**Method must be added manually.

Instance variable:Class class. The instantiated object is an instance object

Keyword function:

  • Access scope keyword

    • @public: declare public instance variables, which can directly access the member variables of the object anywhere.
    • @private: declare private instance variables, which can only be accessed directly in the object methods of the current class. To access subclasses, you need to call the get / set method of the parent class.
    • @protected: can be accessed directly in the object methods of the current class and its subclasses (system default).
    • @package: it can be accessed directly under the same package, for example, in the same framework.
  • keyword

    • @property: declare properties and automatically generate a member variable starting with an underscore_ Propertyname (modified with @ private by default), property setter, declaration of getter method, implementation of property setter and getter method.be careful:stayProtocol @ protocolOnly getter and setter method declarations are generated in, so you need to manually implement getter and setter methods and define variables manually.
    • @sythesize: modify the automatically generated @ property_ Propertyname member variable name,@synthesize propertyName = newName;
    • @dynamic: tell the compiler that the setter and getter methods of properties are implemented by the user and are not automatically generated.Use with caution:If you assign values to attributes, you can compile successfully, but running will cause the program to crash, which is often called dynamic binding.
    • @interface: declaration class
    • @implementation: class implementation
    • @selecter: create a SEL, class member pointer
    • @protocol: declaration agreement
    • @autoreleasepool: auto release pool in arc
    • @end: end of class

Class cluster

Class clusterIs a design pattern widely used in the foundation framework.A class cluster groups multiple private concrete subclasses under a public abstract superclass。 Grouping classes in this way simplifies the common visible architecture of the object-oriented framework without reducing its functional richness.Class clusters are based on abstract factory design patterns

Common class clusters areNSStringNSArrayNSDictionaryWait.Take the array as an example:Whether you create a variable or immutable array, inallocThe resulting classes are__NSPlaceholderArray。 And when weinitAfter an immutable empty array, you get __NSArray0; If there is and only one element, it is__NSSingleObjectArrayI; With multiple elements, it’s called__NSArrayIinitIf you come up with a variable array, it’s all__NSArrayM

advantage:

  • You can hide the complex details behind the abstract base class.
  • Programmers do not need to remember the specific class implementation of various created objects, which simplifies the development cost and improves the development efficiency.
  • It is convenient for packaging and componentization.
  • It reduces the lack of extensibility code such as if else.
  • Adding new feature support does not affect other codes.

Disadvantages:

  • Existing class clusters are very difficult to expand.

We use the scenario of class cluster:

  1. When a bug occurs, you can quickly locate the bug location through the class cluster keyword in the crash report.
  2. When implementing some fixed things that do not need to be modified frequently, you can efficiently select class clusters to implement them. Example:
  • For different versions, different models often need different settings. At this time, you can choose to use class clusters.
  • App settings page, which does not need to be modified frequently, can use class clusters to create a large number of duplicate layout codes.

Recommendation at the end of the article: IOS popular anthology & video analysis

① Swift

② IOS underlying technology

③ IOS reverse protection

④ IOS interview collection

⑤ Large factory interview questions + bottom technology + reverse Security + swift

Remember to like your little partner~

Collecting is equal to whoring for nothing, and praising is the truth (´ ᴗღ) ღ