0, the attention point of the thread (master)
1. Do not drive too many threads at the same time (no more than 5 threads, not more than one thread)
2. Threading Concepts
1> main thread: UI thread, displaying, refreshing UI interface, handling events for UI controls
2> Child Threads: Background threads, asynchronous threads
3. Do not place time-consuming operations on the main thread, but on sub-threads
First, Nsthread (master)
1.3 ways to create and start a thread
1> first created, then started
Create
Nsthread *thread = [[Nsthread alloc] initwithtarget:self selector: @selector (download:) Object:nil];
Start
[Thread start];
2> Create auto Start
[Nsthread detachnewthreadselector: @selector (Download:) totarget:self Withobject:nil];
3> Implicit creation (auto-start)
[Self performselectorinbackground: @selector (Download:) Withobject:nil];
2. Common methods
1> Get current thread
+ (Nsthread *) CurrentThread;
2> Get the main thread
+ (Nsthread *) Mainthread;
3> sleep (pause) thread
+ (void) Sleepuntildate: (NSDate *) date;
+ (void) Sleepfortimeinterval: (Nstimeinterval) ti;
4> set the name of the thread
-(void) SetName: (NSString *) n;
-(NSString *) name;
Second, thread synchronization (master)
1. Essence: To prevent multiple threads from robbing the same resource for data security issues
2. Implementation: Add a mutex to the code (synchronous lock)
@synchronized (self) {
Locked Code
}
Third, GCD
1. Queues and Tasks
1> tasks: What needs to be done
* Use block to encapsulate tasks
2> Queues: Storing tasks
* Global Concurrent queue: Allows tasks to execute concurrently
dispatch_queue_t queue = Dispatch_get_global_queue (Dispatch_queue_priority_default, 0);
* Create a serial queue yourself: Let the task execute one after the other
dispatch_queue_t queue = dispatch_queue_create ("Cn.heima.queue", NULL);
* Home row: Let the task execute on the main thread
dispatch_queue_t queue = Dispatch_get_main_queue ();
2. Functions that perform tasks
1> synchronous execution: Does not have the ability to open new threads
Dispatch_sync ...
2> Asynchronous execution: Ability to open new threads
Dispatch_async ...
3. Common combinations (master)
1> dispatch_async + global concurrency queue
2> Dispatch_async + self-created serial queue
4. Communication between threads (mastering)
Dispatch_async (Dispatch_get_global_queue (dispatch_queue_priority_default, 0), ^{
Perform time-consuming asynchronous operations ...
Dispatch_async (Dispatch_get_main_queue (), ^{
Go back to the main thread and perform a UI refresh operation
});
});
All 5.GCD APIs are automatically imported into this library at Libdispatch.dylib,xcode.
* Main header file: #import <dispatch/dispatch.h>
6. Deferred Execution (master)
1> perform ....
After 3 seconds automatically returns to the current thread called Self's Download: method, and passes the parameter: @ "Http://555.jpg"
[Self performselector: @selector (Download:) withobject:@ "http://555.jpg" afterdelay:3];
2> Dispatch_after ...
Which queue the task is placed in to execute
dispatch_queue_t queue = Dispatch_get_global_queue (Dispatch_queue_priority_default, 0);
Double delay = 3; How many seconds are delayed
Dispatch_after (Dispatch_time (Dispatch_time_now, (int64_t) (Delay * nsec_per_sec)), queue, ^{
Tasks that need to be performed after 3 seconds
});
7. Disposable code (Master)
Static dispatch_once_t Oncetoken;
Dispatch_once (&oncetoken, ^{
The code inside is always executed 1 times during the program's operation.
});
Four, Singleton mode (lazy type)
1.ARC
@interface Hmdatatool:nsobject
+ (instancetype) Shareddatatool;
@end
@implementation Hmdatatool
Used to save unique singleton objects
Static ID _instace;
+ (ID) allocwithzone: (struct _nszone *) zone
{
Static dispatch_once_t Oncetoken;
Dispatch_once (&oncetoken, ^{
_instace = [Super Allocwithzone:zone];
});
return _instace;
}
+ (Instancetype) Shareddatatool
{
Static dispatch_once_t Oncetoken;
Dispatch_once (&oncetoken, ^{
_instace = [[Self alloc] init];
});
return _instace;
}
-(ID) Copywithzone: (Nszone *) zone
{
return _instace;
}
@end
2. Non-arc
@interface Hmdatatool:nsobject
+ (instancetype) Shareddatatool;
@end
@implementation Hmdatatool
Used to save unique singleton objects
Static ID _instace;
+ (ID) allocwithzone: (struct _nszone *) zone
{
Static dispatch_once_t Oncetoken;
Dispatch_once (&oncetoken, ^{
_instace = [Super Allocwithzone:zone];
});
return _instace;
}
+ (Instancetype) Shareddatatool
{
Static dispatch_once_t Oncetoken;
Dispatch_once (&oncetoken, ^{
_instace = [[Self alloc] init];
});
return _instace;
}
-(ID) Copywithzone: (Nszone *) zone
{
return _instace;
}
-(OneWay void) Release {
}
-(ID) retain {
return self;
}
-(Nsuinteger) Retaincount {
return 1;
}
-(ID) autorelease {
return self;
}
@end
V. Nsoperation and Nsoperationqueue
1. Types of queues
1> Home Row
* [Nsoperationqueue Mainqueue]
* Actions added to the "home column" will be placed in the main thread to execute
2> Non-Home row
* [[Nsoperationqueue alloc] init]
* Actions added to the "non-Home column" will be placed in the child thread execution
2. Queue Add Task
*-(void) Addoperation: (Nsoperation *) op;
*-(void) Addoperationwithblock: (void (^) (void)) block;
3. Common usage
1> Setting the maximum number of concurrent
-(Nsinteger) Maxconcurrentoperationcount;
-(void) Setmaxconcurrentoperationcount: (Nsinteger) CNT;
2> Other operations on the queue
* Cancel All operations
-(void) cancelalloperations;
* Pause All operations
[Queue Setsuspended:yes];
* Restore all operations
[Queue Setsuspended:no];
4. Dependencies between operations (interview questions)
* Dependencies can be set between nsoperation to guarantee the order of execution
* [Operationb Adddependency:operationa];
Operation B depends on operation A, and operation A is performed before Operation B is performed.
* Note: cannot rely on each other, such as a dependent b,b dependency a
* You can create a dependency between nsoperation of different queue
5. Communication between threads
Nsoperationqueue *queue = [[Nsoperationqueue alloc] init];
[Queue addoperationwithblock:^{
1. Perform some more time-consuming operations
2. Go back to the main thread
[[Nsoperationqueue Mainqueue] addoperationwithblock:^{
}];
}];
Vi. ways to return to the main thread from other threads
1.perform ...
[Self performselectoronmainthread:<# (SEL) #> withobject:<# (ID) #> waituntildone:<# (BOOL) #>];
2.GCD
Dispatch_async (Dispatch_get_main_queue (), ^{
});
3.NSOperationQueue
[[Nsoperationqueue Mainqueue] addoperationwithblock:^{
}];
Vii. Judging the compiler's environment: ARC or MRC?
#if __has_feature (OBJC_ARC)
The current compiler environment is arc
#else
The current compiler environment is MRC
#endif
Methods of initialization of classes
1.+ (void) load
* When a class is first mounted to the OC Runtime System (memory), it is called
* It will be called when the program starts
* The program will only be called 1 times during operation.
2.+ (void) Initialize
* When a class is first used (such as calling a method of a class), it invokes the
* Not called when a program starts
3. In the process of running the program: 1 classes of an operation, only want to execute 1 times, then this operation is placed in the + (void) Load method The most appropriate
IX. recommendations for the use of third-party frameworks
1. Purpose of the third-party framework
1> Development efficiency: rapid development, people wrapped up a line of code top of their own write n line
2> to use the best implementation of this feature
2. Excessive third-party frameworks, many disadvantages (negligible)
1> management, upgrades, updates
2> third-party framework has bugs waiting for the author to resolve
3> the author of a third-party framework unfortunately dies, stops updating (potential bug unsolved)
4> feeling: own good water
3. For example,
Stream media: Play online video, audio (side download side play)
Know the format of audio and video files very well
Each video has its own decoding method (c\c++)
4. Summary
1> standing on the shoulders of giants programming
2>, it's all right. Use a more stable third-party framework
Ten, the cell image download
1. Face Questions
1> How to prevent a URL corresponding to the picture repeated download
* "Cell download Picture idea – there is a sandbox cache"
What is the default cache duration for 2> sdwebimage?
* 1 weeks
3> Sdwebimage How does the bottom layer come true?
* Class ppt "Cell download Picture ideas – there is a sandbox cache"
2.SDWebImage
1> Common methods
-(void) Sd_setimagewithurl: (nsurl *) URL placeholderimage: (UIImage *) placeholder;
-(void) Sd_setimagewithurl: (nsurl *) URL placeholderimage: (UIImage *) placeholder options: (sdwebimageoptions) options;
-(void) Sd_setimagewithurl: (nsurl *) URL placeholderimage: (UIImage *) placeholder completed: ( Sdwebimagecompletionblock) Completedblock;
-(void) Sd_setimagewithurl: (nsurl *) URL placeholderimage: (UIImage *) placeholder options: (sdwebimageoptions) options Progress: (Sdwebimagedownloaderprogressblock) Progressblock completed: (sdwebimagecompletionblock) CompletedBlock;
2> Memory Processing: When the app receives a memory warning
/**
* When the app receives a memory warning
*/
-(void) applicationdidreceivememorywarning: (uiapplication *) application
{
Sdwebimagemanager *mgr = [Sdwebimagemanager Sharedmanager];
1. Cancel the operation being downloaded
[Mgr Cancelall];
2. Clear the Memory cache
[Mgr.imagecache Clearmemory];
}
3> sdwebimageoptions
* sdwebimageretryfailed: After the download fails, it will be automatically re-downloaded
* Sdwebimagelowpriority: Automatically pauses some internal download operations while UI interaction is in progress
* sdwebimageretryfailed | Sdwebimagelowpriority: Has the above 2 functions
ios-Multithreading Notes