RunLoop在项目中的应用

源码:https://github.com/baitxaps/Block

//1.AFNetworkingRunLoop的创建

- (void)netWorkRequestThreadEntryPoint:(id)__unused  object{

    @autoreleasepool {

        [[NSThreadcurrentThread]setName:@"AFNetworking"];

        

        NSRunLoop *runLoop = [NSRunLoopcurrentRunLoop];

        [runLoop addPort:[NSMachPortport] forMode:NSDefaultRunLoopMode];

        

        [runLoop run];

    }

}


- (NSThread *)networkRequestThread{

    static NSThread *_networkRequestThread =nil;

    static dispatch_once_t oncePreadicate;

    dispatch_once(&oncePreadicate, ^{

        _networkRequestThread = [[NSThread alloc]initWithTarget:selfselector:@selector(netWorkRequestThreadEntryPoint:)object:nil];

        [_networkRequestThread start];

    });

    return _networkRequestThread;

}


//2.接到crashsingal后动重启RunLoop

- (void)restartRuningRunLoop{

    CFRunLoopRef runloop =CFRunLoopGetCurrent();

    NSArray *allModes =CFBridgingRelease(CFRunLoopCopyAllModes(runloop));

    while(1){

        for(NSString *modein allModes){

            CFRunLoopRunInMode((CFStringRef)mode,0.001,false);

        }

    }

}

//3.TableView 延迟加载图片新思路

#if TARGET_OS_IPHONE

UIImageView *imageView;

- (void)delayLoadingImage{

    

    UIImage *downLoadImage = nil;

    [imageView performSelector:@selector(setImage:)

                    withObject:downLoadImage

                    afterDelay:0

                       inModes:@[NSDefaultRunLoopMode]]

}

#elif TARGET_OS_MAC

//...

#endif


- (void)content:(NSString *(^)(NSString * content))block{

    

}


//4.异步测试

- (void)runUnitlBlock:(BOOL(^)())block timeout:(NSTimeInterval)timeout{

    NSDate *timeoutDate = [NSDatedateWithTimeIntervalSinceNow:timeout];

    do{

        CFTimeInterval quantum = 0.0001;

        CFRunLoopRunInMode(kCFRunLoopDefaultMode,quantum,false);

    }while ([timeoutDate timeIntervalSinceNow]>0 &&!block()) ;

}


//4.1升级版异步测试

- (BOOL)upgradeRunUnitlBlock:(BOOL(^)())block timeout:(NSTimeInterval)timeout{

    __block Boolean fulfilled =NO;

    void(^beforeWaiting)(CFRunLoopObserverRef observer,CFRunLoopActivity activity)=

    ^(CFRunLoopObserverRef observer,CFRunLoopActivity activity){

        fulfilled = block();

        if (fulfilled) {

            CFRunLoopStop(CFRunLoopGetCurrent());

        }

    };

    

    CFRunLoopObserverRef observer =CFRunLoopObserverCreateWithHandler(NULL,\

                                  kCFRunLoopBeforeWaiting,true, 0, beforeWaiting);

    

    CFRunLoopAddObserver(CFRunLoopGetCurrent(), observer,kCFRunLoopDefaultMode);

    

    //run

    CFRunLoopRunInMode(kCFRunLoopDefaultMode, timeout,false);

    CFRunLoopRemoveObserver(CFRunLoopGetCurrent(), observer,kCFRunLoopDefaultMode);

    CFRelease(observer);

    

    return fulfilled;

}



你可能感兴趣的:(iOS)