directory

First, basic knowledge points two, third party framework three, algorithm four, coding format (optimization details) five, other knowledge pointsCopy the code

First, basic knowledge points

  1. What are the design patterns? What design patterns do you know, and describe them briefly?

    A design pattern is a coding experience that uses mature logic to do a certain type of thing. 1). MVC pattern: Model View Control, decoupling the Model View controller layer. 2). MVVM mode: Model View ViewModel decouples and writes the Model View business logic layer. 3). Singleton mode: declare global variables using static keywords. The value is assigned only once during the entire duration of the process. 4). Observer mode: KVO is a typical observer mode, observing the state of a certain attribute and notifying the observer when the state changes. 5). Delegation mode: combination of agent and protocol. 1 to 1 to achieve the reverse value operation. 6). Factory pattern: Using a class method to batch produce objects based on an existing template.

  2. MVC vs. MVVM

    MVVM is a split of the fat model, its essence is to reduce the burden of the controller, some weak business logic into the VM to deal with. MVC is the foundation of all design, and all new design patterns are improvements based on MVC. Reference: summary of iOS MVVM Architecture

  3. What’s the difference between #import and #include? What’s the difference between #import<> and #import “?

    1). #import is the keyword used to import headers in Objective-C. #include is the keyword used to import headers in C/C++. 2).@class tells the compiler to look at the implementation file of a class when the declaration is executed, which can solve the mutual inclusion of header files. 3). #import<> is used to contain system headers, and #import “” is used to contain user headers.

  4. What’s the difference between frame and bounds?

    Frame refers to the position and size of the view in the parent view’s coordinate system. (The reference point is the parent view’s coordinate system.) Bounds refer to the position and size of the view in its own coordinate system. (The reference point is its own coordinate system)

  5. Can objective-C classes inherit multiple times? Can multiple interfaces be implemented? What is Category? Is it better to inherit or classify methods that override a class? Why is that?

    A: Objective-C classes cannot be multiple inherited; Multiple interfaces (protocols) can be implemented; Category is a Category; In general, the method of overwriting a class with a Category is only valid for this Category, and will not affect the relationship between other classes and the original class.

  6. What’s the nature of @property? How are ivar, getters, and setters generated and added to this class

    What’s the nature of @property? @property = ivar + getter + setter; A property is a feature of Objective-C that encapsulates data in an object. A property is a property that encapsulates data in an object. Objective-c objects typically store the data they need in a variety of instance variables. Instance variables are typically accessed through an “Access method.” Getters are used to read the value of a variable, and setters are used to write the value.

  7. What are the property keywords in @property? What modifiers can follow / @property?

    Attributes There are four types of attributes that can be possessed: 1. Atomic — nonatomic. 2. Read/Write permission – ReadWrite, readonly 3. Memory management semantics –assign, strong, weak, unsafe_unretained, copy 4. Method name – Getter =, setter= 5. Uncommon: nonNULL, NULl_resettable,nullable

  8. What do the attribute keywords readwrite, readonly, assign, retain, copy, and nonatomic do, and in which case?

    1). Readwrite is a readable and writable feature. Getter and setter methods need to be generated. 2). Readonly Indicates the read-only feature. Only getters are generated, not setters, and you don’t want properties to change outside the class. 3). Assign is an assignment feature. The setter method assigns the passed parameter to the instance variable; Assign is used for the base data type when setting variables only. 4).retain (MRC)/ Strong (ARC) indicates holding characteristics. The setter method will keep the passed parameter and then assign it, and the retainCount of the passed parameter will be +1. 5). Copy indicates the copy feature. When the setter method makes a copy of the passed object, a completely new copy of the variable is required. 6). Nonatomic If not, the default is atomic. The difference between atomic and nonatomic is that the system automatically generates different getter/setter methods. For atomic properties, the system generates getters/setters that guarantee the integrity of the get and set operations, whereas nonatomic does not. So nonatomic is faster than atomic. But atomic does not guarantee thread-safety. What’s the difference between atomic and nonatomic?

  9. When to use the weak keyword, how does it differ from assign?

    1. In ARC, when a circular reference is possible, it is often resolved by having one end use weak, such as the delegate property. 2. The IBOutlet has already made a strong reference to it once. If there is no need to make a strong reference again, weak is also used. Of course, you can also use strong. Why can an IBOutlet view attribute be set to Weak? Because the parent control’s subViews array already has a strong reference to it. Differences: Assign can be used on non-OC objects, whereas Weak must be used on OC objects. Weak indicates that the property defines a “non-ownership relationship.” The property value is automatically cleared (nil) when the object to which the property refers is destroyed.

  10. How to use the copy keyword?

    USES:

> 1\.nsString, NSArray, NSDictionary, and so on often use copy keyword, because they have corresponding variable type: NSMutableString, NSMutableArray, NSMutableDictionary; > 2\. Block also often uses the copy keyword. > > Description: > Block using copy is a "legacy" from MRC. In MRC, the inner block of a method is in the stack, and using copy can put it in the heap. It doesn't matter whether you write in ARC or not: using copy or strong for a block is the same, but writing copy doesn't hurt, and it reminds us that the compiler automatically copies the block. If you don't write copy, the caller of this class may forget or not know that the compiler automatically copies the block, and they may copy the property value before calling it. This operation is redundant and inefficient.Copy the code
  1. NSString/NSArray/NSDictionary declared with @property often uses the copy keyword. Why? What problems might arise if you use the strong keyword instead?

    A: NSString, NSArray, and NSDictionary often use the copy keyword because they have variable types: NSMutableString, NSMutableArray, and NSMutableDictionary may assign between them (that is, assign mutable to immutable). To ensure that the string value in an object does not unintentionally change, a copy should be made when setting the value of a new property.

> > 1\. Since the parent pointer can point to the subclass object, the purpose of using copy is to make the property of this object unaffected by the outside world. If copy is passed to me as a mutable object or an immutable object, I hold an immutable copy. > 2\. If we use strong, then this property may refer to a mutable object, and if the mutable object is modified externally, this property will be affected. > > Summary: The purpose of using copy is to prevent an object of mutable type from inadvertently tamper with the original value of an immutable object by sending changes to the value of an immutable object.Copy the code
  1. What’s the difference between shallow copy and deep copy?

    Shallow copy: Only the pointer to the object is copied, not the reference object itself.

> Deep copy: copies the reference object itself. There are two separate copies of the object itself in memory. When you change A, A_copy does not change.Copy the code
  1. Copy and mutableCopy methods for system objects

    Whether collection objects (NSArray, NSDictionary, NSSet… Or non-collection objects (NSString, NSNumber… ), and when receiving copy and mutableCopy messages, follow the following guidelines:

> 1\.copy returns an immutableObject; If we call a mutable method with the return value of copy, we crash. > 2\.mutablecopy returns a mutableObject.Copy the code
In non-collection objects, copy operations on immutable objects are pointer replication, while mutableCopy operations are content replication; Copy of mutable objects and mutableCopy are both content copies. NSString * STR = @hello word! ; NSMutableString *strMCopy = [STR copy]; NSMutableString *strMCopy = [STR mutableCopy]; NSMutableString *mutableStr = [NSMutableString stringWithString: @" Hello word!"] ; NSMutableString *strMCopy = [mutableStr mutableCopy] // Content copyCopy the code
In the collection object, the immutable object copy operation, is a pointer copy, mutableCopy operation is a content copy; Copy of mutable objects and mutableCopy are both content copies. However: the content copy of a collection object is limited to the object itself; it is still a pointer copy to the object elements within the collection. (i.e., single copy) NSArray * arr = @ [@ [@ "a" @ "b"], @ [@ "c", @"d"]; NSArray *copyArr = [arr copy]; NSMutableArray *mCopyArr = [arr mutableCopy] *array = [NSMutableArray arrayWithObjects:[NSMutableString stringWithString:@"a"],@"b",@"c",nil]; NSArray *copyArr = NSMutableArray *mCopyArr = [mutableArr mutableCopy]; NSMutableArray *mCopyArr = mutableArr mutableCopy]Copy the code

If you copy an immutable object, it is a pointer copy (shallow copy). Otherwise, it is a content copy (deep copy).

  1. @property (nonatomic, copy) NSMutableArray arr;

    Problem: When adding, deleting, or modifying an element in an array, the program crashes because it cannot find the corresponding method. -[__NSArrayI removeObjectAtIndex:]: Unrecognized Selector sent to instance 0x7FCD1bc30460 NSArray objects can not call methods of type NSMutableArray objects) because copy is to copy an immutable NSArray object, you cannot add/modify an NSArray object.

  2. How do I get my class to use the copy modifier? How do I override setters with the copy keyword?

    If you want to copy the objects you write, you need to implement the NSCopying protocol. If the custom object has mutable and immutable versions, implement both the NSCopying and NSMutableCopying protocols. Specific steps: 1. Declare that this class complies with NSCopying protocol 2. Implementation of the NSCopying protocol. // This protocol has only one method:

    • (id)copyWithZone:(NSZone *)zone;

    // Note: using the copy modifier, you call the copy method, but you really need to implement the “copyWithZone” method.

  3. ** Write a setter method for @property (nonatomic, retain) NSString name, Write a setter method for @property (nonatomic, copy) NSString name

