27. How does SDWebImage cache?

  • First, the cache uses a two-level cache strategy. Image caching is both internal and on disk, where memory caching is done with NSCache (NSCache is explained below).

Determine the format of the image: PNG or JPEG, and convert the image to NSData. 3. Obtain the storage path of the image.

Two, how to obtain the picture? If it cannot be found in the memory, it will look for it in the default disk directory. If it cannot be found, it will look for it in the customized disk directory. If it cannot be found in the disk directory, it will download the image. 5. Decompress the image by default to generate bitmap images. 6

How is the image decompressed? 1, determine whether the picture is a dynamic picture, if so, can not be decompressed 2, determine whether the picture is transparent, if so, 4. Create a context based on the size of the image. 5. Draw the image in the context. 6

#### connect to say NSCache

  • This NSCache is basically a system class for caching
  • Like a mutable dictionary, NSCache is thread-safe. The system classes automatically lock and release objects. Importantly, NSCache automatically releases stored objects if memory runs out, without manual intervention by the developer.
  • Take a look at the properties and methods that NSCache provides
// name @property (copy) NSString *name; //NSCacheDelegate delegate @property (Nullable, assign) id<NSCacheDelegate> delegate; - (nullable ObjectType)objectForKey:(KeyType)key; // Set key and value - (void)setObject (ObjectType)obj forKey (KeyType)key; // 0 cost /* Set key and value cost to obj value object. You can set the cost value for each object that you want to add to the cache and that corresponds to totalCostLimit, */ - (void)setObject:(ObjectType)obj */ - (void)setObject:(ObjectType)obj forKey:(KeyType)key cost:(NSUInteger)g; - (void)removeObjectForKey:(KeyType)key; // remove all key-value - (void)removeAllObjects; /* When the total cost of objects cached by NSCache is greater than this value, it automatically frees some of the objects until it is less than this value. This is not strictly limited, which means that objects stored beyond this size are not necessarily deleted. This value corresponds to the previous method */ @property NSUInteger totalCostLimit; // limits are imprecise/not strict /* Maximum number of key-values that the cache can hold is automatically released when the number is greater than this value. Non-strict limits mean that it is not necessarily deleted if the number is exceeded. */ @property NSUInteger countLimit; // limits are imprecise/not strict /* This value is associated with the NSDiscardableContent protocol, which defaults to YES when a class implements that protocol, And the object of a class are no longer means that can be released when using * / @ property BOOL evictsObjectsWithDiscardedContent; @end //NSCacheDelegate @protocol NSCacheDelegate <NSObject> @optional - (void)cache:(NSCache *)cache willEvictObject:(id)obj; @end**Copy the code

Look at this property, countLimit. This property sets the maximum number of caches. What does that mean? It’s like a stack, first in first out (FIFO). The principle. For example, if you set countLimit to 5, when you cache the sixth object, the first object will be removed. So there’s a risk, maybe a pilot, of saying, why, when you evaluate something by key, do you have to say is it nil? A: Because there is a good chance that some object is released (top) dropped.

Another possible interview question! Under what circumstances will cached objects in NSCache be released?

  • Before I answer, let’s talk about a situation where you create an NSCache object in a C, click on the phone’s Home or whatever to go into the background, and you see that the proxy method in NSCache is executed, and the NSCache object frees all objects, or if there’s a memory warning, it frees all objects. So, the answer should go something like this!
  • The NSCache itself is freed, and so are the objects stored in it.
  • Manually call the release methods removeObjectForKey and removeAllObjects
  • The number of cached objects is greater than countLimit
  • Total cache consumption is greater than totalCostLimit
  • Program into the background
  • Memory warning received

28. What is the realization principle of SDWebImage? How does it solve the problem of image confusion in tableView reuse

  • It works like this,
  • The error is that in UIImageView+WebCache this method is called every time [self sd_cancelCurrentImageLoad];

###29. Why refresh UI on main thread

  • UIKit is not a thread-safe class, so involving multiple threads working on the UI at the same time can have an impact.

  • Why not make the UIKit framework thread safe?

  • Because thread safety requires locking, and we all know that locking costs performance, processing speed, rendering speed, we usually write nonatomic at @property ourselves for high performance.

  • Given that we can set the properties of the view asynchronously, do we want these changes to take effect at the same time, or do we want to change the properties of the view at the pace of each runloop?

  • If a UITableView is removing a cell from another thread, and another thread is performing operations on the index of the cell, it may cause a crash.

  • If the background thread removes a view while the runloop cycle is still running, should the user click on the view in the main thread that is “about to” disappear? Which thread is responding?

  • In the Cocoa Touch framework, UIApplication initialization is done on the main thread. All views on the interface are on the leaf node of the UIApplication instance (memory management perspective), so all gesture interactions are handled on the main thread

