IOS multithreading and other supplements 02, ios multithreading supplements 02

Source: Internet
Author: User
Tags delete cache install cocoapods

IOS multithreading and other supplements 02, ios multithreading supplements 02

  • NSOperation

    • NSOperation is an abstract class and does not have the ability to encapsulate operations. It must be used as a subclass.
  • NSInvocationOperation

    • If you directly execute the operation in NSInvocationOperation, It will be executed in the main thread by default.
    •  NSInvocationOperation *op1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(demo) object:nil]; [op1 start];

       

  • NSBlockOperation
    • If only one operation is encapsulated, it is executed in the main thread by default.
    • If multiple operations are encapsulated, all operations except the first one will be executed in the Child thread.
    • NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{        NSLog(@"1- %@", [NSThread currentThread]);    }];[op1 start];

       

  • Custom Operation
      • @implementation XMGOperation- (void)main{    NSLog(@"%s, %@", __func__,[NSThread currentThread]);}@end

         

  • NSOperationQueue
  • Comparison between GCD queue and NSOperationQueue

    • GCD
      • Serial: self-created, main queue
      • Concurrency: self-created, global
      NSOperationQueue
      • Self-created: alloc/init
      • Main queue: mainQueue
  • NSOperationQueue features

    • Add taskCreate by yourselfNew threads are enabled in the queue.
      • Concurrency by default: maxConcurrentOperationCount-1
      • Serial: maxConcurrentOperationCount = 1
    • Add taskmainQueueNew threads are not enabled in the queue
  • Invocation

      • // 1. create a queue NSOperationQueue * queue = [[NSOperationQueue alloc] init]; // 2. encapsulation task NSInvocationOperation * op1 = [[NSInvocationOperation alloc] initWithTarget: self selector: @ selector (demo) object: nil]; // 3. add the task to the queue [queue addOperation: op1];

         

  • Block
      • // 1. create a queue NSOperationQueue * queue = [[NSOperationQueue alloc] init]; // 2. encapsulation task NSBlockOperation * op1 = [NSBlockOperation blockOperationWithBlock: ^ {NSLog (@ "1 = % @", [NSThread currentThread]);}]; // 3. add the task to the queue [queue addOperation: op1]; // 1. create a queue NSOperationQueue * queue = [[NSOperationQueue alloc] init]; // The addOperationWithBlock method will do two things // 1. create an NSBlockOperation object based on the input block // 2. add the NSBlockOperation object created internally to the queue. // 2. add the task to the queue [queue addOperationWithBlock: ^ {NSLog (@ "1 =%@", [NSThread currentThread]) ;}]; [queue addOperationWithBlock: ^ {NSLog (@ "2 = % @", [NSThread currentThread]);}];

         

  • Custom
      • // 1. create a queue NSOperationQueue * queue = [[NSOperationQueue alloc] init]; // 2. encapsulate the task JXOperation * op1 = [[JXOperation alloc] init]; // 3. add the task to the queue [queue addOperation: op1];

         

  • Pause-resume
      • The task is not paused.
      • Will resume execution from the first unexecuted task
      • // If YES, it indicates the pause is required. // If NO, it indicates that self. queue. suincluded = YES is resumed;

         

  • Cancel
      • The task being executed is not canceled.
      • Task cannot be restored after cancellation
      • The time-consuming operation should not be executed for a period of time.
      • // The cancel Method of all tasks is called internally [self. queue cancelAllOperations];

         

  • Inter-thread Communication
      • NSOperationQueue * queue = [[NSOperationQueue alloc] init]; // enable the subthread [queue addOperationWithBlock: ^ {// return to the main thread [[NSOperationQueue mainQueue] addOperationWithBlock: ^ {}] ;}];

         

  • Dependency and listener
      • The current task is executed only when the dependent task is completed.
      • Cross-queue dependency
      • [OperationB addDependency: operationA]; // operation B depends on operation A op1.completionBlock =^{ NSLog (@ "the first image has been downloaded ");}; op2.completionBlock = ^ {NSLog (@ "the second image has been downloaded ");};

         

  • Image download
      • Repeated download problems
        • Define the dictionary to save the downloaded Image
      • Disk cache Problems
        • The memory has not been retrieved from the disk.
      • Main thread Blocking
        • Create NSOperationQueue download Image
      • Repeated settings
        • ReloadRowsAtIndexPaths
      Logic 1-never downloaded 1. check whether there are images in the memory cache. 2. check whether the disk cache has images. 3. you have a task to download the current image. enable task download image 5. write to disk 6. cache to memory 7. delete download operation 8. show image logic 2-downloaded 1. check whether there are images in the memory cache. 2. check whether the disk cache has images. 3. use disk cache 4. cache the image to the memory. update UI logic 3-downloaded and not restarted 1. check whether there are images in the memory cache. 2. update the UI
  • Directory structure
  • Documents

      • Files or data generated by the application itself need to be saved, such as drawing of game progress and graffiti software.
      • Files in the directory will be automatically stored in the iCloud
      • Note: Do not save the files downloaded from the network. Otherwise, they cannot be mounted!
      • Caches

        • Save temporary files and "need to be used later", such as cache images and offline data (map data)
        • The system does not clear files in the cache directory.
        • When the program is required to be developed, "the cache directory cleaning solution must be provided"
      • Preferences

        • User preference: Use NSUserDefault to directly read and write!
        • If you want to write data to the disk in time, you also need to call a synchronization method.
      • Tmp

        • Save the temporary file, "No need to use later"
        • Files in the tmp directory are automatically cleared.
        • Restart the phone, and the tmp directory will be cleared.
        • When the system disk space is insufficient, the system automatically clears the disk space.
      • Encapsulation Method for obtaining the file path

      • -(NSString *) cacheDir {// 1. obtain the cache directory NSString * dir = [NSSearchPathForDirectoriesInDomains (NSCachesDirectory, NSUserDomainMask, YES) lastObject]; return [dir stringByAppendingPathComponent: [self lastPathComponent *) documentDir {NSString * dir = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; return [dir stringByAppendingPathComponent: [self lastPathComponent];}-(NSString *) tmpDir {NSString * dir = NSTemporaryDirectory (); return [dir stringByAppendingPathComponent: [self lastPathComponent];}

         

    • SDWebImage Architecture
    • SDWebImageManager

      • SDImageCache
      • SDWebImageDownloader
        • SDWebImageDownloaderOperation
    • SDWebImage FAQ

    • Default Cache Time

      • One week
    • Cache address

      • NSString * fullNamespace = [@ "com. hackemist. SDWebImageCache." stringByAppendingString: ns];
    • How does cleanDisk clear expired images?

      • Delete objects earlier than the expiration date
      • Save file attributes to calculate disk cache space occupied
      • If the remaining disk cache space exceeds the maximum limit, perform the cleanup operation again to delete the earliest files.
    • How to clear a clearDisk

      • Delete cache directory
      • Create cache directory
    • How to play images with SDWebImage

      • Each frame in the gif is taken and an animated image is generated.
    • How does SDWebImage determine the image type?

      • Determine the first 8 bytes of the Image Binary
      • KPNGSignatureBytes [8] = {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A };
    • What is CocoaPods?

      • CocoaPods is a dependency management tool for developing third-party libraries for OS X and iOS applications. With CocoaPods, you can define your own dependencies (called pods). With time changes, it is very convenient to manage versions of third-party libraries throughout the development environment.
    • The concepts behind CocoaPods are mainly embodied in two aspects:

      • Introducing third-party code in a project involves a lot of content. For Junior Objective-C developers, project file configuration can be frustrating.
      • Many human errors may occur during buildphases and linker flags configuration.
      • CocoaPods simplifies all of this and can automatically configure compilation options.
    • CocoaPods principles

      • It puts all the dependent libraries in another project named Pods, and then allows the main project to depend on the Pods project. In this way, the source code management work is moved from the main project to the Pods project.
      • 1. the Pods project will eventually compile into a file named libPods. a. The main project only needs to rely on this. a file.
      • 2. for resource files, CocoaPods provides a bash script named Pods-resources.sh, which is executed every time the project is compiled, copying various resource files from third-party libraries to the directory.
      • 3. CocoaPods uses a file named Pods. xcconfig to set all dependencies and parameters during compilation.
    • CocoaPods Installation

      • Update gem
        • Sudo gem update -- system
      • Update ruby software sources
        • Gem sources -- remove https://rubygems.org/
        • Gem sources-a http://ruby.taobao.org/
        • Gem sources-l
      • Install CocoaPods
        • Sudo gem install cocoapods
      • Replace CocoaPods image Index
        • Pod repo remove master
        • Pod repo add master http://git.oschina.net/akuandev/Specs.git
        • Pod repo add master https://gitcafe.com/akuandev/Specs.git
        • Pod repo update
      • Set pod Repository
        • Pod setup
      • Test
        • Pod -- version
    • Uninstall CocoaPods

      • Sudo gem uninstall cocoapods
    • CocoaPods usage:

      • Create a new file named Podfile
      • List the dependent library names in the file in sequence
    platform :iospod'AFNetworking'
    • Comments
      • 1. After using the CocoPods Management Library, open the project with xxxx. xcworkspace later, instead of the previous. xcodeproj file.
      • 2. Every time you change the Podfile file, you need to re-execute the pod update command.
      • 3. When executing pod install and pod update, CocoaPods will update the CocoPods spec repository index by default. You can use the -- no-repo-update parameter to disable INDEX update.
    pod install --no-repo-updatepod update --no-repo-update

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.