// retain - (void)setName:(NSString *)str {
      [str retain];
      [_name release];
      _name = str;
    } // copy - (void)setName:(NSString *)str {
      id t = [str copy];
      [_name release];
      _name = t;
    }
Copy the code
  1. What does at sign synthesize do and at sign dynamic do?

    At sign property has two words, at sign synthesize, and at sign dynamic. If it’s not at sign synthesize or at sign dynamic, then the default is at sign synthesize var = _var; The @synthesize syntax is used to specify the name of the instance variable in the class’s implementation code. (@synthesize var = _newVar;) 1. The semantics of at sign synthesize is that if you don’t implement the setter and getter manually, then the compiler will automatically add those two methods to you. 2. @Dynamic tells the compiler that setters and getters for properties are implemented by the user and are not automatically generated (for example, @dynamic var).

  2. What are the common data types in Objective-C, and how are they different from the basic data types in C? For example, NSInteger and int

    The data types in Objective-C are NSString, NSNumber, NSArray, NSMutableArray, NSData, and so on, and these are all classes, and they’re created as objects, whereas the basic data type in C, int, is just a bunch of bytes of memory to hold numbers; NSInteger is a basic data type, not a subclass of NSNumber, and certainly not a subclass of NSObject. NSInteger is an alias for the basic data type Int or Long (typedef Long NSInteger). The difference is that NSInteger is itself an Int or a Long based on whether the system is 32-bit or 64-bit.

  3. What are the properties of the object declared by id?

    The object declared by id has the runtime property that it can point to any Objcetive-C object of any type.

  4. How is memory management in Objective-C? What are your thoughts and solutions?

    A: There are three main ways to manage memory in Objective-C: ARC(automatic memory count), manual memory count, and memory pool. 1). Automatic memory counting ARC: Xcode automatically adds memory management code to the code during App compilation. 2). Manual memory count MRC: follow the memory who apply, who release; He who adds, he who releases. 3). Release Pool: Put all the memory to be released into one Pool. When the Pool is drained, all the memory space in the Pool will be released automatically. A memory pool can be released automatically or manually. Automatic release is affected by the Runloop mechanism.

  5. What’s the way to create a thread in Objective-C? If the code is executed in the main thread, what is the method? If you want to delay the execution of the code, what method?

    A: There are three ways to create a thread: using NSThread, using GCD’s Dispatch, subclassing NSOperation, and then adding it to NSOperationQueue; In the main thread to execute code, the method is performSelectorOnMainThread, if you want to delay implementation code can use the performSelector: onThread: withObject: waitUntilDone:

  6. The difference between Category, Extension, and inheritance

    1. Classification has a name, class extension does not have a name, is a special classification. 2. Classes can only extend methods (attributes are just declarations, not implementations). Class extensions can extend attributes, member variables, and methods. 3. Inheritance can add, modify, or delete methods, and can add attributes.

  7. What do we mean when we say OC is a dynamic runtime language?

    Answer: It mainly postpones data type determination from compile time to run time. In simple terms, the runtime mechanism allows us to not determine the class of an object and call the methods specified for that class object until run time.

  8. Why do we use week instead of retain/ Strong for the delegate attribute?

    Answer: To prevent unnecessary circular references from being generated between the delegates. @property (nonatomic, weak) id delegate;

  9. When to use delete and when to use Notification?

    Delegate: 1-to-1 reverse message notification function. Notification mode: You just want to send a message to inform you of some state change. But it doesn’t matter who wants to know.

  10. What are KVO and KVC?

    1).kvc (key-value-coding) : Key-value Coding is a way of indirectly accessing objects through strings (i.e. assigning values to attributes)

> For example: > [stu. Name] (https://link.jianshu.com/?t=http%3A%2F%2Fstu.name) = @ "zhang SAN" / / some syntax for attribute assignment > [stu setValue: @ "zhang" forKey:@"name"]; Stu1.namelabel. text = @" "; stu1.namelabel. text = @" "; > [stu1 setValue: @namelabel.text "]; // cross-layer assignment > 2).kvo (key-value-observing) : this mechanism provides a way to observe changes in an attribute, greatly simplifying code. > KVO can only be triggered by KVC, including using setValue:forKey: method and dot syntax. > - (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(nullable void *)context; > > // When the observed property sends a change, > - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context; The keyPath of KVC and KVO can be a property, instance variable, or member variable. > iOS member variable, attribute variable, local variable, instance variable, Global variables, rounding] (https://link.jianshu.com/?t=http%3A%2F%2Fblog.csdn.net%2Fchenshun123%2Farticle%2Fdetails%2F52280564)Copy the code
  1. The underlying implementation of KVC?

    When an object calls the setValue method, the method internally does the following:

> 1). Check if there is a set method for the corresponding key, and if so, call the set method. > 2). If the set method does not exist, it looks for the underlined member variable with the same name as key, and if it does, it assigns a value directly to the member variable attribute. > 3). If _key is not found, it looks for the attribute key with the same name, and assigns a value directly if there is one. > 4). If you haven't found, the call valueForUndefinedKey: and setValue: forUndefinedKey: method. The default implementation of these methods is to throw exceptions, and we can override them as needed.Copy the code
  1. Underlying implementation of KVO?

    KVO is implemented based on runtime mechanism.

> [to explore the underlying implementation principle of KVO] (https://www.jianshu.com/p/829864680648)Copy the code
  1. ViewController life cycle

    In order of execution:

> 1\.initWithcoder: triggered when initializing through a NIB file. > 2\.awakeFromNib: When the nib file is loaded, an awakeFromNib message is sent to each object in the nib file. > 3\.loadView: Starts loading the view controller's own view. > 4\.viewDidLoad: The view controller's view is loaded. > 5\.viewwillAppear: The view controller's view will be displayed on the window. > 6\.updateViewConstraints: The View controller's view starts updating the AutoLayout constraint. > 7\.viewwillLayoutSubViews: The location where the view controller's view will update the content view. > 8\.viewDidLayoutSubViews: View controller's view has updated the position of the view. > 9\.viewDidAppear: The view controller's view has been displayed on the window. > 10\. ViewWillDisappear: View controller's view is about to disappear from the window. > 11\. ViewDidDisappear: The view controller's view disappears from the window.Copy the code
  1. What’s the difference between methods and selectors?

    A selector is the name of a method, and a method is a combination of a name and an implementation.

  2. Have you been exposed to the reflex mechanism in OC? A little bit about concepts and usage

    1). Class reflection

> Instantiates an object as a string of the class name. > Class class = NSClassFromString(@"student"); > Student *stu = [[class alloc] init]; > Change the class name to a string. > Class class =[Student class]; > NSString *className = NSStringFromClass(class); > 2).sel reflection > Instantiate a method through its string form. > SEL selector = NSSelectorFromString(@"setName"); > [stu performSelector:selector withObject:@"Mike"]; > Turn the method into a string. > NSStringFromSelector(@selector*(setName:));Copy the code
  1. There are two ways to call a method:

    1). Call directly by method name. [person show];

> 2). Call indirectly through SEL data. SEL aaa = @selector(show); [person performSelector:aaa];Copy the code
  1. How do I perform performance tests on iOS devices?

    A: Profile-> Instruments ->Time Profiler

  2. How do you check for memory leaks when developing a project?

    1). Static analysis