30. RunTime

Class structure:

Typedef struct objc_class *Class; struct objc_class { Class _Nonnull isa OBJC_ISA_AVAILABILITY; #if ! __OBJC2__ Class _Nullable super_class OBJC2_UNAVAILABLE; const char * _Nonnull name OBJC2_UNAVAILABLE; long version OBJC2_UNAVAILABLE; long info OBJC2_UNAVAILABLE; long instance_size OBJC2_UNAVAILABLE; struct objc_ivar_list * _Nullable ivars OBJC2_UNAVAILABLE; struct objc_method_list * _Nullable * _Nullable methodLists OBJC2_UNAVAILABLE; struct objc_cache * _Nonnull cache OBJC2_UNAVAILABLE; struct objc_protocol_list * _Nullable protocols OBJC2_UNAVAILABLE; #endif } OBJC2_UNAVAILABLE;Copy the code

Classification structure

struct category_t {
    const char *name;
    classref_t cls;
    struct method_list_t *instanceMethods; // Object method
    struct method_list_t *classMethods; / / class methods
    struct protocol_list_t *protocols; / / agreement
    struct property_list_t *instanceProperties; / / property
    // Fields below this point are not always present on disk.
    struct property_list_t *_classProperties;

    method_list_t *methodsForMeta(bool isMeta) {
        if (isMeta) return classMethods;
        else return instanceMethods;
    }

    property_list_t *propertiesForMeta(bool isMeta, struct header_info *hi);
};
Copy the code

1. The difference between class_copyIvarList and class_copyPropertyList?

  • 1. Class_copyIvarList: can get all properties in. H and. M and variables declared in curly braces. The obtained property names are underlined (except in curly braces).
  • 2. Class_copyPropertyList: Only properties declared by the property can be obtained, including. M. Property names are not underlined.

What is the difference between class_ro_t and class_rw_t?

  • Class_rw_t provides the ability to extend classes at runtime,
  • Class_ro_t stores most of the information that the class has already determined at compile time.
  • Both contain information about the class’s methods, attributes (member variables), protocols, and so on, but the lists that store them are implemented differently. Simply put, class_rw_t stores a two-dimensional array for lists, and class_ro_t uses a one-dimensional array.
  • Class_ro_t is stored in the class_rw_T structure and is immutable. Holds information about the class that was determined at compile time.
  • The methods, attributes, protocols, and so on that modify classes at run time are stored in class_rw_t

31. NSNotification

  • NSNotificationCent sends notifications in the child thread, and also refreshes the UI in the main thread
// dispatch_async(dispatch_get_main_queue(), ^{// refresh UI});Copy the code
  • Does NSNotificationCenter crash if it’s not removed after it’s used up?
  • Sometimes it can cause a crash. For example, processing data or UI events in a notification event, but because of the uncertainty of the notification event causes the uncertainty of the event, there are asynchronous operations in the notification event processing can cause crashes.
  • And notification crashes are hard to detect.

What is the difference between the weak keyword and assign? (Samsara Series)

  • The word weak solves one thing, which is memory
  • The presence of weak in ARC solves some of the problems of circular references, such as the delegate and XIB controls that are wired up to be weak (strong is also possible).
  • Weak indicates a “non-owning relationship” that does not retain new values or release old ones.
  • The same applies to assign, but the more common ones are for basic data types (CGFloat or NSlnteger, etc.)
  • Assign can be used for non-OC objects as well as OC objects (used in the MRC era), but weak must be used for OC objects.

1. How to use the keyword copy?

  • Block Copy is a legacy of the MRC era. In MRC, the block inside a method is on the stack, and copy can be used to put it on the heap. ARC is optional. Strong is also optional.
  • NSString, NSArray, and NSDictionary often use copy because they have mutable subtypes. For security purposes, use the copy modifier

What is the essence of 2.@property? How ivar, getters, and setters are generated and added to this class.

  • @property = ivar + getter + setter
  • Automatic synthesis

33. What about memory management?

  • In fact, encountered this question, quite tangled, some TMD interviewers are used to screwing people, from this inside can go to death to give you high! You have to read the detailed principles of memory management, you will find that there are a lot of C++ operations, did not learn C++ people can see a 90 or 90, but also just can say a big idea, but the internal details or use C++, nonsense not to say, directly said the so-called interview answer.
  • The crude version says,
  • Version 1: Every object in memory has its own reference counter. When an object A is referenced by another object, A’s reference counter is +1, and if another object is referenced to A, A’s reference counter is +1. When one of these objects no longer refers to A, A’s reference counter will be -1. Until A’s reference count drops to zero, then no one needs it anymore, and it’s time to release it
  • Version 2: In the MRC era, objects generated by alloc copy new need to manually manage memory. The technique is returnCount reference counter to manage the timing of object release. Alloc creates object reference counter +1, retain holds relational reference counter +1, Release references the counter -1. If the current object has returnCount = 0, the object will be released in the dealloc method at the appropriate time. If the current returnCount is greater than 0, it will always be held.
  • In a slightly more detailed version, first of all, when alloc copy New generates the object, inside the underlying source code is also associated with the current object SideTable, which has three internal properties, one is a spin lock, one is a reference counter correlation, and one is a table that maintains the weak life attribute. Retain and release use key-value pairs to add and subtract the reference counter of the current object. If the current reference counter is 0, the dealloc will delete the current reference counter and release the current object.
  • For details, please seewww.jianshu.com/p/ef6d9bf8f…

miscellaneous

  • 1, imageName and imageWithContentsOfFile difference?
  • ImageWithContentsOfFile: loads images from the local directory, does not cache, occupies a small memory, and cannot load image resources inside image.xcassets. The same image is repeatedly loaded into memory
  • ImageName: loaded into memory, will be cached, occupying a large memory, the same image will not be repeatedly loaded into memory, will read image. Xcassets image resources.

Uiimages created with imageNamed are immediately added to NSCache (the decoded Image Buffer), and unused UIimages are not released until a memory warning is received. And the image with Content file will reapply memory every time, the same image will not be cached, so xcassets

  • If the same image is read repeatedly, use imageName

  • If you don’t need to read the same image repeatedly and you need low memory, use image with Content file

  • 2. Why can the view attribute connected by IBOutlet be set to weak?

  • Because of links within the Xcode put control links in a _topLevelObjectsToKeepAliveFromStoryboard private array, the array strong reference all the top level object With weak so doesn’t hurt.

    1. Why can’t I use dot syntax for id?
  • The point syntax is setter and getter methods, whereas the id class cannot determine what type of class it refers to. The setter and getter methods cannot be found, and the object of type ID can only be called with method []

  • 4. The difference between ID and NSObject?

    • Id is a pointer to the struct objc_Object structure and can point to any OC object except NSInteger, which is not an OC object.
  • In addition, the OC base class has not only NSObject, but also NSProxy virtual class. So the ID type and NSObject are not equivalent.

  • 5. OC Null vs. nil

    • NULL indicates that the pointer is NULL and is used to determine the C pointer.
    • Nil means that an OC object (pointer) is null;
    • Nil means that an OC class is empty;
    • NSNull is used to populate collection elements; This class has only one method, NULL, and is singleton;
  • 6. Spin locks and mutex

  • Similarities: Both ensure that only one thread can access shared resources at a time, ensuring system security

  • Difference:

Mutex: If the shared data has been locked by another thread, the thread will sleep to wait for the lock. Once the accessed resource is unlocked, the thread waiting for the resource will wake up. "Dispatch_semaphore" is a mutex. @synchronized is a mutex. Mutex is used when the wait time is long. If the shared data has been locked by another thread, the thread will wait for the lock in an infinite loop. Once the accessed resource is unlocked, the thread waiting for the resource will execute immediately. Spin locks are usually used for short periods of time. OSSpinLock is suitable for ** : threads wait longer for locksCopy the code
  • 7. The difference between processes and threads

  • A process is an application that is running in the system

  • Thread is an entity in the process. If a process wants to execute a task, it must have at least one thread. When the program is started, one thread will be started by default, that is, the main thread

  • A process has multiple threads

  • 8 Call timing of LayoutSubviews and drawRect

LayoutSubviews Call timing

  • Init initialization does not call the LayoutSubviews method
  • It’s called when you addsubView
  • Called when changing the frame of a View
  • Called when scrolling UIScrollView causes UIView to be rearranged
  • Manually call setNeedsLayout or layoutIfNeeded

DrawRect call timing

  • DrawRect is dropped after Controller->loadView and Controller->viewDidLoad. So don’t worry about in the controller, the View’s drawRect starts drawing.

  • 9 How can POD Install be updated from cocoaPods?

**pod install **

  • This is usually used when you first want to add a POD to a project, but can also be used when adding and removing libraries
  • Each time pod install is installed, Pod Install writes the version number of each installed POD library to the podfile. lock file and locks the current version number.
  • If pod install does not update its version library, it will download a new version or remove the current version

pod update

  • When a POD update is performed, cocoaPods does not consider the version in podfile. lock. Simply update all current libraries to the latest, and podfile. lock will update the current version number.
  • 10 Which is better for frame or navigation? why
  • Some relative layouts end up being converted to Frame absolute layouts with one more layer of transformation in between

  • IOS features from iOS 9-13

iOS9

Add UIStackView to your App

iOS10

Added operations related to notification push. Customizing notification pop-ups, customizing notification types (geographic location, interval, calendar, etc.)

iOS11

Wireless debugging

Fringe, navigation bar, safe distance, etc

iOS12

Start speed optimization

App startup speed increased by 40% keyboard response speed increased by 50% Camera startup speed increased by 70%Copy the code

iOS13

The dark pattern For details, please refer to www.jianshu.com/p/0da3b107f…


Ii. App package and startup process

App thin body

1. How does App slim down?

  • Delete stale code, delete stale XIB/SB, and delete useless image resources (LSUnusedResources for detecting unused images)
  • Lossless compression of pictures, local audio and video compression. To directly reduce the image size
  • Use webP images (slower to load, but slimmer)
  • Reduce the length of class names (try this for high performance)
  • Reduce the use of static libraries
  • Some thematic things provide download functionality, not packaged directly into the application package, load resources on demand
  • App Slicing, Bitcode, and On Demand Resources

Slicing: This process is a lean process without programmer intervention after iOS9 comes out. Simply put, we upload the IPA package to iTunes Connect, and then AppStore will slice the app into the data that a specific model wants. For example, @3x will be used by Max, and @2x will be automatically removed. Is an automatic process, Bitcode: Bitcode is an intermediate code. If an application is configured with Bitcode (Xcode7 is enabled by default), it will be recompiled in App Store Connect, etc., and then apple will optimize the executable file internally, which means we don’t need to interfere with anything or operate it. If apple has better optimizations in the future, that’s apple’s business. It has nothing to do with us. In other words, we need to download some Resources when we use them, but we need to configure them when we configure them, and we need to write some extra code, etc. When we submit them to the market, Apple internally did something to remove our on-demand resources from the pack to make it smaller for downloading. For example, if you don’t download the desert map, you can’t play the desert.

* * on – demond resource (ODR) * specific version please see principle: www.jianshu.com/p/bacedd8a3…

Or detailed version of use: www.cocoachina.com/articles/12…

About * * slicing, bitcode, on – demond resource (ODR) * * of resources blog.csdn.net/zhuod/artic…


2. What happened when the app was launched?

There are two kinds of priming. One is to start the app before, press the home button, and then click start, this start is called hot start, and the other is to start the app for the first time, or after the app is killed, it is called cold start

Follow the Settings in info.plist to load, sandbox, check permissions, etc

Load the executable file to load the dynamic library objC runtime initialization process (class registration, category registration, selector uniqueness check, etc.) initialization, including the +load method to perform the main function initialization, To applicationDidFinishLaunchingWithOptions execution of the rendering screen, to complete, viewDidAppear is presented to the user

  • Mian before

Follow the Settings in info.plist to load, sandbox, check permissions, etc

Load the executable file load the dynamic library objC runtime initialization process (class registration, category registration, selector uniqueness check, and so on) initialization, including the +load method

  • After the mian
    • As shown in figure
    • The loading process is as follows:

    Picture lost !!!!! Baidu go!


3. Optimize startup time

  • The startup time is the time when the user clicks the App icon and arrives at the first interface display.

Note: A startup time of less than 400ms is optimal, since the time between clicking on the icon and launching the Launch Screen and the Launch Screen disappearing is 400ms. The startup time cannot exceed 20 seconds; otherwise, the system will kill you.

  • Using the main function as the watershed, the startup time actually consists of two parts:
    • Before main (parses and loads the dynamic library, registers the required classes (including system classes), the methods in the Category are also registered with the applicable classes, performs the necessary initialization methods (+load methods), and so on
    • The main function to the first interface viewDidAppear:.
  • Therefore, optimization is also carried out from two aspects, I suggest that the latter should be optimized first, because the bottleneck of most apps is in their own code.

Mian function prior to startup optimization

  • Reduce the number of dynamic libraries (this is by far the most time-consuming, basically 95% + of the time)
  • Merge dynamic libraries, such as your own UI controls into your own UIKit
  • Verify whether the dynamic library is Optional or required. If the Framework exists on all versions of iOS currently supported by the App, it is set to Required, otherwise it is set to Optional because optional has some additional checks
  • Merge categories (UIView+Frame,UIView+AutoLayout merge into one)
  • Delay things that do not need to be done in the +load method to +initialize.

Startup optimization after mian starts by analyzing what happened between the execution of main and the first page display

  1. Perform didFinishLaunchingWithOptions method
  2. Initialize Window, initialize base ViewContreoller (UINavigationController+UITabViewController)
  3. Getting data (local and remote)
  4. Finally, show it to the user
  5. Reduce thread creation (As mentioned in the high Performance iOS development book, threads not only cost time to create, they also consume kernel memory, i.e. the memory space of the application. Each thread consumes approximately 1KB of kernel memory space. The duration of thread creation (excluding startup time) ranges from 4000 to 5000 microseconds, that is, 4-5 milliseconds. The time it takes to start a thread after it is created ranges from 5 to 100 milliseconds, with an average of 29 milliseconds. This is a significant time cost, especially if multiple threads are started at application startup. Threads take so long to start because of the overhead of multiple context switches. So threads also avoid abuse during development.)
  6. The more classes that merge or delete unnecessary classes (or classes) and the function objc, the slower the function starts
  7. Use as small a picture as possible in a sample acceptable to the designer
  • AppDelegate

In general, you should start with an AppDelegate

didFinishLaunchingWithOptions
applicationDidBecomeActive
Copy the code

The core idea of optimization is to delay the delay, can not delay as far as possible to put in the background to optimize.

- Logs, statistics and other events that must be configured first upon APP startup. Still in didFinishLaunchingWithOptions start it. - Project configuration, environment configuration, user information initialization, push, IM and other events, these functions must be loaded before the user enters the APP body, put him into the advertising page viewDidAppear start. - Other SDK and configuration events, since the startup time is not required, we can put them in the viewDidAppear method of the first screen, which does not affect the startup time at all. - each time with NSLog print implicitly create a Calendar, so you need to cut the business side dozen the log when starting, or only for closed beta version of the output log - try not to create and open multiple threads inside the didFinishLaunchingWithOptionsCopy the code

Reference www.jianshu.com/p/f40fdd879… The internal author of the article talked about meituan about the relevant analysis of startup optimization, seems to have been similar, remember the picture “high performance iOS application development” this book is meituan these buddies translated it, the implementation is quite similar to the book.


3. App power consumption

  • 1. The positioning
  • 2. Network request
  • 3. CPU
  • 4. The GPU
  • 5.Bluetooth

Location optimization

1. Try to avoid real-time updates

2. The positioning accuracy should not be too high

Network optimization

1. Reduce and compress network data

2. Use cache whenever possible to reduce network requests 3. Breakpoint continuation 4. Set a suitable timeout period so that users can cancel time-consuming network requests. 6. Do not perform network requests when the network is unavailable

The CPU/GPU optimization

Relevant off-screen rendering operations should be handled as far as possible to avoid memory management. Lazy loading should be used to draw images the same size as imageView to avoid redundant operations. The Timer interval should not be too short to meet the needs of threads, not too much, do not block the main thread. Make sure to refresh only when necessary. If you can refresh one cell row, refresh only one cell row.

In order to optimize power consumption, we can also do: 1. Do not use timers 2. Optimize I/O operations (read and write operations of files) 2.1 It is better not to read and write small data frequently, and it is better to read and write in batches. It provides an API for asynchronously manipulating file I/O based on GCD. The system optimizes disk access with dispatch_io

There are several points mentioned in high performance iOS application development

  • 1. CPU optimization
  • Data processing (e.g. text formatting optimization)
  • Size of data to process —- The larger display allows software to present more information in a single view, but it also means processing more data
  • Algorithms and data structures for processing data
  • Number of updates performed, especially after a data update, that triggers an update to the application’s state or UI (such as refreshing a single cell row)
  • Server data should not be processed on the client side (e.g. server string, split on the client side)
  • Load on demand (for example, tableViewcell doesn’t need to be rendered all at once, and white space in the process when sliding quickly).
  • 2, the network
  • Before making a network request, check to see if there is a network connection. (Don’t ask for the Internet when you don’t have it)
  • Avoid high-bandwidth consumption operations when WiFi is not connected (because 3G, 4G and other mobile networks consume much more power than WiFi signals). For example, video streams should be prompted in 4G or non-wifi situations.
  • 3, positioning
  • Try not to update in real time
  • The positioning accuracy should not be too high

Three, algorithm

Define related

  1. What’s the difference between a linked list and an array? What’s the difference between a linked list and a dictionary?

Arrays are stored one by one in memory, and there is no relative fixed position relationship between each node in the linked list

Once an array is declared, its size is fixed and cannot be dynamically expanded. The time complexity of array insertion and deletion is O(n), the subscript time complexity of array O(1) query is O(1), the time complexity of list O(n) query by value, both list and array are O(n).

  1. How do I detect if there are rings in a linked list?

Suppose there are two students A and B running on A track. They start from the same starting point. Suppose A is running at 2m/s and B is running at 1m/s.

The answer is simple. A will catch up with B once around the track! To extend this problem to linked lists, runways are linked lists, we can set two Pointers, A runs fast, B runs slow, if the linked list has a loop, then when the program reaches a certain state, A == B. If the list has no loops, the program will execute until a==NULL.

Swap A and B

//    int a = 10;
//    int b = 20;
//
//    a = a + b;
//    b = a - b;
//    a = a - b;
//
//    NSLog(@"a = %d , b = %d", a, b);
//
//
//    a = a*b;
//    b = a/b;
//    a = a/b;
//
//    NSLog(@"1 =====    : a = %d , b = %d", a, b);
Copy the code

###2, greatest common divisor

// int n = 20,v = 30,temp = 0,max,min; // // if (n>v) { // max = n; // min = v; // } else { // max = v; // min = n; // } // // // while (min ! = 0) { // temp = max - min; // max = min; // min = temp; // } // // NSLog(@"%d", max);Copy the code

###3, print prime numbers from 2 to 100 that are divisible except for 1 and themselves.

//    NSMutableArray *primeNumberArray =[NSMutableArray array];
//    for(int i=2; i<=100; i++) {
//
//        NSInteger n = 0;
//
//        for(int j = 1; j <= i; j++) {
//
//            if(i % j == 0) {
//                n = n + 1;
//            }
//        }
//
//        if(n == 2) {
//            [primeNumberArray addObject:@(i)];
//        }
//    }
//
//    NSLog(@"primeNumber = %@",primeNumberArray);
//
Copy the code

###4

// NSString *string = @"hei Son I am your father"; // NSMutableString *string1 = [NSMutableString string]; // for (NSInteger i = string.length; i>0; I -) {/ / [string1 appendString: [string substringWithRange: NSMakeRange (I - 1, 1)]]. // } // // NSLog(@"%@", string1); //Copy the code

###5, find the Chinese characters in the string

// for (int i = 0; i < string.length; i++) { // NSString *str1 = [string substringWithRange:NSMakeRange(i, 1)]; // const char *cStr = [str1 UTF8String]; / / if (strlen (cStr) = = 3) {/ / oc Chinese three bytes / / NSLog (@ "% @", str1); / / / /}}Copy the code

# # # # 6. Sorting

  • Bubble sort

Compare adjacent elements. If the first one is bigger than the second, swap them both.

Do the same for each pair of adjacent elements, starting with the first pair and ending with the last pair. At this point, the last element should be the largest number. Repeat this step for all elements except the last one. Keep repeating the above steps for fewer and fewer elements at a time until there are no more pairs to compare

for (int i = 0; i<result.count- 1; i++) {
        for (int j = 0; j<result.count- 1-i; j++) {
            NSInteger left = [result[j] integerValue];
            NSInteger right = [result[j+1] integerValue];
            if (left>right) {
                [result exchangeObjectAtIndex:j withObjectAtIndex:j+1]; }}}NSLog(@ "% @",result); Time order n^2)
Copy the code
  • Selection sort

Selection sort is to find the subscript of the smallest element of each traversal by iterating through the array of numbers, and then arrange them in order from the first

     //self.array = @[@2,@4,@3,@1];
     NSMutableArray *mutableArray = [self.array mutableCopy];// The oc array cannot store basic data types, so after quick assignment, the default array element is NSNumber
    if (mutableArray == nil || [mutableArray count] == 0)
    {
        return;
    }
    for (int i = 0; i < [mutableArray count]; i++)
    {
        NSInteger minIdx = i;// The default minimum index is I
        for (int j = i+1; j < [mutableArray count]; j++)// Loop through to find the index of the smallest value in the current array
        {
            if (NSOrderedAscending == [mutableArray[j] compare:mutableArray[minIdx]])//NSNumber determines the size method when mutableArray[j] 
            {
                minIdx = j;// Update the index of the smallest value in the array
            }
        }
        [mutableArray exchangeObjectAtIndex:i withObjectAtIndex:minIdx];// Swap the minimum value found at the end of each loop to the i-th bit of the array
        NSLog(@ "% @",mutableArray); The time complexity is O(n). In the worst case, it's still O(n^)2)
Copy the code
  • Ascending/descending order
NSMutableArray *priceArray = [NSMutableArray arrayWithObjects:@ "0.2".5 "@".44 "@".@ "67".@ "98.5".@ "1.55".nil];
 
[priceArray sortUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2)  {
     if ([obj1 integerValue] < [obj2 integerValue]){
         return NSOrderedAscending;
     } else {
       return NSOrderedDescending; }}]; Again, priceArray is an array in ascending order; If you want to get a descending switchreturnThe location ofCopy the code

####7 Find the nearest public View

// The parent View of all views
+ (NSArray *)superViews:(UIView *)view{
    if (view==nil) {
        return@ []; }NSMutableArray *result = [NSMutableArray array];
    while(view! =nil) {
        [result addObject:view];
        view = view.superview;
    }
    return [result copy];
}

// Compare the views in the two nodes
+ (UIView *)commonView_1:(UIView *)viewA  andView:(UIView *)viewB{
    NSArray *arr1 = [self superViews:viewA];
    NSArray *arr2 = [self superViews:viewB];
    for (NSUInteger i =0; i<arr1.count; ++i) {
        UIView *targetView = arr1[i];
        for (NSUInteger j=0; j<arr2.count; ++j) {
            if (targetView == arr2[j]) {
                returntargetView; }}}return nil;
}


// The above code can be further optimized using the hash table in the NSSet
+ (UIView *)commomView_2:(UIView *)viewA andView:(UIView *)viewB{
    NSArray *arr1 = [self superViews:viewA];
    NSArray *arr2 = [self superViews:viewB];
    NSSet *set = [NSSet setWithArray:arr2];
    for (NSUInteger i =0; i<arr1.count; ++i) {
        UIView *targetView = arr1[i];
        if ([set containsObject:targetView]) {
            returntargetView; }}return nil;
}
Copy the code

####8. Array questions: How to find two elements in an ordered array whose sum equals a given value?

NSArray *arr = @[@ "1".@ "12".13 "@".23 "@".@ "31".43 "@".52 "@".@ "66".@ "88".@ "111".@ "127".@ "199"];
[self confirmNumbers:arr total:199]; -- - (void)confirmNumbers:(NSArray *)array total:(NSInteger)totalNmuber  {
    if (array.count <= 1) { return; }

    NSInteger tempAddCount = 0;
    NSInteger tempDeleltCount = 0;

    for (int i = 0; i <= array.count; i++) {
        NSInteger tNamber = [array[tempAddCount] integerValue] + [array[array.count- 1-tempDeleltCount] integerValue];
        if (tNamber == totalNmuber) {
            NSLog(@"%ld, %ld, first element %@ - next element %@", (long)tempAddCount, (long)tempDeleltCount, array[tempAddCount] ,array[array.count-tempDeleltCount- 1]);
            break;
        } else if (tNamber < totalNmuber) {
            tempAddCount ++;
        } else {
            tempDeleltCount ++;
        }
        if (i == array.count - 1) {
            NSLog(@" Nothing matches");
            break; }}}Copy the code

Write an algorithm recursively to calculate the sum from 1 to 100.

NSLog(@"%ld"[self getSumResult:100]);

- (NSInteger)getSumResult:(NSInteger)number {
    if (number <=0 ) {
        return number;
    }
    
    return number + [self getSumResult:number - 1];
}
// The reason for poor recursive efficiency is that each call to the function (itself) has memory overhead, which affects the efficiency of CUP
Copy the code

10. Scramble an array

  NSArray* arr = @[@ "1".@ "2".@ "3"];
    arr = [arr sortedArrayUsingComparator:^NSComparisonResult(NSString *str1, NSString *str2) {
        int seed = arc4random_uniform(2);
        if (seed) {
            return [str1 compare:str2];
        } else {
            return[str2 compare:str1]; }}];Copy the code

11. The iOS array has to redo those schemes


/ / a
    NSArray *originalArr = @[@1The @2The @3The @1The @3];
    NSMutableArray *resultArrM = [NSMutableArray array];

    for (NSString *item in originalArr) {
        if (![resultArrM containsObject:item]) {
          [resultArrM addObject:item];
        }
    }
    NSLog(@"result : %@", resultArrM);
    
    
/ / 2
     NSArray *originalArr = @[@1The @2The @3The @1The @3];
    NSMutableDictionary *dictM = [NSMutableDictionary dictionary];
    for (NSNumber *n in originalArr) {
        [dict setObject:n forKey:n];
    }
    NSLog(@ "% @",[dictM allValues]);
    
3 / / solution
       NSArray *originalArr = @[@1The @2The @3The @1The @3];
    NSSet *set = [NSSet setWithArray:originalArr];
    NSLog(@"result: %@", [set allObjects]);
   
/ / four
    NSArray *originalArr = @[@1The @2The @3The @1The @3];
    NSArray *result = [originalArr valueForKeyPath:@"@distinctUnionOfObjects.self"];
Copy the code

1. What technical difficulties did you encounter during development? How is it solved?

  • But this topic is mainly the interviewer would like to know your real project experience, if you answer, what is not technical problem, but the fundamental problem that estimates also no need to talk, for example, your answer is “I always found the UITableView this control in the development process to write up more troublesome, “I’m sorry, but the best you can do is get an internship. Because you can say this question, I guess you don’t know half of the hardcore interview questions above!
  • In fact, this question is not so high, say you encountered difficulties in the real development process, the more high the better, the best is to impress the interviewer said meng, of course, if you are confident, best not to exaggerate, in case you meet someone who happens to be in the field is better?
  • For example, “when I was developing our project, I was involved in the problem of image processing. For example, the crash problem occurred when SDWebImage was used to download super large images, which was quite popular on the Internet, because decodeImageWithImage was used to compress and cache the images. In order to ensure the tableView/CollectionView interaction is more smooth, but if this method is used to load the super large image, it will backfire, and may lead to the memory consumption of G. The solution is that for the high definition image, it should be placed after the image decompression, and it is forbidden to cache the decompressed data. Here’s the code.”
- SD4. X solution [[SDImageCache sharedImageCache] setShouldDecompressImages:NO];
[[SDWebImageDownloader sharedDownloader] setShouldDecompressImages:NO];


- SD5. 0And above solution SDWebImageAvoidDecodeImage added this enumeration, mean in image compression [child thread equationself.imageView sd_setImageWithURL:self.url placeholderImage:[UIImage imageNamed:@"logo"] options:SDWebImageAvoidDecodeImage];
Copy the code
  • For more details please see also must see!

  • www.jianshu.com/p/b36e96d6d…

  • www.jianshu.com/p/64be3aed2…

  • For example, “In the development process, all the pictures used must be original pictures, the problem arises. If several pictures are super-large in ULTRA hd, and all these pictures are rendered to a canvas and the ultra HD puzzles with random shapes are carried out, this process will cause a strange problem. Are the result of the drawing is a big probability becomes a picture of a pure white without any pattern, the reason is that if you’re running within the App memory reaches a certain worth when rendering image context will get a blank picture, solution because is probability event made a render loop inside mechanism, within the scope of the specific number, If there is a draw the picture of the successful return to normal, if not correct, then a internal the clues of the App doesn’t have any response, so if production project related with images, especially involving the custom system the function of the album, best to optimize memory problems, because of the bad memory optimization problems has a lot of system BUG. And it’s hard to find the cause of the problem.

  • ** This leads the interviewer to the task of optimizing memory. Tools to optimize memory, detect memory leaks, circular reference tools, and so on. These will be described below. 支那

2. What debugging tools have you used in this process?

  • instrument
Leaks: Generally looks at memory usage, checks for leaking memory, and provides statistics on all active allocations and class object allocations of the leaking module, as well as memory address history; -Locations (Memory allocation) : Tracks the process of anonymous virtual memory and heap objects providing the class name and optional hold/release history;Copy the code

To view more

conclusion

This is a summary of the interview, in short, some questions answered more leakage, some questions ambiguous, some interviewers more solid feedback, some interviewers said the answer of Thailand is not detailed enough, anyway, this thing depends on opinion.

Finally attached a very detailed written basic knowledge of the blogger wrote some columns, personally feel very helpful! Juejin. Cn/user / 782508…

This article basically will not add new problems, if there is a mistake I will correct in time, to avoid delaying friends who need help! Last updated on 20 July 2020