The preface

Currently, more and more people are joining the iOS team, even to the point of oversupply. This year, those who have been looking for a job are likely to get a better sense of the tough job market this year, as training agencies rush to send iOS developers to employers, upsetting the ecosystem dynamics. Hypocritical once, get down to business, I offer once, comb for iOS applicant below test questions, hope can help!

Understanding and characteristics of OC

  • As an object-oriented language, OC naturally has the characteristics of object-oriented language: encapsulation, inheritance, polymorphism. It has both the features of a static language (such as C++) and the efficiency of a dynamic language (dynamic binding, dynamic loading, and so on). Overall, OC is a great programming language,
  • Objective-c has a number of Dynamic features, which can be seen in three aspects: Dynamic typing, Dynamic binding, and Dynamic loading. Dynamic — something that must not be done until run time.
  • Dynamic type: The runtime determines the type of the object. This dynamic feature is very common in everyday applications. Simply put, it is the ID type. In fact, static types are more widely used because of their inflexibility and predictability. Static types are strong, while dynamic types are weak, and the runtime determines recipients.
  • Dynamic binding: Based on dynamic typing, after an instance object is identified, its type is determined, and its corresponding properties and response messages are also fully determined.
  • Dynamic loading: According to the resources you will need to load demand, the most basic is the adaptation of different models, for example, load on Retina equipment @ 2 x pictures, and on the old some ordinary apple equipment load artwork, let program at runtime to add code modules and other resources, the user can according to need to load some executable code and resources, rather than when it starts loading all of the components, Executable code can contain new classes that are integrated with the program runtime.

This section describes basic principles of memory management

  • Before: OC memory management follows the “who creates, who releases, who references, who manages” mechanism. When creating or referencing an object, you need to send alloc, copy, and retain messages to it. When releasing the object, you need to send a release message. This is the OC’s manual management mechanism (MRC).
  • For now: After iOS 5.0, automatic management mechanism — Automatic reference counting (ARC) is introduced. The management mechanism is the same as manual mechanism, but no longer need to call retain, release, autorelease. Its compile-time features, when you use ARC, insert release and autoRelease in place; It refers to the strong and weak keywords. When the pointer variable modified by strong points to an object, the associated object will be released automatically when the pointer points to a new value or the pointer no longer exists, while the pointer variable modified by weak points to an object. When the owner of the object points to a new value or does not exist, the pointer modified by weak is automatically set to nil.
  • If you are usingalloc,copy(mutableCopy)orretianWhen you have an object, you have an obligation to send one to itreleaseorautoreleaseThe message. Other methods create objects that do not require you to manage memory.
  • Sends a packet to an objectautoreleaseInstead of destroying the object immediately, it puts the object into the automatic release pool, and when the pool is released, it sends one to every object in the poolreleaseMessage to release the object.
  • Send to an objectreleaseMessage, which does not mean that the object is destroyed, but is called when the object’s reference count is zerodeallocMethod to release the object and its own instances.
Other Matters needing attention
  • If an object has a _strong pointer to it, the object will not be released. If a pointer points out of its scope, it will be pointed to nil. If a pointer is pointed to nil, the object it was pointing to is released. When a view controller is released, its internal global pointer is pointed to nil. Use “_strong” to describe global and local variables.
  • Local variables: Out of scope, Pointers are set to nil.
  • Method creates an object internally, and adds _autoRelease for external use.
  • When connected, use _weak to describe.
  • The proxy used unsafe_unretained is the same as assign.
  • The _weak description is used in blocks to avoid the problem of circular references.
  • When declaring properties, do not use thenewAt the beginning. If you have tonewStart with the name of the property, you need to customize the get method name, for example
    @property(getter=theString) NSString * newString;Copy the code
  • If you want to use automatic release pools, use@autoreleasepool{}
  • ARC can only manage Foundation variables. If the application forces a Foundation variable to be replaced by a COre Foundation variable, the management rights need to be exchanged.
  • Use ARC in non-ARC projects to compile certain classes: -fobjc-arc.
  • Projects under ARC use non-Arc to compile certain classes: -fno-fobjc-arc.

How to understand the MVC design pattern

MVC is an architectural pattern where M stands for MOdel, V for View, and C for Controller:

  • Model stores, defines, and manipulates data;
  • View is used to show the book to the user, and the user operation interaction;
  • The Controller is the coordinator between the Model and the View. The Controller takes the data from the Model and gives it to the View. The Controller can communicate directly with the Model and View, whereas the View cannot communicate directly with the Controller. When there is data update, the MOdel also needs to communicate with the Controller, using Notification and KVO. This way is just like a broadcast. The MOdel sends a signal. The Controller is set to listen to receive signals and send signals to the Controller when there is data update. The Model and View cannot communicate directly, which would violate the MVC design pattern.

How to understand the MVVM design pattern

  • ViewModelThe layer, which is the glue between the View and Model layers, is a great place to put user input validation logic, View display logic, network request initiation, and all sorts of other code. To put it bluntly, the originalViewControllerThe business logic and page logic of the layer are stripped out into the ViewModel layer.
  • The View layer, the ViewController layer, its job is to get the data from the ViewModel layer and display it.
  • To learn more, check out this article