> 2). There is a leak inside the instruments to dynamically analyze.Copy the code
  1. What is lazy loading?

    A: Lazy loading means initializing only when needed. You can also think of it as delayed loading.

> < span style = "box-sizing: border-box; color: RGB (74, 74, 74); line-height: 22px; font-size: 14px; white-space: inherit;"Copy the code
  1. What do @public, @protected, @private, and @package declarations mean for class variables?

    @public can be accessed anywhere;

> @protected class and subclasses, is the default; > @private can only be accessed in this class; > @package Use within this package, not across packages.Copy the code
  1. What is a predicate?

    Predicates are the logical conditions given by NSPredicate as constraints to complete the filtering of data.

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"age<%d",30]; NSPredicate predicateWithFormat:@"age<%d",30]; > / / use the predicate filter element in the array, returns after filtering the results of the query > NSArray * array = [persons filteredArrayUsingPredicate: predicate];Copy the code
  1. The ISA pointer problem

    Isa: isa pointer to type Class. Each instance object has a pointer to ISA, which points to the object’s Class, and there is also a pointer to ISA, which points to meteClass(metaclass). A metaclass holds a list of class methods. When a class method is called, it first looks for the implementation of the class method from itself; if not, the metaclass looks for the method from its parent class. Also note that a meteClass is also a class, which is also an object. Metaclasses also have isa Pointers, and its ISA pointer ultimately points to a root meteClass. The root metaclass’s ISA pointer points to itself, thus forming a closed inner loop.

  2. How to access and modify the private properties of a class?

    1). One is through KVC.

> 2). Use Runtime to access and modify private properties.Copy the code
  1. What does an OBJc object’s ISA pointer point to? What does it do?

    Answer: Point to the object of his class, so you can find the methods on the object.

  2. What does the following code output?

    @implementation Son : Father

> - (id)init { > if (self = [super init]) { > NSLog(@"%@", NSStringFromClass([self class])); // Son > NSLog(@"%@", NSStringFromClass([super class])); // Son > } > return self; >} > @end > // Parse: > self is a hidden argument to the class that points to the instance of the class in which the method is being called. > super is a Magic Keyword, which is essentially a compiler identifier and refers to the same message receiver as self. > > The difference is that super tells the compiler to call the class method to the superclass method, not the class method. If you call [self class] or [super class], the object that receives the message is the current Son *obj object.Copy the code
  1. Write a complete proxy, including declaration, implementation
// create @protocol MyDelagate @required -(void)eat:(NSString *)foodName; @optional -(void)run; @end // declare.h @interface person: M @implementation Person - (void)eat (NSString *)foodName {NSLog(@" eat: %@!") , foodName); } - (void)run { NSLog(@"run!" ); } @endCopy the code
  1. What are the functions of isKindOfClass, isMemberOfClass, and selector

    IsKindOfClass: Specifies that an object belongs to or inherits from a type. IsMemberOfClass: Indicates that an object belongs to a certain type. Selector: Gets the entry address of a function in memory by a method name.

  2. The difference between delegate and Notification

    1). Both are used to deliver messages, the main difference being that one is one-to-one and the other is one-to-many. 2). Notification realizes one-to-many message forwarding by maintaining an array. 3). The delegate needs to establish a connection between the two, otherwise it cannot call the methods of the delegate. Notification does not require a connection between the two.

  3. What is a block?

    Closures (blocks) : Closures are anonymous functions that retrieve local variables of other functions.

  4. Block passes values backwards

* Values can be passed between controllers using proxies or blocks. Using blocks is relatively simple. * Implement the following code in the touchesBegan: method of the previous controller. // OneViewController.m TwoViewController *twoVC = [[TwoViewController alloc] init]; Twovc. valueBlcok = ^(NSString * STR) {NSLog(@"OneViewController gets value: %@", STR); }; [self presentViewController:twoVC animated:YES completion:nil]; // twoViewController.h (declare a block property in the.h file) @property (nonatomic,strong) void(^valueBlcok)(NSString * STR); // TwoViewController.m (.m) - (void) Touches began :(NSSet *) Touches withEvent:(UIEvent *)event {// Touches: call block if (_valueBlcok) { _valueBlcok(@"123456"); }}Copy the code
  1. Block

    1). __week (); __weak Typeof (self) weakSelf = self; __weakType (self) weakSelf = self; 2). If the delay function is called inside the block and the weak pointer is used, the pointer cannot be retrieved because it has been destroyed, and the weak pointer needs to be re-referenced inside the block. __strong typeof(self) strongSelf = weakSelf; 3). If you need to change an external stack variable inside a block, you need to use __block to modify the external stack variable.

  2. Under what circumstances does BAD_ACCESS occur?

    A: This kind of problem is often encountered during development. The reason is to access the wild pointer, such as access to the freed object member variables or send messages, infinite loop, etc.

  3. LLDB (GDB) common console debugging commands?

    1).p outputs the basic type. If it is a print command, the type needs to be specified. P (int)[[[self view] subviews] count] 2). Is short for print-object Po [self view] 3). Expr dynamically executes the specified expression during debugging and prints the result. Often used to modify the value of a variable during debugging. 5).brl: short for breakpoint list

  4. How do you usually use Instruments?

    1). Time Profiler; 2). Zombies: Checks for access to zombie objects, but this tool only checks from the top down. 3).allocations: Checks memory and the people who wrote the algorithm use this Allocations. Leaks: Check memory to see if there are any memory Leaks

  5. What are the common data storage methods in iOS?

    There are four data storage schemes: NSUserDefault, KeyChain, File, and DB. There are three types of File: writeToFile: Atomically:, Plist, and NSKeyedAchiever (archive) DB includes SQLite, FMDB, and CoreData

  6. What is the sandbox directory structure for iOS?

    Sandbox structure: 1. appname. app directory: This is the package directory of the application, containing the application itself. Because applications must be signed, you cannot make changes to the contents of this directory at run time that might prevent the application from starting. 2. Documents: You should write all application data files to this directory. This directory is used to store user data. ICloud backup directory. 3. Library directory: There are two subdirectories in this directory: The Preferences directory: contains the Preferences files for the application. Instead of creating preferences files directly, you should use the NSUserDefaults class to get and set the application’s preferences. The Caches directory: Used to hold application-specific support files that hold information needed to restart the application. Subfolders can be created. Can be used to place data that you want to be backed up but don’t want to be seen by users. All folders in this path, except for Caches, are backed up by iTunes. 4. TMP: Stores temporary files that will not be backed up, and the data in this file may be deleted at any time.

  7. What are the ways of iOS multithreading?

    A: pthread, NSThread, GCD, NSOperation

  8. GCD and NSOperation:

    GCD and NSOperation are both used to implement multi-threading: GCD is based on the low-level API of THE C language, GCD is mainly used in combination with blocks, and the code is simple and efficient. NSOperation belongs to the Objective-C class and is a higher level of encapsulation based on the GCD. Complex tasks are generally implemented using NSOperation.

  9. Write the method code from the child thread back to the main thread using the GCD method

    A: dispatch_sync(dispatch_get_main_queue(), ^{});

  10. How to synchronize several asynchronous calls with GCD? (for example, load multiple images asynchronously according to several urls, and then synthesize a whole image after downloading)

    // Append blocks to the Global Group Queue using the Dispatch Group. If all of these blocks are completed, the terminating blocks in the Main Dispatch Queue will be executed.

