1. 程式人生 > >RunLoop在專案中的應用

RunLoop在專案中的應用

//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;

}