Objective-C Is garbage collection supported?

  • OC supports garbage collection (Garbage collectionReferred to as”GC), but GC is not supported on Apple mobile terminals, and it is supported on Mac desktop systems.
  • Mobile terminal development is supported by ARC (Automatic Reference CountingARC is a new technology released after IOS5, it is different from GC mechanism. When we write code, we don’t need to send objectsreleaseorautoreleaseMethod, also cannot be calleddellocMethod, which the compiler automatically generates for the user in the appropriate placereleaseMessage (autorelease),ARC features automatic reference technology that simplifies memory management.

What are the basic concepts of protocols and the default types of methods in protocols

The protocol in OC is a list of methods and is more or less related. The special feature is that it can be used by any class (implementation), but it is not a class (note here) and does not implement such methods by itself. Instead, other people implement protocols that are often used to implement delegate objects (delegate design pattern). If a class adopts a protocol, it must implement methods that must be implemented in the protocol. Methods in the protocol are required by default (@required). Add the keyword @optional to indicate that these “optional” methods are optional once the protocol is adopted.

A brief introduction of categorycategoryAdvantages and disadvantages

Advantages:
  • There is no need to increase the behavior (methods) of an existing class by adding subclasses, and the methods in the class are basically the same as the original class methods;
  • The method of a large class can be divided through the category, so as to facilitate the future maintenance, update and improve the code reading;
    Disadvantages:
  • There is no way to add instance variables to a category. If you need to add instance variables, you must define a subclass.
  • Methods in the class category have higher precedence than the original class and methods of the parent class. Overwriting methods of the parent class may causesuperBreaking of messages. Therefore, it is best not to overwrite methods in the original class.

The role of categories

  • Add a method to a system class without extending properties. If the name of the method in the class is the same as the name of the method in the system, the method in the class has higher priority when invoked.
  • Implementation of decentralized classes:
    + (NSIndexPath *)indexPathForRow:(NSInteger)row
    inSection:(NSInteger)sectionCopy the code

    NSIndexPath is an NSIndexPath method, but because this method is called when it frequently uses tables, it is declared in uitableView.h as a class.

  • Declare a private method, a method that is only implemented, not declared, is equivalent to a private method.
  • Categories cannot declare variables, and categories cannot add attributes directly.propertyIf you describe setter methods, you won’t get an error.

The cause of circular reference, and the solution

  • Cause: As shown in the figure below, object A and object B refer to each other as their own member variables. The reference count of the member variables can be reduced by 1 only when they are destroyed. The destruction of object A depends on the destruction of object B, and the destruction of object B also depends on the destruction of object A, thus forming A circular reference, in which case, it cannot be freed even if no pointer from outside has access to it.



Loop through the sample diagram


There is still the problem of circular reference between multiple objects, forming a ring. In programming, the larger the ring is, the more difficult it is to detect, as shown in the following figure:




Multiple objects reference sample diagrams


Solutions:
  • Knowing in advance where circular references exist and breaking a reference at a reasonable location is object recycling.
  • Use weak references.

KeyPath (keyPath), key value encoding (KVC), key value observation (KVO)

The key path
  • In a given entity, all values of the same attribute have the same data type.
  • Key-value coding is used for such lookups – it is a mechanism for indirectly accessing object properties. – Key path is a string of dot-delimited keys used to specify a concatenated sequence of object properties. The properties of the first key are determined by the preceding properties, and the values of each subsequent key are also relative to the preceding properties.
  • Key paths allow you to specify the properties of related objects in a way that is independent of the model implementation. With key paths, you can specify a path in an object graph at any depth to point to a specific property of the object in question.
Key value encoding KVC
  • Key-value coding is a mechanism for indirectly accessing properties of objects using strings to identify properties, rather than calling access methods, directly or through instance variables. Variables of non-object types are automatically encapsulated or unencapsulated into objects, simplifying program code in many cases.
  • Disadvantages of KVC: Once you use KVC, your compiler cannot detect errors, that is, it does not check for errors on set keys, key paths, and is less efficient than synthetic accessor methods and custom setters and getters. Because it uses KVC key-value encoding, it must parse the string before setting or accessing the instance variable of the object.
Look at the key value KVO
  • Key-value observation is a mechanism that allows an object to get notification of changes in other object properties, greatly simplifying the code.
  • To implement KVO key-value observation, the observed object must use KVC key-value encoding to modify its instance variables in order to be observed by the observer. Therefore,KVC is the foundation of KVO.
Demo

Let’s say I made a button

[self addObserver:self forKeyPath:@"highlighted" options:0 context:nil]; #pragma mark KVO - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if ([keyPath isEqualToString:@"highlighted"] ) { [self setNeedsDisplay]; }}Copy the code

For the system, the value can be changed according to keypath, which is theoretically the same as the KVC mechanism.

The KVC mechanism passeskeyfindvalueThe principle of
  • When an object is called via KVC, for example:[the self valueForKey: @ "someKey"]The program automatically tries to resolve the call in several different ways.
  • The first thing to look for is whether the object hassomeKeyThis method, if not found, continues to look for the object to see if it hassomeKeyThis instance variable (iVar), if not found, the program will continue trying to call-(id) valueForUndefinedKey:This method. If the method is still not implemented, the program will throw oneNSUndefinedKeyExceptionException error.
  • (getsomeKey) (getsomeKey) (getsomeKey) (getsomeKey) (getsomeKey) (getsomeKey) Meanwhile, when looking for instance variables, it will not only look for someKey, but also look for the existence of _someKey.
  • designvalueForUndefinedKey:The main purpose of the method is when you use it-(id)valueForKeyWhen a method requests a value from an object, the object has a last chance to respond to the request before an error occurs.

inObjective-C How to implementKVO

  • Register observer (note: Observer and observed are not retained or released)

    - (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath 
    options:(NSKeyValueObservingOptions)options 
    context:(void *)context;Copy the code
  • Receiving notification of change
    - (void)observeValueForKeyPath:(NSString *)keyPath 
    ofObject:(id)object change:(NSDictionary *)change   context:(void *)context;Copy the code
  • Removes the observer status of the object
    - (void)removeObserver:(NSObject *)observer 
    forKeyPath:(NSString *)keyPath;Copy the code
  • In the KVOWho wants to listen who wants to registerAnd then the response is processed so that the observer and the observed are completely decoupled. KVO only checks for attributes in a class, and attribute names are found using NSString. The compiler does not check for errors or complete them.

The role of agency

  • Agent, also called delegate, is a design pattern. Agent is the communication interaction between objects. Agent removes the coupling between objects.
  • Change or pass control chains. Allows a class to notify other classes at certain times without having to retrieve Pointers to those classes. You can reduce framework complexity.
  • On another point, proxies can be understood as an analogy to the callback listening mechanism in Java.
  • The properties of a proxy are oftenassignPrevents cyclic references so that objects cannot be released properly.

Differences between NSNotification, Block, Delegate, and KVO

  • Proxy is a callback mechanism and is one-to-one. Notification is a one-to-many relationship. One pair provides change notification to all observers.
  • Efficiency: Delegate is higher than NSNOtification;
  • Delegate and Block are typically one-to-one communication;
  • The Delegate needs to define the protocol method, the proxy object implements the protocol method, and needs to establish a proxy relationship to achieve communication;
  • Block: Block is simpler and does not need to define complicated protocol methods. However, if communication events are large, Delegate is recommended.

Types that can and cannot be modified in Objective-C

  • Modifiable and non-modifiable collection classes are dynamically modifiable and non-dynamically modifiable.
  • Such asNSArrayandNSMutableArray, the former after initialization memory control is fixed immutable, the latter can be added, etc., can dynamically apply for new memory space

When we call a static method, we need to apply therelease ?

  • No, static methods (class methods) create an object when the object is already in the automatic release pool. The automatic release pool will most likely be destroyed when it is released.

Why do we need to call when we free our object[super dealloc]Method, what is its position?

  • Because some instances of subclasses inherit from their parent class, they need to be called[super dealloc]Method to free instances owned by the parent class, which is the subclass itself. Typically we release instances owned by subclasses first, and those owned by the parent class last.

Knowledge of predicates

  • One is provided in CocoaNSPredicateClass, which is mainly used to specify the conditions of the filter, and each object is filtered through predicates to determine whether the conditions match. If you need to know how to use it, seeConcrete use of predicates

The static, self, super keywords

  • Function in the bodystaticThe scope of a variable is the function body, unlikeautoVariable whose memory is allocated only once, so its value remains the same the next time it is called.
  • Inside the modulestaticGlobal variables can be accessed by functions used within a module, but not by other functions outside the module.
  • Inside the modulestaticA function can only be called by other functions within the module, and its use is restricted to declarations.
  • In the classstaticMember variables are owned by the entire class and have only one copy of all objects of the class.
  • Self: The receiver of the current message.
  • Super: sends messages to the parent class.

# include and#import difference,#import The difference from @class

  • #include#importThe effect is the same, the actions (methods) defined in the query class;
  • #importDoes not cause cross-compilation, ensuring that header files are imported only once;
  • @classThe name of the class is defined, and the behavior of the concrete class is unknown.
  • @class#importCompilation efficiency is higher.
  • In addition@class#importThe main difference is that reference deadlocks are resolved.

@public, @protected, and @private

  • @publicThe scope of an instance variable of an object can be accessed anywhere;
  • @protectedThe instance variable scope of an object can be accessed in this class and in subclasses.
  • @privateThe scope of an instance variable can only be accessed within the class itself.

explainid type

The type of any object is determined at runtime.

switch statementsif Statement distinction and relation

The switch statement expression can only handle integer, character, and enumeration types, whereas the flow statement has no such restriction. But switch statements are more efficient than flow control statements.

IsMemberOfClass and isKindOfClass connections and differences

  • Connection: Both detect whether an object is a member of a class
  • The difference between:isKindOfClassIt is used not only to determine whether an object is a member of a class, but also to determine whether an object is derived from a class of that classisMemberOfClassYou can only do the first thing.
  • Example: such asClassADerived from theNSObjectClass,ClassA *a = [ClassA alloc] init]; .[a isKindOfClass:[NSObject class]]We can check to see if ANSObjectA member of a derived class, butisMemberOfClassCan’t do.

iOS What are the types of data persistence in development?

Data storage is all about writing files.

  • Attribute list: only NSString, NSArray, NSDictionary, and NSData can be writeToFile; The storage is still plist files. Plist files can store seven types of data: array, Dictionary, String, bool, data, date, and number.
  • Object serialization (object archive) : Object serialization is stored locally in the form of serialization with key-value relationships and converted to binary streams. See this article for automated archiving/unarchiving via the Runtime. Two methods must be implemented to implement NSCoding protocol: 1. Encoding (object serialization) : data that cannot be directly stored in plIST files is converted into binary data, and NSData can be stored locally; 2. Decode (object deserialization) : Convert binary data to its original type.
  • SQLite database: A database that uses a lot of data regularly.
  • CoreData: Adds, deletes, searches, and modifies managed objects. It is not a database, and you can use an SQLite database not only to hold data, but also to store it in other ways. Such as XML.

CoreData Introduction:

  • CoreData is an object-oriented API, CoreData is a very important technology in iOS, almost in all written programs, CoreData is used as the basis of data storage.
  • CoreData is a set of frameworks provided by Apple to solve problems related to object declaration cycle management, object relationship management, and persistence.
  • In most cases, we refer to CoreData as a solution for persistent data and use it as persistent data mapped to in-memory objects. Object-relational mapping is provided, that is, CoreData can convert Objective-C objects into data, save it to SQL, and then restore the saved data to OC objects.

CoreData features:

  • Managing your application’s data model through CoreData can greatly reduce the amount of code you need to write.
  • Storing object data in an SQLite database has been optimized for performance.
  • NSFetchResultsController class is provided to manage table view Data, that is, store persistent Core Data in table view, and manage these Data: add, delete, check and modify.
  • Manage undo/redo manipulation;
  • Checks that the managed object’s property values are correct.

6 member object of Core Data

  • NSManageObject: The Managed Object Model describes the data Model of the application, including Entity, Property, Fetch Request, etc.
  • NSManageObjectContext: manages the object context, stores model objects persistently, participates in the whole process of data object operations, and monitors the changes of data objects to provide support for Undo /redo and update the UI bound to data.
  • 3. NSPersistentStoreCoordinator: connect to the database of the Persistent Store Coordinator is equal to the data file manager, dealing with the underlying the data file read and write, we did not overlap with the general.
  • 4. Ns-managed ObjectModel: managed data model and data structure.
  • NSFetchRequest: indicates a data request.
  • 6.NSEntityDescription: entity structure of the table, also need to know that the.xcDatamodel file is compiled into a.momd or.mom file.

The functionality of Core Data

  • Complete and automated support for KVC and KVO integrates appropriate collection access methods to handle multi-valued relationships in addition to integrating KVO and KVC access methods for attributes;
  • Automatic validation of property values;
  • Support for tracking modification and undo operations;
  • Relationship maintenance. Core Data manages the relationship propagation of Data, including maintaining consistency between objects.
  • Group, filter, and organize data in memory and on the interface;
  • Automatic support for object storage in external data warehouses;
  • Create complex requests: Associate NSPredicate in fetch Requests without having to write SQL statements. NSPreadicate supports basic functions, related subqueries, and other advanced SQL features. It supports correct Unicode encoding, region-aware queries, sorting, and regular expressions;
  • Lazy operation: Core Data uses lazy loading to reduce memory load. It also supports partially materialized lazy loading and Data sharing of copied objects.
  • Merge strategy: Core Data has built-in version tracking and optimistic locking to support the resolution of multi-user write conflicts. Optimistic locking detects Data conflicts and returns conflicting information if there are conflicts.
  • Data Migration: Core Data’s Schema Migration tool simplifies the task of dealing with changes in database structure, and in some cases allows you to perform efficient in-place database Migration.
  • Can choose according to program the Controller layer integration, to support the UI display synchronization Core Data on the IPhone OS, providing NSFetchedResultsController object to do related work, On Mac OS X we did this using the Binding mechanism provided by Cocoa.

Conditions under which an object can be copied

  • Only by implementingNSCopyingandNSMutableCopyingOnly objects of the protocol class can be copied, including immutable copy and mutable copy.Specific differences stamp here;
  • NSCopyingProtocol method:
    - (id)copyWithZone:(NSZone *)zone {
     MyObject *copy = [[[self class] allocWithZone: zone] init];
     copy.username = [self.username copyWithZone:zone];
     return copy;
    }Copy the code

Working principle of automatic release pool

  • Auto release pool isNSAutoreleaseClass when sent to an objectautoreleaseMessage, the object is automatically added to the pool. When the pool is destroyed, a message is sent to all objects in the poolreleaseMessage to release the object.
  • [pool release]、 [pool drain]The pool itself is not destroyed, but temporary objects in the pool are sentreleaseTo destroy the object.

In a method self.name = _name, name = _name are they different? Why?

  • The former is a memory-managed setter method assignment that performs either a save or copy operation on the _NAME object
  • The latter is normal assignment
  • In general, member variables and methods are accessible in object methods, and we often override Setter methods to perform some extra work. For example, if I pass in a model, I’m going to override the Setter method, and when the model comes in, that means that the data has changed, and the view needs to update the display, I’m going to refresh the UI while assigning the new model.

Explain the self = [super init] method

  • Fault tolerant handling, when the parent class fails to initialize, it returns nil, indicating initialization failed. Because of inheritance, a subclass needs to have instances and behaviors of its parent class, so we must initialize the parent class first and then initialize the child class

When defining attributes, when do you use themassign,retain,copy And the difference between them

  • assign: Plain assignment, commonly used for primitive data types, common delegate design patterns to prevent circular references. (We call this weak reference).
  • retainThe reference count is incremented by 1.
  • copy: a new memory space is created to store the new object, which has two different addresses and a reference count of 1. But whencopyWhen the object is immutable, thencopyIs equivalent toretain. Because, this can save memory space

The difference between heap and stack

  • The stack area (stack)A stack is a data structure that extends to a lower address. It is a contiguic area of memory. That is, the address of the top of the stack and the maximum capacity of the stack are predetermined by the system.
  • The heap area (heap)Generally, the data structure is allocated and released by the programmer. If the programmer does not release it, the data structure is reclaimed by the OS at the end of the program. The data structure extended to high address is discontinuous memory area, so the space obtained by the heap is more flexible.
  • Fragmentation issues: For the heap, frequentnew/deleteIt is bound to cause the discontinuity of memory space, resulting in a large number of fragments, so that the efficiency of the program is reduced. This is not a problem with stacks, because stacks are first in, last out queues, and they are so one-to-one that it is never possible for a block of memory to eject from the middle of the stack.
  • allocation: The heap is dynamically allocated, there is no statically allocated heap. There are two types of stack allocation: static allocation and dynamic allocation. Static assignment is done by the compiler, such as assignment of local variables. Dynamic allocation is done by the Alloca function, but stack dynamic allocation is different from heap dynamic allocation, which is released by the compiler without manual implementation.
  • Allocative efficiency: Stack is a data structure provided by the machine system, and the computer provides support for the stack at the bottom: special registers are allocated to store the address of the stack, and special instructions are executed to push and unload the stack, which determines the high efficiency of the stack. The heap is provided by the C/C++ library, and its mechanism is quite complex.
  • Global region (Static region)(static)Global variables and static variables are stored together. Initialized global variables and static variables are stored in one area, and uninitialized global variables and uninitialized static variables are stored in another area adjacent to each other. The system is released after the program ends.
  • Text constant area— This is where constant strings are placed. The program is released by the system after completion.
  • Program code area– Stores the binary code of the function body

How do I use performSelector to pass in more than three arguments, one of which is a structure

  • Because the system providesperformSelectorThe API does not provide three parameters. So, we can only pass arrays or dictionaries, but arrays or dictionaries can only store object types, and structures are not object types, so we can only pass objects by putting structures as properties.
     - (id)performSelector:(SEL)aSelector;
     - (id)performSelector:(SEL)aSelector withObject:(id)object;
     - (id)performSelector:(SEL)aSelector withObject:
        (id)object1 withObject:(id)object2;Copy the code
  • The concrete implementation is as follows:

    typedef struct HYBStruct { int a; int b; } *my_struct; @interface HYBObject : NSObject @property (nonatomic, assign) my_struct arg3; @property (nonatomic, copy) NSString *arg1; @property (nonatomic, copy) NSString *arg2; @end@implementation HYBObject - (void)dealloc {free(self.arg3); } @endCopy the code
  • Testing:
    my_struct str = (my_struct)(malloc(sizeof(my_struct))); str->a = 1; str->b = 2; HYBObject *obj = [[HYBObject alloc] init]; obj.arg1 = @"arg1"; obj.arg2 = @"arg2"; obj.arg3 = str; [self performSelector:@selector(call:) withObject:obj]; - (void)call:(HYBObject *)obj {NSLog(@"%d %d", obj. Arg3 ->a, obj. }Copy the code

UITableViewCell has a UILabel that shows the stopwatch time implemented by NSTimer. Does the label refresh during scrolling of the cell? Why?

Whether this is refreshed or not depends on what Mode the timer adds to the Run Loop. Mode is mainly used to specify the priority of events in the running loop, including:

  • NSDefaultRunLoopMode (kCFRunLoopDefaultMode): The default state is idle
  • UITrackingRunLoopMode: ScrollView slides to this Mode
  • UIInitializationRunLoopMode: Run loop Switches to this mode when it is started
  • NSRunLoopCommonModes (kCFRunLoopCommonModes): set Mode

    There are two modes publicly provided by Apple:

  • NSDefaultRunLoopMode (kCFRunLoopDefaultMode)
  • NSRunLoopCommonModes (kCFRunLoopCommonModes)
  • In programming: If we put aNSTimerObject toNSDefaultRunLoopMode (kCFRunLoopDefaultMode)When added to the main run loop, ScrollView scrolling will be caused by mode switchingNSTimerWill no longer be scheduled. When we scroll, we want to not schedule, so we should use the default mode. However, if you want the timer to be called back when scrolling, you should use Common Mode.

Understanding cell reuse

  • When the screen slides off the screen, the system will add this cell to the reuse queue, waiting to be reused. When a new cell slides into the screen from outside the screen, the system will look for the reuse queue to see if there is a cell that can be reused. If there is a cell, it will be used directly.

Solve the problem of cell reuse

  • UITableView saves memory by reusing cells by specifying a reuseidentifier for each cell, which specifies the type of cell and allows the cell to be recovered for reuse when it rolls off the screen. Use different ids for different types of cells, and for simple tables, one identifier is sufficient.
  • For example, there are 10 cells in a TableView, but the screen displays 4 cells at most. In fact, iPhone only allocates 4 cells of memory for it, not 10. When scrolling cells, the cells displayed on the screen repeatedly use these 4 cells of memory. In fact, the number of allocated cells is the maximum number of cells that can be displayed on the screen. When a new cell enters the screen, the memory occupied by the cell that has been rolled off the screen is randomly called, which is cell reuse.
  • In the case of variable custom cells, this reuse mechanism can lead to errors in the content
    UITableViewCell * cell = [tableview dequeueReusableCellWithIdentifier: defineString] is amended as: UITableViewCell *cell = [tableview cellForRowAtIndexPath:indexPath];Copy the code

    This solves the problem caused by cell reuse.

If there are four asynchronous requests a, B, C, and D, how can I determine that a, B, C, and D are all executed? If a, B, C, and D need to be executed in sequence, how to achieve this?

  • For each of the four asynchronous requests, the easiest way to determine whether they are all completed is through the GCD group:
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_group_t group = dispatch_group_create(); Dispatch_group_async (group, queue, ^{/* task a */}); Dispatch_group_async (group, queue, ^{/* task b */}); Dispatch_group_async (group, queue, ^{/* task c */}); dispatch_group_async(group, queue, ^{/* task C */}); Dispatch_group_async (group, queue, ^{/* task d */}); Dispatch_group_notify (group,dispatch_get_main_queue(), ^{// dispatch_group_notify(group,dispatch_get_main_queue(), ^{Copy the code
  • Of course, we could have done it the old-fashioned way, using four variables to indicate whether tasks A, B, C, and D are complete, then waiting in the runloop and exiting the runloop when they are. But doing so prevents subsequent code from executing until the Run loop completes.
  • Explanation: If sequential execution is required, tasks can be placed in a serial queue and executed asynchronously.

What are the benefits of using blocks? Use NSTimer to write code that uses blocks to display a stopwatch (on UILabel)

  • Compact code, value, callback are very convenient, save a lot of code to write agent.
  • NSTimer encapsulated into a block, concrete implementation
  • Implementation method:
    NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval: 1.0 repeats: YES callback: ^ () {weakSelf. SecondsLabel. Text =...  } [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];Copy the code

A view has been initialized and n buttons have been added to the view. In addition to using the view tag, how can we find the desired button and modify the value of the button

There are two ways to solve this problem:

  • First: if a button is clicked, it will refresh its value, other need not modify, then do not reference any button, directly in the callback, the button has received the response to pass, directly through it can be modified.
  • Click on a button and all buttons of the same type will change their value, so you can create the button by storing it in an array and iterating through it as needed.

What are the differences and connections between threads and processes?

  • A program must have at least one entry, and a process must have at least one thread.
  • Process: the smallest independent unit of resource allocation. A process is a running activity of a program with certain independent functions on a data set. A process is an independent unit of the system for resource allocation and scheduling.
  • Thread: A branch of a process. It is the entity of a process and the basic unit of CPU scheduling and dispatching. It is a basic unit smaller than a process that can run independently. However, it can share all resources owned by the process with other threads belonging to the same process.
  • Process and thread are the basic unit of the program run by the operating system. The system uses the basic unit to realize the system’s concurrency to the application.
  • The main difference between processes and threads is that they are different ways of managing operating system resources. Processes have independent address Spaces, a crash of one process in protected mode does not affect other processes, and threads are just different execution paths within a process. Thread has its own stack and local variables, but there is no separate address space between threads, a thread dead is equal to the whole process dead, so multi-process procedures than multithreaded procedures robust, but in the process switch, the cost of resources is larger, the efficiency is poor.
  • However, for concurrent operations that require simultaneous and variable sharing, only threads, not processes, can be used.

Multithreaded programming

  • NSThread: When time-consuming operations need to be performed, time-consuming operations are put into the thread. Thread synchronization: Multiple threads accessing the same data can cause problems, NSlock, thread synchronization block, @synchronized(self){}.
  • NSOperationQueue Indicates the operation queue(No need to worry about thread synchronization). The focus of programming is in Main,NSInvocationOperation,BSBlockOperation, User-defined Operation. Create an action bound method. When an action is added to an action queue, the action bound method is automatically executed. When an action is added to an action queue, the main method is called by default.
  • The GCD (`Grand Central Dispatch) grand central scheduling, serial queue, concurrent queue, main queue;
  • Synchronous and asynchronous: Synchronous means that the second task is not started until the first task is completed. Asynchronous means that the second task is started regardless of whether the first task is completed.
  • Serial and parallel: serial means that multiple tasks are executed in a certain order, while parallel means that multiple tasks are executed simultaneously.
  • The code is executed in split threads, refreshing the UI in the main thread tuple.

Multithreaded programming is the best way to prevent main thread clogging and increase operation efficiency.

  • Apple provides the NSOperation class, which provides an excellent multithreaded programming method;
  • An NSOperationQueue is like a thread manager, not a thread, because you can set the number of threads in that thread manager that can run in parallel and so on.
  • Multithreading is a lightweight way to implement multiple code execution paths within a single application.
  • The main thread under iPhoneOS has a stack size of 1M. The second thread starts at 512KB, and this value cannot be changed by compiler switches or thread API functions. Only the main thread has the ability to modify the UI directly.

The difference between timer and thread;

  • The timer. It can be executed multiple times and is in the main thread by default.
  • Thread: Can be executed only once.

Apple device size and programming size




The device





The IPod devices





The equipment


The difference between TCP and UDP is contact

  • TCP is the transmission control layer protocol, for connection-oriented, reliable, point-to-point communication;
  • UDP is a user datagram protocol, unconnected and unreliable point-to-multipoint communication.
  • TCP focuses on reliable transmission, while UDP focuses on fast transmission.

Three-way handshake for TCP connection

  • First handshake: The client sends a SYN packet (SYN = J) to the server and enters the SYN_SEND state.
  • Second handshake: After receiving a SYN packet, the server must acknowledge the client’s SYN (ACK = J +1) and send a SYN packet (ACK = J +1). In this case, the server enters the SYN+RECV state.
  • Third handshake: After receiving the SYN+ACK packet from the server, the client sends an ACK packet (ACK = K +1) to the server. After this packet is sent, the client and the server enter the ESTABLISHED state.

The difference between a Scoket connection and an HTTP connection:

  • HTTP is an application layer protocol based on TCP connections. It mainly deals with how to package data. The Socket is the encapsulation of TCP/IP. The Socket itself is not a protocol, but an API. Through the Socket, we can use TCP/IP.
  • HTTP connection: A short connection. The client sends a request to the server. The server responds and the connection is disconnected, saving resources. The server cannot actively respond to the client (unless using HTTP long connection technology), and the iPhone mainly uses the class NSURLConnection.
  • Socket connection: long connection, the client and server directly use Socket connection, there is no provision for the connection after the disconnect, so the client and server maintain the connection channel, both sides can actively send data, generally used for games. The default connection timeout period of the Socket is 30 seconds, and the default size is 8K (understood as a packet size).

HTTP protocol features, about HTTP requests GET and POST differences

GET and POST:

  • HTTP hypertext transfer protocol is a short connection, where the client sends a request, the server responds, and when the server responds, the connection is disconnected. HTTP is an object – oriented protocol at the application layer. HTTP has two types of packets: request packets and response packets.
  • HTTP request packet: an HTTP request packet consists of four parts: request line, request header, blank line, and request data.
  • An HTTP response packet consists of a status line, a message header, and a response body.
  • GET request: Parameters are concatenated after the address, no data is requested, unsafe (because all parameters are concatenated after the address), and not suitable for transferring large amounts of data (limited length, 1024 bytes).

    GET submits and requests data that is appended to the URL, placing the data in the HTTP header. In order to? Split URL and transfer data, multiple parameters with & join. If the data is English letters or numbers, send it as is, if it is space, convert to +, if it is Chinese/other characters, the string is directly BASE64 encrypted.Copy the code
  • POST request: Parameters are placed in the request data area, which is more secure than GET requests, and the data size is unlimited. Put the submitted data in the body of the HTTP package.

  • Data submitted by GET will be displayed in the address bar, while data submitted by POST will not change the address bar.

Size of data transferred:

  • When A GET submission is submitted, the data transmitted will be limited by the URL length. POST is theoretically not limited because it does not transmit values through the URL.

Security:

  • POST is more secure than GET;
  • By submitting data through GET, the user name and password will appear in the URL in plain text. For example, the login interface may be cached by the browser.
  • HTTPS: Secure hypertext Transfer Protocol (Secure Hypertext Transfer Protocol), which is a secure communication channel developed based on HTTP for exchanging information between client computers and servers using the condom protocol layer (SSI) for information exchange, the secure version of HTTP.

The difference between ASIHttpRequest and AFNetWorking

  • ASIHttpRequest is a powerful function, mainly implemented under MRC, is the system CFNetwork API encapsulation, support HTTP protocol CFHTTP, configuration is more complex, and the ASIHttpRequest framework will not help you monitor network changes by default, If you need to ask ASIHttpRequest to listen for network state changes for you, start the function manually.
  • AFNetWorking builds on NSURLConnection, NSOperation, and other familiar Foundation technologies. With a good architecture, rich API and module building way, it is very easy to use. It’s based on the AFURLConnectionOperation subclass that NSOperation encapsulates.
  • ASIHttpRequest is a direct operation object. ASIHttpRequest is a subclass of NSOperation that implements the NSCoding protocol. AFNetWorking directly operates on objects. AFHttpClient is a subclass of NSObject that implements the NSCoding and NSCopying protocols.
  • Synchronous request: ASIHttpRequest directly by calling onestartSynchronousMethods; AFNetWorking does not encapsulate synchronous requests by default and will need to be overridden if developers want to use synchronous requestsgetPath:paraments:success:failuresMethod to synchronize the AFHttpRequestOperation.
  • Performance comparison: AFNetworking request is better than ASIHttpRequest;

What are the different ways in which XML data is parsed, and what are the frameworks for JSON parsing?

  • There are two ways to parse XML data: DOM parsing and SAX parsing;
  • DOM parsing must complete the structure of DOM tree, which consumes a lot of memory and resources when processing large XML documents. Read the entire XML document and build a tree structure (node tree) that resides in memory. By traversing the tree structure, you can retrieve any XML node and read its attributes and values. XML nodes can be queried with XPath;
  • SAX and DOM, it is an event-driven model, parse the XML document every encounter a beginning or end tags, attributes, or an instruction, the program will generate an event to carry on the corresponding processing, processing, as he reads the XML document don’t have to finish the entire document loading to take measures, such as when it reads the objects encountered in the parsing process to deal with, A notice will be issued for processing. Thus, SAX is better suited to working with large XML documents than DOM. -JSON parsing: The third-party JSONKIT and the BUILT-IN JSON parsing classes of iOS have high performance. The built-in JSON parsing classes have the highest performance, but can only be used after iOS5.

How to debug the real machine

  • 1. You need it firstKey stringCreate a key;
  • 2. Upload the key string to the official website to obtain the iOS Development certificate;
  • 3. Create the App ID, the Boundle ID in our App.
  • 4. Add Device ID (UDID).
  • 5. Select the previously created certificates App ID and Device ID.
  • 6. Generate mobileprovision files.
  • 7. Prerequisites: $99 for a developer account

APP launch process

  • 1. Log in to the application publishing website to add application information.
  • 2. Download and install the distribution certificate.
  • 3. Select the publishing certificate, use Archive to compile the publishing package, and use Xcode to upload the code (publishing package) to the server.
  • 4. Waiting for approval;
  • 5. Generate IPA: menu bar ->Product->Archive

The use of SVN

  • SVN= version control + backup server. SVN can be used as a backup server, and can help you remember the file content of the server every time, and automatically assign the version of each change.
  • Version control of SVN: All uploaded versions are recorded for you, and version branching and merging are also available. SVN allows different developers to access the same files and uses SVN Server as the file synchronization mechanism, meaning that you do not need to send files to your developers when you have file updates. The SVN stores files in differential backup mode, that is, files are backed up to different locations to save disk space. Non-text files can also be backed up differently.
  • Importance of SVN: The importance of backing up work files, version control, data synchronization between partners, and backing up different versions consumes hard disk space.
  • Prevent conflicts: 1. Prevent code conflicts: do not modify the same file at the same time, for example: A, B modify the same file, first let A modify, and then submit to the server, and then B update, and then modify; 2. For project file Xcodeproj on the server, only one person is allowed to manage submission, while others are only updated to prevent file conflicts.

How do I push network messages

  • One is the notification service provided by Apple itself (APNS server), and the other is the third-party push mechanism.
  • First, the application sends a notification, and a prompt box is displayed asking the user whether to allow it. After the user allows it, the user requests deviceToken to the Apple server (APNS), and the Apple server sends the deviceToken to its own application, and the application sends the deviceToken to its own server. When your own server wants to send network push, it sends deviceToken and the information you want to push to The Apple server, and the Apple server sends the information to the application.
  • The total volume of push information does not exceed 256 bytes;
  • The iOS SDK itself provides APNS server push, which can be directly pushed to target users and pop-up prompts according to your way. Advantages: Whether the app is open or not, it will be sent to the mobile phone; Cons: The push mechanism is controlled by the Apple server, and there may be occasional delays because the Apple server also has queues to handle all message requests;
  • The third-party push mechanism, which is generally implemented by Socket mechanism, can be almost instantly sent to the target user’s mobile phone. It is suitable for instant messaging applications. Advantages: Real-time, depending on the rhythm of the heartbeat packet; Disadvantages: Limited by iOS system, the application cannot run in the background for a long time, so this push mechanism is not available when the application is closed.

Network Layer 7 protocol

  • Application layer: 1. User interface and application program; Typical device: gateway; 3. Typical protocols, standards, and applications: TELNET, FTP, and HTTP
  • Presentation layer: 1. Data representation, compression and encryption Typical equipment: gateway 3. Typical protocols, standards and applications: ASCLL, PICT, TIFF, JPEG | MPEG 4. The presentation layer represents a representation of something, representing some protocol, such as picture, sound, and video MPEG.
  • Session layer: 1. Establish and end a session. 2. Typical equipment: gateway; 3. Typical protocols, standards and applications: RPC, SQL, NFS, X WINDOWS, ASP
  • Transport layer: 1. Main functions: end-to-end control Transport; 2. Typical equipment: gateway; 3. Typical protocols, standards, and applications: TCP, UDP, and SPX
  • Network layer: 1. Main functions: routing and addressing Network; 2. Typical equipment: router; 3. Typical protocols, standards, and applications: IP, IPX, APPLETALK, and ICMP
  • Data link layer: 1. Main function: to ensure error-free negligence of the data link; 2. Typical devices: switches, Bridges, and network adapters; 3. Typical protocols, standards and applications: 802.2, 802.3ATM, HDLC, FRAME RELAY;
  • 1. Main functions: transmit bitstream Physical; Typical equipment: hub and repeater 3. Typical protocols, standards and applications: V.35, EIA/TIA-232.

An understanding of NSUserDefaults

  • NSUserDefaults: A method of storing data provided by the system. It is used to store small amounts of data in the Preferences folder under the Library by default.

SDWebImage principle

Method to call the class:

  • Find the image from memory (dictionary) (when the image has been loaded in this program), find directly use;
  • Go to the sandbox, find it and use it directly, cache it into memory.
  • Fetch from the network, use, cache to memory, cache to sandbox.

Is there a two-dimensional array in OC? How to implement a two-dimensional array

When is LayoutSubViews called?

  • This method is called when the frame of the View itself changes.

Deep copy and shallow copy

  • If an object has a pointer member variable that points to a resource in memory, how do I copy that object? Would you just copy the value of the pointer to the copy of the new object? Pointers are just placeholders for storing the addresses of resources in memory. In a copy operation, if you just copy a pointer to the new object, then the underlying resource is actually still shared between the two instances.



Figure 1


  • Shallow replication: Pointers to both instances still point to the same resource in memory, copying the pointer value instead of the actual resource.
  • Deep copy: Copies not only the pointer value, but also the resource to which the pointer points. The diagram below:



The example in figure 2


Understanding and using singleton patterns

  • Singleton is a common design pattern in which a class has only one instance object in the system. Access to the instance object through a global entry point;
  • In iOS, singleton mode is generally implemented in two ways: non-Arc and ARC+GCD.

Understanding sandboxes

  • Each iOS app is limited to a “sandbox,” which is a folder with permissions visible only to the owner. During the app installation process, each individual app generates its home directory and some key subdirectories. Apple has several restrictions on sandboxes:
    1. The application operates in its own sandbox, but cannot access any other application's sandbox; 2. Applications cannot share data. Files in the sandbox cannot be copied to other application folders or other application folders to the sandbox. 3. Apple forbids any reading or writing to files outside the sandbox, and forbids apps from writing to folders outside the sandbox; 4. There are three folders in the sandbox directory: Documents -- store application data files, store user data or other information that is backed up regularly; There are two folders under Library, Caches store the information the application needs to start up again, and Preferences contain the application's Preferences file, which cannot be changed. Temp stores temporary files that are not needed to restart the application.Copy the code
  • There are several ways to get the root of the sandbox: use NSHomeDirectory to get it.
  • Obtain the Document path:

    NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES).

An understanding of waterfall flow

  • First of all, the width of the picture is the same. 1. Compress the picture proportionally so that the picture is not deformed. 2. Calculate the lowest position of the picture and put it in the lowest column. 3. Perform optimal arrangement, add two TableViews on the basis of ScrollView, and then display the height of ScrollView calculated before through tableView.
  • How to interwork with two TableViews: Disable scrolling events for both TableViews, scroll both TableViews with the outermost scrollView, and change the contentOffset so that both tableViews are scrolling.

When are loadView, viewDidLoad, viewDidUnload called?

  • viewDidLoadCalled when the view is initialized from the NIB file,loadViewCalled when the view of the controller is nil.
  • This method is called when the view is implemented programmatically, and the View controller is registered by defaultmemory warning notificationwhenview controllerWhen any view of theviewDidUnloadWill be called, and the implementation here will beretaintheview releaseIf it isretaintheIBOutlet viewProperties don’t go thererelease.IBOutletBe responsible forrelease

What is the meaning of the keyword volatile? And give three different examples:

  • One is defined asvolatileThe value of this variable can be changed unexpectedly, so that the compiler does not assume its value. To be precise, the optimizer must carefully re-read the value of the variable each time it is used, rather than using a backup stored in a register. The following isvolatileA few examples of variables:

    • Hardware registers of parallel devices (e.g. status registers);

    • Non-automatic variables that will be accessed in an interrupt service subroutine;

    • A variable shared by several tasks in a multithreaded application.





At sign synthesize, at sign dynamic

  • @synthesizeThe system automatically generates getter and setter property declarations.@synthesizeThe compiler generates code to satisfy the property declaration unless the developer has already done so;
  • @dynamicIt is the developers themselves who provide the corresponding property declarations,@dynamicThis means that the developer provides the corresponding code: for read-only attributes you dosetterFor the read and write properties, it needs to be providedsettergetter. Consulted some data to determine@dynamic“Attribute” tells the compiler that the methods for obtaining and assigning attributes are implemented by the user and not automatically generated.

What’s the difference between frame and bounds?

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

What are the touch events of a view?

  - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
  - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
  - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event; 
  - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;Copy the code

Custom implementation of UITabbarController principle

  • Using the dictionary, click one of the five buttons to select a controller object from the dictionary and display its View on the main controller View.

How responder chains work in iOS

  • Each application has a responder chain, and our view structure is an N-fork tree (a view can have multiple child views, and a child view has only one parent view at a time), and each one inheritsUIResponderCan act as a node in the n-tree.
  • When the leaf node becomes the highest responder, a chain is traced from this leaf node to its parent node, so for this leaf node, this chain is the current responder chain. Responder chain distributes the UIEvent and UITouch captured by the system layer by layer from the leaf node downwards, during which the distribution can be stopped or continued downwards.
  • For more details, readThis article.

    Value transfer between views

  • The property property of the object passes a value.
  • Method parameter transmission;
  • NSUserDefault spread value;
  • Block value.

The effect of the modifier on the property

  • Getter =getName, setter=setName: sets setter and getter method names.
  • Readwrite, readonly: Set the access level.
  • Assign: assigns the value directly without performing any retain operations to solve the problem of original type and loop reference.
  • Retain: its setter method releases the old value and then retains the new value of the arguments, in this order for all implementations;
  • Copy: setter methods copy the old value release as retained and copy the new object, retainCount is 1. This is a mechanism introduced to reduce dependency on context.
  • Nonatomic: Non-atomic access, no synchronization, multi-threaded concurrent access to improve performance. Note that without this attribute, both access methods are atomic transaction access by default.

Understanding Run Loop

  • RunLoop, the magic weapon of multithreading, means that a thread can execute only one task at a time, and then exit the thread. The main thread continues to wait for events to be received after completing an instant task without exiting. The non-main thread is usually used to perform a task, and the resource needs to be returned upon completion, so RunLoop is not run by default;
  • Each thread has its own RunLoop, but only the main thread RunLoop is started by default, the other child thread RunLoop is not started by default, to start manually.
  • In a separate thread, you need to enable RunLoop if you want to wait for events to be received without exiting after processing a task.
  • NSRunLoop provides a method to add NSTimer. You can specify Mode. If you want to call back in any case, you need to set Mode to Common Mode.
  • Essentially, runloops for child threads do not exist by default, because Apple uses lazy loading. If we didn’t call it manually[NSRunLoop currentRunLoop]There is no query to see if there is a RunLoop for the current thread, no loading, and no creation.

Common SQL statements in SQLite

  • Create a table :creat table table name (whether the field data type is primary key, field name field data type, field name field data type…) ;
  • Add: insert into table name (insert into table name) Values (1, 2…) ;
  • Delete: delete from table_name where table_name = 1;

Advantages and disadvantages of XIB versus Storyboards

Advantages:

  • XIB: Provides a visual interface before compilation, you can directly drag controls, also can directly add constraints to the control, more intuitive, and the class file is less code to create controls, really simplified a lot, usually each XIB corresponds to a class.
  • Storyboard: It provides visual interface, drag-and-drop controls, and constraints before compilation, which is intuitive for development. A Storyboard can have many interfaces, and each interface corresponds to a class file. Through Storybard, you can intuitively see the structure of the entire App.

Disadvantages:

  • XIB: When requirements change, the XIB needs to be modified significantly, and sometimes constraints need to be re-added, resulting in a longer development cycle. XIB loads are naturally slower than pure code. Xibs can be difficult to use when more complex logic controls the display of different content in different states. XIB files can easily lead to conflicts when developed by multiple or multi-team teams, and conflict resolution is much more difficult.
  • Storyboard: When requirements change, constraints on the corresponding interface in a Storyboard need to be modified. As in a XIB, constraints may need to be re-added, or adding constraints can cause a lot of conflict, especially in multi-team development. It can be difficult to control different displays with complex logic. In multi-person or multi-team development, everyone can change a storyboard at the same time, leading to a lot of conflicts that can be very difficult to resolve.

Example Change the formatted date of string 2015-04-10 to NSDate

NSString *timeStr = @"2015-04-10";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd";
formatter.timeZone = [NSTimeZone defaultTimeZone];
NSDate *date = [formatter dateFromString:timeStr];
// 2015-04-09 16:00:00 +0000
NSLog(@"%@", date);Copy the code

How queues and multithreading work

Queues are divided into the following types in iOS:

  • Serial queue: Tasks in a queue are executed sequentially only;
    dispatch_queue_t q = dispatch_queue_create("..." , DISPATCH_QUEUE_SERIAL);Copy the code
  • Parallel queues: Tasks in queues usually execute concurrently;
    dispatch_queue_t q = dispatch_queue_create("......" ,DISPATCH_QUEUE_CONCURRENT);Copy the code
  • Global queue: is the system, directly take over (GET) can be used; Similar to parallel queues;
    dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);Copy the code
  • Primary queue: Each application corresponds to a unique primary queue, which can be directly GET. In multithreaded development, use main queues to update the UI;
    dispatch_queue_t q = dispatch_get_main_queue();Copy the code
  • See below for more details:




    From Jane’s book



Memory usage and optimization considerations

  • Reuse problems: such as UITableViewCells, UICollectionViewCells, UITableViewHeaderFooterViews set the correct reuseIdentifier, fully reuse;
  • Set the views as opaque as possible: When opque is set to NO, the layer’s translucency depends on the image and its own composite layer, which improves performance.
  • Don’t use XIB/ storyboards that are too complex: All the resources needed for XIB/ storyboards, including images, are loaded into memory at load time, even if they will be used long into the future. Those are much worse in performance and memory than lazy loading in pure code;
  • Choose the right data structure: Learning to choose the best array structure for your business scenario is fundamental to writing efficient code. For example, an array: an ordered set of values. Indexing is fast, value is slow, and insert/delete is slow. Dictionary: Stores key-value pairs, which are faster to find by key. Collection: An unordered set of values that are quick to find and quick to insert/delete. Gzip/ZIP compression: When you download attachments from the server, you can compress them using gzip/zip to reduce memory size and speed up the download.
  • Lazy loading: Lazy loading is used for data that should not be used. Lazy loading is used for views that do not need to be displayed immediately. For example, when a network request fails, the notification screen may never be used, so lazy loading should be used.
  • Data cache: Cache the row height of the cell to make reload data efficient. For network data that does not need to be requested every time, it should be cached, written to a database, or stored in a PList file.
  • Handling memory warnings: Generally, memory warnings are handled uniformly in the base class, and related unused resources are immediately released

    Reuse large overhead objects: Some objects are slow to initialize, for exampleNSDateFormatterandNSCalendarBut they inevitably need to be used. They are usually stored as properties to prevent repeated creation.

  • Avoid reprocessing data: Many applications need to load data, often in JSON or XML format, from the server for functionality. It is important to use the same data structure on both the server and client sides;
  • Using an Autorelease Pool: When some loops create temporary variables to process data, the Pool is automatically released to ensure that memory is freed in a timely manner.
  • Choose the right image loading method: Read more about UIImage loading method

The full life of a UIViewController

- [ViewController initWithNibName: bundle:]; - [ViewController init]; - [ViewController loadView]; - [ViewController viewDidLoad]; - [ViewController viewWillDisappear:]; - [ViewController viewWillAppear:]; - [ViewController viewDidAppear:]; - [ViewController viewDidDisappear:];Copy the code

UIImageView add rounded corners

  • The most straightforward way is to use the following property Settings:
    imgView.layer.cornerRadius = 10; Imgview. clipsToBounds = YES;Copy the code

    ** This is off-screen rendering, which consumes performance

  • Add an extended API to UIImage that generates rounded images: on-screen-rendering

    - (UIImage *)imageWithCornerRadius:(CGFloat)radius {
    CGRect rect = (CGRect){0.f, 0.f, self.size};
    
    UIGraphicsBeginImageContextWithOptions(self.size, NO, UIScreen.mainScreen.scale);
    CGContextAddPath(UIGraphicsGetCurrentContext(),
     [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:radius].CGPath);
    CGContextClip(UIGraphicsGetCurrentContext());
    
    [self drawInRect:rect];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return image;
    }Copy the code

Thank you very much for your reading. Recently, we opened an official wechat account to present more exciting technical articles to you. The official account ID is iOSDevSkills. Thank you very much!