> dispatch_group_t group = dispatch_group_create(); > dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); > dispatch_group_async(group, queue, ^{/* load image 1 */}); > dispatch_group_async(group, queue, ^{/* load image 2 */}); > dispatch_group_async(group, queue, ^{/* load image 3 */}); > dispatch_group_notify(group, dispatch_get_main_queue(), ^{> // Merge images >});Copy the code
  1. What does dispatch_barrier_async do?
Function definition: dispatch_barrier_async(dispatch_queue_t queue, dispatch_block_t block); Functions: 1. It is executed after the preceding task is finished, and the following task is executed after it is finished. Dispatch_queue_t queue = dispatch_queuE_CREATE ("myQueue", DISPATCH_QUEUE_CONCURRENT); Dispatch_async (queue, ^{// 1.2 is parallel NSLog(@" task 1, %@",[NSThread currentThread]); }); Dispatch_async (queue, ^{NSLog(@" task 2, %@",[NSThread currentThread]); }); Dispatch_barrier_async (queue, ^{NSLog(@" task barrier, %@", [NSThread currentThread]); }); Dispatch_async (queue, ^{// these two are simultaneous NSLog(@" task 3, %@",[NSThread currentThread]); }); Dispatch_async (queue, ^{NSLog(@" task 4, %@",[NSThread currentThread]); }); // Task 1, task 2, task 3, task 4.Copy the code
  1. How does the following code run?
- (void)viewDidLoad { [super viewDidLoad]; NSLog(@"1"); dispatch_sync(dispatch_get_main_queue(), ^{ NSLog(@"2"); }); NSLog(@"3"); } // Output only: 1. (Main thread deadlock)Copy the code
  1. What is the RunLoop

    • Literally, run a loop, run a circle
    • Inside, it is a do-while loop that continuously processes tasks (such as Source, Timer, Observer).
    • A thread corresponds to a RunLoop, which basically keeps the program running and handles various events in the app.
    • With Runloop, you can save CPU resources and improve performance by running while you need to.

    The run loop for the main thread is started by default. In the iOS app, Int main(int argc, char * argv[]) {@autoreleasepool {return UIApplicationMain(argc, argv, nil, argv) NSStringFromClass([AppDelegate class])); }} RunLoop learning summary

  2. Tell me what you think of Runtime

    Runtime, also called Runtime, is a set of low-level C language API, which is one of the core of iOS internal, we usually write OC code, the bottom is based on it to implement.

  3. What is the Runtime implementation mechanism, how is it used, and what is it used for?

    2). Runtime mechanism, which is a set of C language library. 3). In fact, all of the OC code we write eventually turns into runtime library stuff. Such as: // OC is a dynamic language; // OC is a dynamic language; // OC is a dynamic language; // OC is a dynamic language; // OC is a dynamic language. Each method is dynamically converted to a message at run time, i.e., objc_msgSend(Receiver, selector). // [stu show]; Objc_msgSend (stu, @selector(show)); objc_msgSend(stu, @selector(show)); 4). Therefore, it can be said that Runtime is the underlying implementation of OC, is the executor behind OC. What can you do with the Runtime library? The Runtime library contains apis related to classes, member variables, and methods. For example: (1) get all member variables in a class. (2) Dynamically add member variables to the class. (3) Dynamically add new methods to the class. (4) Dynamically change the class method implementation. (Method Swizzling) So, with Runtime, you can change it any way you want. IOS: Learn about Runtime

  4. What is Method Swizzle (Dark Magic) and when is it used?

    1). If you want to change the implementation of a Method in the absence of a class implementation source code, you can override it by inheriting it, and preemption by using a class-named Method. 2). Method Swizzle is the process of changing the implementation of an existing selector. Calls to methods in OC can be made at runtime by changing, by changing the mapping between the selector and the final function in the class’s schedule. 3). Call a method in OC that sends a message to an object. The only way to find the message is by the selector name. Using the dynamic characteristics of OC, we can realize the implementation of the method corresponding to the sneaker selector at run time. 4). Each class has a method list containing the selector name and the method implementation mapping. IMP is a bit like a function pointer, pointing to a specific method implementation. 5). We can use method_exchangeImplementations to swap IMP for 2 methods. 6). We can use class_replaceMethod to modify the class. 7). We can directly set IMP of a method with method_setImplementation. 8). It’s all about the IMP with the selector.

  5. What does the _objc_msgForward function do, and what happens if you call it directly?

    Answer: _objc_msgForward is IMP type, used for message forwarding: when a message is sent to an object, but it is not implemented, _objc_msgForward tries to do message forwarding.

  6. What is TCP/UDP?

    TCP: transmission control protocol. UDP: user data protocol. TCP is connection-oriented and requires a three-way handshake to establish a connection. It is a reliable transport layer protocol. UDP is connectionless. Data transmission is unreliable. It just sends whether it receives or not. Simply put, TCP focuses on data security, while UDP transmits data faster but with less security.

  7. Communication Underlying Principle (OSI seven-layer model)

    OSI uses layered structured technology, which is divided into seven layers: physical layer, data link layer, network layer, transport layer, session layer, presentation layer and application layer.

  8. What about XMPP?

    XMPP is an open real-time communication protocol based on XML. Simply put, XMPP is a protocol, a specification. That is, when you upload something on the Internet, XMM is the format that specifies the size of your upload.

  9. What is the method of creating a thread in OC? If the code is executed in the main thread, what is the method?

/ / create a thread method - [NSThread detachNewThreadSelector: nil toTarget: nil withObject: nil] - [self performSelectorInBackground: nil withObject:nil]; - [[NSThread alloc] initWithTarget:nil selector:nil object:nil]; - dispatch_async(dispatch_get_global_queue(0, 0), ^{}); - [[NSOperationQueue new] addOperation:nil]; / / main thread that executes code method - [self performSelectorOnMainThread: nil withObject: nil waitUntilDone: YES]; - dispatch_async(dispatch_get_main_queue(), ^{}); - [[NSOperationQueue mainQueue] addOperation:nil];Copy the code
  1. What’s the reuse mechanism for tableView?

    A: UITableView saves memory by reusing cells: By specify a reuse identifier for each cell, which specifies the types of cell, when the cell slide out of the screen on the screen, the system will add the cell to reuse the queue, waiting to be reused, when there is a new cell from the outside into the screen inside, look have found from the reuse of the queue can reuse a cell, if any, will bring them here to use, If not, create one and use it.

  2. Write a thread-safe singleton pattern in pseudocode

static id _instance;
    + (id)allocWithZone:(struct _NSZone *)zone { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{
           _instance = [super allocWithZone:zone];
       }); return _instance;
    } 

    + (instancetype)sharedData { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{
           _instance = [[self alloc] init];
       }); return _instance;
    }

     - (id)copyWithZone:(NSZone *)zone { return _instance;
    }
Copy the code
  1. How to achieve view deformation?

    A: Modify the Transform property of the view.

  2. Which two gestures in the common subclass of gesture types of the gesture object base class UIGestureRecognizer are executed only once after they occur?

    A: UITapGestureRecognizer UISwipeGestureRecognizer is one-time gesture, gestures, the response will only perform a.

  3. Common methods for strings:

    NSString str = @”abc123″; NSArray arr = [str componentsSeparatedByString:@””]; // Split the original string into two parts and store them in an array. @[@”abc”, @”123″];

  4. How to add rounded corners to UIImageView in high performance?

Bad solution: Using the following method 'forces Core Animation to render the off-screen drawing of the screen ahead of time, which negatively affects performance' and can cause delays. The self. The view. The layer. The cornerRadius = 5.0 f; self.view.layer.masksToBounds = YES; * the correct solution: use the drawing technology - (UIImage *) circleImage {/ / NO representative transparent UIGraphicsBeginImageContextWithOptions (self. The size, NO, 0.0); / / get the context CGContextRef CTX = UIGraphicsGetCurrentContext (); Rect = CGRectMake(0, 0, self.size.width, self.size.height); CGContextAddEllipseInRect(ctx, rect); / / cutting CGContextClip (CTX); [self drawInRect:rect]; UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); / / close the context UIGraphicsEndImageContext (); return image; } * Another option is to "cut" the image using bezier curves and add rounded corners to the UIImageView, which is also done by drawing techniques. UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; imageView.center = CGPointMake(200, 300); UIImage *anotherImage = [UIImage imageNamed:@"image"]; UIGraphicsBeginImageContextWithOptions (imageView. Bounds. The size, NO, 1.0); [[UIBezierPath bezierPathWithRoundedRect:imageView.bounds cornerRadius:50] addClip]; [anotherImage drawInRect:imageView.bounds]; imageView.image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); [self.view addSubview:imageView];Copy the code
  1. How do you encapsulate a view
2). Create a model related to the view, and then pass model data to the View. */ - (instancetype)initWithFrame:(CGRect)frame {if(self = [super] initWithFrame:frame]) { [self setupUI]; } return self; } /** * initWithCoder:(NSCoder *)aDecoder {if(self = [super initWithCoder:aDecoder]) { [self setupUI]; } return self; } - (void)setupUI {// initialize code}Copy the code
  1. What are the differences between THE HTTP POST and GET methods?

    1. GET is used to request data from the server, and POST is used to submit data. 2. GET request. POST requests do not have a length limit

  2. This section briefly describes the mechanism of sending system messages in APNS

    APNS advantage: it eliminates the behavior of keeping a long connection in the background to receive notifications like Android. It is replaced by iOS and APNS with a long connection. APNS principle: 1). The application registers in the notification center, and the iOS system requests APNS to return the device Token 2). 3). The server sends the content and device to be pushed to APNS 4). APNS finds the device according to the device token, and iOS displays the pushed content according to the APPID

77. Several methods for ios development to backpass values

The first: proxy value passing

The second controller: @ protocol WJSecondViewControllerDelegate - (void) changeText (nsstrings *) text; @end @property(nonatomic,assign)iddelegate; - (IBAction)buttonClick:(UIButton*)sender { _str = sender.titleLabel.text; [self.delegate changeText:sender.titleLabel.text]; [self.navigationController popViewControllerAnimated:YES]; } first controller: - (IBAction)pushToSecond:(id)sender { WJSecondViewController *svc = [[WJSecondViewController alloc]initWithNibName:@"WJSecondViewController" bundle:nil]; svc.delegate = self; svc.str = self.navigationItem.title; [self.navigationController pushViewController:svc animated:YES]; [svc release]; } - (void)changeText:(NSString *)text{ self.navigationItem.title = text; }Copy the code

The second type: notification pass value

The first controller: [[NSNotificationCenter defaultCenter] addObserver:self Selector :@selector(limitDataForModel:) name:@"NOV" object:nil]; - (void)limitDataForModel:(NSNotification *)noti{ self.gamesInfoArray = noti.object; } Second controller: // Send notification [[NSNotificationCenter defaultCenter] postNotificationName:@"NOV" object:gameArray];Copy the code

The third: singletons pass values

Single is a singleton class and has a string type property titleName on the second controller:  - (IBAction)buttonClick:(UIButton*)sender { Single *single = [Single sharedSingle]; single.titleName = sender.titleLabel.text; [self.navigationController popViewControllerAnimated:YES]; } First controller: - (void)viewWillAppear (BOOL)animated{[super viewWillAppear:animated]; Single *single = [Single sharedSingle]; self.navigationItem.title = single.titleName; }Copy the code

Fourth: Block pass value

Second controller: @Property (nonatomic,copy) void (^changeText_block)(NSString*); - (IBAction)buttonClick:(UIButton*)sender { _str = sender.titleLabel.text; self.changeText_block(sender.titleLabel.text); [self.navigationController popViewControllerAnimated:YES]; } first controller:  - (IBAction)pushToSecond:(id)sender { WJSecondViewController *svc = [[WJSecondViewController alloc]initWithNibName:@"WJSecondViewController" bundle:nil]; svc.str = self.navigationItem.title; [SVC setChangeText_block: ^ (STR) nsstrings * {> self. The navigationItem. Title = STR;}]. [self.navigationController pushViewController:svc animated:YES]; }Copy the code

Extern; extern; extern; extern

The second controller: extern NSString * BTN; - (IBAction)buttonClick:(UIButton*)sender { btn = sender.titleLabel.text; [self.navigationController popViewControllerAnimated:YES]; } first controller: NSString * BTN = nil; - (void)viewWillAppear:(BOOL)animated{ [super viewWillAppear:animated]; self.navigationItem.title = btn; }Copy the code

Sixth: KVO pass value

First controller: - (void)viewDidLoad {[super viewDidLoad]; _vc =[[SecondViewController alloc]init]; //self listens to the textValue property in vc [_vc addObserver:self forKeyPath:@"textValue" options:0 context:nil]; } 选 项 controller: - (IBAction)buttonClicked:(id)sender {self.textValue = self.textField. [self.navigationController popViewControllerAnimated:YES]; }Copy the code

A brief introduction to several ways of method delay execution in iOS development

Method1. PerformSelector method

Method2. NSTimer timer

Method3. NSThread thread sleep

Method4. GCD


Common deferred execution method

  • (void)delayMethod{ NSLog(@”delayMethodEnd”);

Method1: performSelector

[self performSelector:@selector(delayMethod) withObject:nil/* Can pass any type argument */ afterDelay:2.0]; Note: This method is a non-blocking execution, no way to cancel execution is found. > Program Run end > 2015-08-31 10:56:59.361 CJDelayMethod[1080:39604] DelayMethodStart2015-08-31 10:56:59.363 CJDelayMethod[1080:39604] NextMethod2015-08-31 10:57:01.364 CJDelayMethod[1080:39604] delayMethodEndCopy the code

Method2: NSTimer timer

NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval: 2.0 target: self selector: @ the selector (delayMethod) the userInfo: nil repeats:NO]; '- (void)invalidate;' - (void)invalidate; 2015-08-31 10:58:10.182cjDelayMethod [1129:41106] DelayMethodStart2015-08-31 10:58:10.183 CJDelayMethod[1129:41106] NextMethod2015-08-31 10:58:12.185 CJDelayMethod[1129:41106] delayMethodEndCopy the code

Method3: Sleep for the NSThread thread

[NSThread sleepForTimeInterval: 2.0]; Note: this method is a blocking execution mode, it is recommended to be executed in the child thread, otherwise the interface will be stuck. There are still times when you need to block execution, such as when the welcome screen needs to sleep for 3 seconds before you can get to the home screen. No cancellation mode found. > End of program run > 2015-08-31 10:58:41.501 CJDelayMethod[1153:41698] DelayMethodStart2015-08-31 10:58:43.507 CJDelayMethod[1153:41698] nextMethodCopy the code

Method4: GCD

__block ViewController/* Master controller */ *weakSelf = self; Dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0/* delayed execution time */ * NSEC_PER_SEC)); dispatch_after(delayTime, dispatch_get_main_queue(), ^{ [weakSelf delayMethod]; }); Note: This method can select the thread of execution as an argument and is a non-blocking method of execution. No cancellation mode found. > End of program run > 2015-08-31 10:59:21.652 CJDelayMethod[1181:42438] DelayMethodStart2015-08-31 10:59:21.653 CJDelayMethod[1181:42438] nextmethod 2015-08-31 10:59:23.653 CJDelayMethod[1181:42438] delayMethodEndCopy the code
For the complete code, see: > // > // createdcontroller. M > // CJDelayMethod > // > // Created by chenjie on 8/31/15. > // Copyright (c) 2015 chenjie.all rights reserved. > // > > # import "ViewController.h" > > @interface ViewController () > @property (nonatomic, strong) NSTimer *timer; > @end > @implementation ViewController* > > *`- (void)viewDidLoad { `* > > *` [super viewDidLoad]; `* > > *` NSLog(@"delayMethodStart"); `* > > *` [self methodOnePerformSelector]; // `* > > *` [self methodTwoNSTimer]; // `* > > *` [self methodThreeSleep]; //`* > > *` [self methodFourGCD]; `* > > *` NSLog(@"nextMethod"); '* > > *' - (void)methodFiveAnimation{' * > > * '[UIView animateWithDuration:0 Delay :2.0 options:UIViewAnimationOptionAllowUserInteraction animations:^{ } completion:^(BOOL finished) { `* > > *` [self delayMethod]; `* > > *` }]; `* > > *`}` > `- (void)methodFourGCD{ `* > > *` __block ViewController`*`weakSelf = self; Dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)); dispatch_after(delayTime, dispatch_get_main_queue(), ^{ ` > > ` [weakSelf delayMethod]; '> >'}); '> >' - (void)methodThreeSleep{' > > '[NSThread sleepForTimeInterval:2.0]; ` > > `} ` > > ` - (void) methodTwoNSTimer {` > > ` NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval: 2.0 target: the self  selector:@selector(delayMethod) userInfo:nil repeats:NO]; ` > > `}` > > `- (void)methodOnePerformSelector{` > > ` [self performSelector:@selector(delayMethod) WithObject :nil/* Passable argument of any type */ afterDelay:2.0]; ` > > `}` > > `- (void)delayMethod{` > > ` NSLog(@"delayMethodEnd"); ` > > `}` > `- (void)didReceiveMemoryWarning { ` > > ` [super didReceiveMemoryWarning]; ` > > ` // Dispose of any resources that can be recreated.` > > `}` > > `@end`Copy the code

  1. NSPersistentStoreCoordinator NSManaged0bjectContext and NSManaged0bject of those who need to create or pass in the thread

    Answer: NSPersistentStoreCoordinator is persistent store coordinator, is mainly used for coordinating managed object context and the relationship between the persistent storage. Ns-managed ObjectContext uses the coordinator’s managed object model to save data to a database, or to query data.

  2. Have you ever done any work related to network processing and communication? If so, could you describe the implementation strategy in detail?

    A: NSOperation is used to send asynchronous network requests, NSOperationQueue is used to manage the number and priority of threads, and the bottom layer is NSURLConnetion.

  3. Have you ever used Runtime Programming in Objective-C? If so, what did you do with it? Can you remember the associated header file or the name of any of the methods you used?

    A: The important feature of objecitve-c is Runtime. You can see the methods under #import. You’ve used objc_getClass() and class_copyMethodList() to get the private API. Use Method method1 = class_getInstanceMethod(CLS, sel1); Method method2 = class_getInstanceMethod(cls, sel2); method_exchangeImplementations(method1, method2); The code exchanges two methods, which are used when writing Unit Test.

  4. The series starting with Core. Whether CoreAnimation and CoreGraphics have been used. What is the connection between the UI framework and the CA and CG frameworks? What animations or graphics have you done in CA and CG, respectively. (A little bit of Quartz if you need to)

    A: The UI framework has CoreAnimation at the bottom, and CoreGraphics at the bottom of CoreAnimation.

    UIKit
    Core Animation
    Core Graphics
    Graphics Hardware
    2. Use CA to unwrap the menu menu (lame)
  5. Have you used CoreText or CoreImage? If so, tell us about your experience with CoreText or CoreImage.

    A: CoreText can solve the problem of complex text content layout. CoreImage can process images and add various effects to them. The experience is powerful and complex.

  6. What is an automatic release pool and how does it work

    Answer: When you send an AutoRelease message to an object, Cocoa puts a reference to that object into the latest autorelease. It is still an OC object, so other objects in the scope defined by the automatic release pool can send messages to it. When the program reaches the end of the scope, the automatic release pool is released and all objects in the pool are released.

  7. What are the differences and usages between NSNotification and KVO? Is there any implementation difference between when you should use advice and when you should use KVO? Is it possible to do something similar with a protocol and a delegate (or an Array for a delegate)? If so, what are the potential problems? If not, why not? (Although protocol and delegate stuff is pretty bad…)

    Answer: NSNotification is the implementation of notification mode in iOS. The full name of KVO is key-value Observing. It is based on KVC (key-value coding), which is a mechanism for accessing attribute variables by attribute name. For example, NSNotification can be used to notify multiple Controller objects of changes in the Module layer. You can use KVO if you only want to observe a property of an object. In the case of the delegate pattern, in the design pattern there is an object adapter pattern where a delegate points to an object, which is a one-to-one relationship, whereas in the notification pattern it is often a one-to-many relationship. In delegate mode, it’s technically possible to now change the delegate to point to objects, but it’s not recommended. It can be confusing if a delegate keeps changing to point to different objects.

  8. Have you ever used NSOperationQueue? If so, why did you use NSOperationQueue and what did you implement? Please describe the differences and similarities between it and G.C.D. (Hint: both can be described in terms of their implementation mechanism and scope of application).

    A: NSOperationQueue is used to manage subclassed NSOperation objects and control the number of concurrent threads. Both GCD and NSOperation can implement thread management. The difference is that NSOperation and NSOperationQueue are object-oriented abstractions of multiple threads. The advantage of using NSOperation in a project is that NSOperation is a high abstraction of threads. Using NSOperation in a project will make the program structure of the project better. The design idea of subclassing NSOperation has the advantages of object-oriented (reuse, encapsulation), which makes the implementation support multi-threading, and the interface is simple. Recommended for complex projects. The advantage of using GCD in a project is that GCD itself is very simple and easy to use. For non-complex multi-threaded operations, it will save the amount of code, and the use of Block parameter will make the code more readable, so it is recommended to use it in a simple project.

  9. Now that G.C.D is mentioned, what should I pay attention to when using G.C.D and block? Are they the same thing? Is there any difference between the behavior and usage of blocks in ARC and traditional MRC?

    GCD is Grand Central Dispatch, which is an open source library for threads. Blocks are closures, which are functions that can read variables inside other functions.

  10. What do you think are the greatest strengths and weaknesses of Objective-C? As for the deficiencies, is there a way available to bypass these deficiencies to implement the requirements? If possible, have you considered or practiced reimplementing some of the functions of OC, and if so, how?

> a: the biggest advantage is its runtime features, there is no namespace, for naming conflicts, can use long nomenclature or special prefix to solve, if is the introduction of naming conflicts between third-party libraries, you can use the link command and flag to resolve conflicts.Copy the code
  1. Have you implemented a framework or library for others to use? If so, talk about your experience building the framework or library; If not, imagine and design the framework’s public API, and figure out how to do it and what you need to pay attention to to make it easy for others to use your framework.
> answer: Abstract and encapsulation, easy to use. The first is to have a full understanding of the problem, such as building a file decompression compression framework, from the user's point of view, just focus on sending a decompression request to the framework, the framework completes the complex file decompression operation, and in the appropriate time to notify is oh sad, such as decompression completed, decompression error, etc. Build the relationships of objects within the framework, making them more robust and easy to change through abstractions. The second is the documentation of the API.Copy the code

Second, third-party framework

  1. Analysis of UNDERLYING principles of AFNetworking

    AFNetworking is an encapsulation of NSURLSession and NSURLConnection(deprecated in iOS9.0). 1). AFHTTPRequestOperationManager: internal packaging is NSURLConnection, responsible for sending the network request, the most used a class. (3.0 deprecated) 2).afHttpsessionManager: The internal encapsulation is NSURLSession, responsible for sending network requests, the most used class. 3). AFNetworkReachabilityManager: real-time monitoring the state of the network tools. The utility class can detect changes in the current network environment. 4). AFSecurityPolicy: network security tool class, mainly for HTTPS service. 5). AFURLRequestSerialization: serialization tool class, the base class. Convert the uploaded data to THE JSON format (AFJSONRequestSerializer). Not much. 6). AFURLResponseSerialization: deserialization tools; Base class. Use more: 7).afjsonresponseserializer; JSON parser, default parser. Universal parser; Data types other than JSON and XML, directly return binary data. The server returned data do not do any processing. 9). AFXMLParserResponseSerializer; XML parser;

  2. Describe the logic in SDWebImage to load an image to a UIImageView

    SDWebImage for UIImageView classification provides a UIImageView + WebCache. H, this classification is one of the most commonly used interface sd_setImageWithURL: placeholderImage:, The placeholder image will be displayed before the real image appears, and will be replaced when the real image is loaded. The process of image loading is roughly as follows: 1. First, it will search for the corresponding cache of the image in SDWebImageCache. It will take the URL as the index of the data and first look for the corresponding cache in the memory. If the cache is not found, it will continue to query the corresponding data in the disk using the KEY processed by MD5. If it is found, the disk data will be loaded into memory and the image will be displayed 3. If it is not found in either memory or disk cache, a request is sent to the remote server to start downloading Image 4. 5. The whole process of obtaining the image is executed in the child thread. After obtaining the image, return to the main thread to display the image SDWebImage Principle: call the method of category: 1. Look for the image in memory (dictionary) that has been loaded during the course of this application and use it directly. 2. Find the image in the sandbox (when the image was loaded during the previous use of the program), find it, use it, and cache it in memory. 3. Get, use, cache to memory, cache to sandbox from network.

Reference: SDWebImage internal implementation process

  1. Alliance Statistics Indicates all interface statistics functions

    APP startup speed, APP stay on page time, etc

Three, algorithm

1. Swap the values of A and B in two ways without using an intermediate variable

Void swap(int a, int b) {int temp = a; a = b; b = temp; Void swap(int a, int b) {a = a + b; b = a - b; a = a - b; } // 3. Void swap(int a, int b) {a = a ^ b; b = a ^ b; a = a ^ b; }Copy the code

2. Find the greatest common divisor

Int maxCommonDivisor(int a, int b) {int Max = 0; for (int i = 1; i <=b; i++) { if (a % i == 0 && b % i == 0) { max = I; } } return max; } /** 2. */ maxCommonDivisor(int a, int b) {int r; while(a % b > 0) { r = a % b; a = b; b = r; } return b; } // extension: least common multiple = (a * b)/ greatest common divisorCopy the code

3. Simulate stack operation

#include #include #include #include #include #include #include Static int data[1024] = static int data[1024]; Static int count = 0; Push void push(int x){assert(! full()); Data [count++] = x; Int pop(){assert(! empty()); return data[--count]; Int top(){assert(! empty()); return data[count-1]; Bool full() {if(count >= 1024) {return 1; } return 0; Bool empty() {if(count <= 0) {return 1; } return 0; } int main(){// push for (int I = 1; i <= 10; i++) { push(i); } // leave the stack while(! empty()){ printf("%d ", top()); // Pop (); } printf("\n"); return 0; }Copy the code

4. Sorting algorithm

The selection sort, bubble sort, and insertion sort algorithms can be summarized as follows: * All divide the array into sorted and unsorted parts. 1\. Select sort to define the sorted part on the left, and then select the smallest element of the unsorted part to exchange with the first element of the unsorted part. 2\. Bubble sort defines the sorted part at the right end, and performs an exchange during the process of traversing the unsorted part, swapping the largest element to the right end. 3\. Insertion sort defines the sorted part on the left, and inserts the first element of the unsorted part into the appropriate place for the sorted part.Copy the code

* select sort /** * [Select sort] : the most value appears at the beginning ** 1st run: find the smallest (large) number among n to switch positions with the first number * 2nd run: find the smallest (large) number among n to switch positions with the second number * repeat the operation… The third, the fourth… The number exchange position * n-1 trip, finally can realize the ascending (descending) order of data. * / void selectSort(int arr, int length) { for (int i = 0; i < length – 1; For (int j = I + 1; j < length; J++) {/ / times if comparing (arr [I] > arr [j]) {int temp = arr [I]; arr[i] = arr[j]; arr[j] = temp; }}}} * bubble sort / * [bubble sort] : compare the two adjacent elements in pairs, after the comparison, the most value appears at the end * the first time: compare the two adjacent numbers in turn, constantly exchange (before the decimal, after the large number put) advance one by one, the most value finally appears at the NTH element position * the second time: Compare the two adjacent numbers in turn, constantly switching (before the decimal number, after the large number) advance one by one, the most value finally appears in the n-1 element position *…… … */ void bublleSort(int *arr, int length) {for(int I = 0; i < length – 1; For (int j = 0; int j = 0; j < length – i – 1; J++) {/ / times if comparing (arr [j] > arr [j + 1]) {int temp = arr [j]; arr[j] = arr[j+1]; arr[j+1] = temp; }}}}


Reference: 8 sorting algorithm illustrated commonly used algorithm OC implementation


5. Double search (binary search)

/** * Split search: optimize the search time (without traversing all data) ** Split search: * 1> Array must be ordered * 2> Must know min and Max (know range) * 3> Dynamically calculate mid and fetch mid for comparison * 4> If mid is greater than the value we are looking for, So Max is going to be smaller than mid-1 * 5> if mid is less than the value we're looking for, Int int (int *arr, int length, int key) {int min = 0, int (int *arr, int length, int key) {int min = 0, max = length - 1, mid; while (min <= max) { mid = (min + max) / 2; If (key > arr[mid]) {min = mid + 1; } else if (key < arr[mid]) { max = mid - 1; } else { return mid; } } return -1; }Copy the code

Iv. Coding format (optimization details)

Review the code below and make the correct changes according to the iOS coding specifications

1. In Objective-C, the enum is recommended to use the NS_ENUM and NS_OPTIONS macros to define enumeration types.

// define an enumeration typedef NS_ENUM(NSInteger, BRUserGender) {BRUserGenderUnknown, // unknown BRUserGenderMale, // Gendergendergendergendergenderfemale, // gendergendergenderneuter // asexual}; @interface BRUser : NSObject @property (nonatomic, readonly, copy) NSString *name; @property (nonatomic, readonly, assign) NSUInteger age; @property (nonatomic, readonly, assign) BRUserGender gender; - (instancetype)initWithName:(NSString *)name age:(NSUInteger)age gender:(BRUserGender)gender; @end // Description: // Since the class already has an "initialization method" to set the initial values for name, age, and gender: design the @property corresponding to the object as immutable as possible: all three properties should be set to "read-only." Once the property value is set using the initialization method, it cannot be changed. // Attribute parameters should be arranged in the following order: (atomicity, read/write, memory management)Copy the code

2. Avoid using basic data types in C language. Instead, you are advised to use Foundation data types.

Int -> NSInteger unsigned -> NSUInteger float -> CGFloat animation time -> NSTimeInterval

Five, other knowledge points

  1. HomeKit, apple’s smart home platform, was launched in 2014.

  2. What is OpenGL, Quartz 2D?

    Quatarz 2D is the basic graphics tool library provided by Apple. It is only suitable for 2D graphics drawing. OpenGL is a cross-platform graphics development library. Suitable for 2D and 3D graphics drawing.

  3. Ffmpeg framework:

    Ffmpeg is audio and video processing tool, both audio and video encoding and decoding function, and can be used as a player.

  4. Talk about UITableView optimization

    1). Correctly reuse cell; 2) Design cells of uniform specifications; 3). Calculate and cache the height (layout) in advance, because heightForRowAtIndexPath: is the most frequently called method; 4). Asynchronous rendering may be the breakthrough when it encounters complex interface and performance bottleneck; 5). Swiping loads on demand, which is great for loads of pictures and network loads! 6). Reduce the hierarchy of subviews; 7). Make all views as opaque as possible and tangent circles; 8). Do not add or remove child controls dynamically. It is better to add it at initialization, and then use hidden to control whether it is displayed or not. 9). Analyze problems using debugging tools.

  5. How to implement dynamic row height for cell

    If you want each piece of data to display its own row height, you must set two properties: 1. Estimate the row height and 2. Custom row height. Set the forecast line height tableView. EstimatedRowHeight = 200. Set high definition line tableView. EstimatedRowHeight = UITableViewAutomaticDimension. For custom row height to be effective, the container view must have a bottom-up constraint.

  6. Tell me what you think about blocks

    On the stack automatically copy to the heap, block attribute modifier is copy, circular reference principle and solution. Circular references to blocks; Block code implementation; Why circular references are created; How the block strongly references self; Reference: Self reference is used in the Block code, resulting in a circular reference

  7. What is a wild pointer, a null pointer?

    Wild pointer: a pointer that points to something unknown is called an wild pointer. That is, the pointer to the pointer is uncertain, the address stored by the pointer is a garbage value, uninitialized. Null pointer: a pointer that does not point anywhere is called null. That is, the pointer doesn’t point to anything, the address that the pointer holds is an empty address, NULL.

  8. What is OOA/OOD/OOP?

    OOA (Object Oriented Analysis) — Object Oriented Design (Object Oriented Design) — Object Oriented Programming (Object Oriented Programming

  9. What is multithreading

    Multithreading is a complex concept, according to the literal meaning is the synchronization to complete various tasks, improve the efficiency of the use of resources, from the hardware, operating system and application software to see a different point of view, a multithreaded are endowed with different meaning, for hardware, now on the market most of the CPU are multicore, multi-core CPU operation multithreaded better; In terms of operating systems, it’s multitasking. The mainstream operating systems are multitasking. You can listen to music and write a blog at the same time. For applications, multi-threading makes them more responsive and can be downloaded over the network in response to user touch. In iOS applications, the initial understanding of multithreading is concurrency, which means that the original work of boiling water first, then picking vegetables, and then cooking vegetables, will become boiling water at the same time to pick vegetables, and then cooking vegetables.

  10. Multithreading in iOS

    The multithreading, iOS is multithreaded, under the framework of the Cocoa by Cocoa encapsulation, can make us more convenient in the use of threads, worked in c + + classmates threads is likely to have more understanding, such as thread creation, semaphores, and Shared variables are known, the Cocoa framework will be more convenient, it gave an encapsulation, the thread some encapsulation, This allows us to create objects that have threads of their own, objectification of threads, thereby reducing the robustness of our project provider.

> > GCD, short for Grand Central Dispatch, is an easy-to-use multithreaded class library provided at the system level with runtime features that take full advantage of multi-core hardware. > > NSOperation and Queue > > NSOperation is an abstract class. It encapsulates the details of the implementation of threading. We can manage multithreaded programs with object-oriented thinking by subclassing the object and adding NSQueue. See here: a multi-threaded Network access project based on NSOperation. > > NSThread > > NSThread is an object that controls the execution of a thread. It is less abstract than NSOperation. It is easy to get a thread and control it. But the concurrency control between nsThreads, we need to control ourselves, can be implemented through NSCondition. > > See The use of NSThread in iOS Multithreaded programming > > Other multithreading > > In Cocoa framework, notifications, timers, asynchronous functions, etc.Copy the code
  1. When do you choose to use GCD in a project and when do you choose NSOperation?

    The advantage of using NSOperation in a project is that NSOperation is a high abstraction of threads. Using NSOperation in a project will make the program structure of the project better. The design idea of subclassing NSOperation has the advantages of object-oriented (reuse, encapsulation), which makes the implementation support multi-threading, and the interface is simple. Recommended for complex projects.

> > The advantage of using GCD in projects is that GCD itself is very simple and easy to use. For non-complex multi-threaded operations, it will save the amount of code, and the use of Block parameter, it will make the code more readable, it is recommended to use in simple projects.Copy the code
  1. KVO, NSNotification, delegate and block

    • KVO is the Observer mode implemented by the Cocoa framework. It is usually used in conjunction with KVC to monitor changes in a value, such as the height of a View. Is a one-to-many relationship in which all observers are notified when a value changes.
> * NSNotification is a notification and a one-to-many usage scenario. In some cases, KVO and NSNotification are the same, both notifying each other after a state change. The characteristic of NSNotification is that the observer needs to proactively send the notification first, and then the observer registers for listening and then responds. This is a step more than KVO to send the notification, but its advantage is that listening is not limited to attribute changes, but also can be listened on a variety of state changes, listening range is wide, and the use is more flexible. > > * Delegate is something I don't want to do and delegate it to someone else. For example, if a dog needs to eat a meal, it will notify its owner via a delegate, and the owner will cook the meal, serve the meal, or pour the water for the dog. All the dog needs to do is call a delegate, and another class will do the work. So a delegate is a one-to-one relationship. > > * Block is another form of delegate, which is a form of functional programming. The use scenario is the same as that of a delegate. It is more flexible than a delegate, and the implementation of a delegate is more intuitive. > > * KVO is usually used for data and requirements are data changes, such as stock price changes. We usually use KVO (observer mode). A delegate is usually a behavior, a requirement is a need for someone to do something for me, like buying or selling a stock, so we usually use a delegate. > < p style = "max-width: 100%; clear: both; The delegate is a strong correlation, so the delegate and the agent know each other, so if you're delegating to someone to buy a stock you need to know the broker, and the broker doesn't know his or her customers. Notification is a weak correlation, good news is sent, you don't need to know who sent it to you to react accordingly, and the person who sent the message to you doesn't need to know who received it to send the message.Copy the code
  1. Four ways to execute a function on the main thread
The GCD method sends a block to the main thread queue so that the methods in the block can be executed on the main thread. Dispatch_async (dispatch_get_main_queue(), ^{// methods to execute}); * NSOperation method NSOperationQueue *mainQueue = [NSOperationQueue mainQueue]; // Main queue NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{// Methods to be executed}]; [mainQueue addOperation:operation]; * NSThread method [self performSelector:@selector(method) onThread:[NSThread mainThread] withObject:nil waitUntilDone:YES modes:nil]; [self performSelectorOnMainThread:@selector(method) withObject:nil waitUntilDone:YES]; [[NSThread mainThread] performSelector:@selector(method) withObject:nil]; RunLoop method [[NSRunLoop mainRunLoop] performSelector:@selector(method) withObject:nil];Copy the code
  1. How do I get a timer to call a class method

    • Timers can only call instance methods, but static methods can be called within this instance method.
    • When using a timer, note that the timer must be added to the RunLoop and run with the model selected. ScheduledTimerWithTimeInterval method to create a timer and join the RunLoop so can be used directly.
    • If the repeats option is selected for the timer repeats, be sure to call the timer invalid at the appropriate time. Cannot be called in dealloc because once set repeats to YES, the timer will hold self so dealloc will never be called and the class will never be released. For example, you can call it in viewDidDisappear so that the class goes into dealloc when it needs to be collected.
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerMethod) userInfo:nil repeats:YES]; -(void)timerMethod {// Call a class method [[self class] staticMethod]; } -(void)invalid { [timer invalid]; timer = nil; }Copy the code
  2. How do I override a class method

    • Implement a static method in a subclass with the same name as the base class

    • 2, do not use the class name to call, but use [self class] method to call. Calling with the class name is early binding, binding at compile time, and calling with [self class] is late binding, deciding which method to call at run time.

  3. Which thread will run when NSTimer is created

    • Use scheduledTimerWithTimeInterval created, in which thread creation will be added to the RunLoop which thread running on which thread

    • A Timer created by yourself runs in the thread’s RunLoop.

  4. The difference between ID and NSObject star

    • Id is a pointer to an objC_object structure, defined as
    typedef struct objc_object *id
    Copy the code
    • Id can be thought of as a pointer to an object. All object ids of oc can be pointed to, the compiler does no type checking, and any existing method called by the ID will not be reported at compile time. Of course, if the object referred to by the ID does not have the method, the crash will still happen.

    • NSObject star has to point to a subclass of NSObject, and it can only call a method in NSObjec or else it’s going to be cast.

    • Not all OC objects are subclasses of NSObject, and some inherit from NSProxy. The type that NSObject star points to is a subset of ID.

  5. The effect of the static keyword

  • Answer a:

    1. Static defined in the body of a function is scoped to the body of the function, and is allocated only once in memory, so its value remains the same on the next call; Static global variables in a module can be accessed by all functions in the module, but cannot be accessed by functions outside the module. 3. Staic global variables within a module can be called by other functions within the module. The scope of this function is limited within the module; 4. Static member variables in a class belong to the entire class. There is only one copy of all objects of the class, which means that all static member variables in an object of the class refer to the same address.

  • Answer two:

    Modify local variables: 1. Prolong the life cycle of local variables until the end of the program will be destroyed. 2. Local variables generate only one copy of memory and are initialized only once. 3. Change the scope of the local variable. Modify global variables: 1. Access only in this file, modify the scope of global variables, life cycle will not change 2. Avoid duplicating global variables

  • The static keyword in OC is incorrectly used

    It is not allowed to use static to modify instance variables. It is also wrong to use static to modify methods

Extern OC/extern OC/extern OC/extern OC/extern OC

  1. Overall, I think the advantages of using Swift as a programming language far outweigh the disadvantages, many of which Apple is gradually improving.
  • Advantages:

    Better type safety Support for functional programming The Swift language itself provides support for functional programming. Objc itself is not supported, but functional programming can be supported by introducing the library ReactiveCocoa. 4. Write automation scripts for OS X

  • disadvantages

    After Swift is used, the size of the App will increase by about 5-8 M, so it should be used with caution if it is sensitive to the size. The reason for the increase in size is because Swift is still changing, so Apple has not put a Swift runtime in iOS. Instead, every App has to include its Swift runtime. Xcode support is not good enough if you are using Xcode and you often get stuck or crash, this is by far the most annoying thing about using Swift, even now in Xcode 9, sometimes, so it’s up to you… It is true that Swift has not written many third-party libraries, but Objc’s third-party libraries can be bridged without much problem. It has improved a lot now… The language itself is still evolving, so every time there is a release, there will be compilation problems (at least so far), but since the 4.0 release, the changes are not as big as they were in the beta. And you can basically solve compilation problems caused by syntax changes by following Xcode prompts.

(iOS Interview Guide)