NSURL
- +URLWithString:relativeToURL:
可以根據(jù)一個 base URL 地址和關(guān)聯(lián)字符串來構(gòu)造 URL。
NSURL *url = [NSURL URLWithString:@"..." relativeToURL: baseURL];
NSDictionary
- addEntriesFromDictionary:dic
使用來拼接字典,為現(xiàn)有字典體添加數(shù)據(jù)
[params addEntriesFromDictionary:(NSDictionary *)newParams];
dispatch_ _semaphore__t semaphore
多線程之間的同步
信號量為0則阻塞線程,大于0則不會阻塞。則我們通過改變信號量的值,來控制是否阻塞線程,從而達(dá)到線程同步。
- 創(chuàng)建信號量,可以設(shè)置信號量的資源數(shù)。0表示沒有資源,調(diào)用dispatch_semaphore_wait會立即等待。
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
- 等待信號,當(dāng)信號總量少于0的時候就會一直等待,否則就可以正常的執(zhí)行,并讓信號總量-1
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
- 發(fā)送一個信號,信號總量+1如果等待線程被喚醒則返回非0,否則返回0。
dispatch_semaphore_signal(semaphore);
??1:
//并發(fā)隊列
dispatch_queue_t concurrentQueue = dispatch_queue_create("com.gcd.concurrentQueue", DISPATCH_QUEUE_CONCURRENT);
__block NSString *strTest = @"test";
dispatch_async(concurrentQueue, ^{
if ([strTest isEqualToString:@"test"]) {
NSLog(@"--%@--1-", strTest);
[NSThread sleepForTimeInterval:1];
if ([strTest isEqualToString:@"test"]) {
[NSThread sleepForTimeInterval:1];
NSLog(@"--%@--2-", strTest);
} else {
NSLog(@"====changed===");
}
}
});
dispatch_async(concurrentQueue, ^{
NSLog(@"--%@--3-", strTest);
});
dispatch_barrier_async(concurrentQueue, ^{
strTest = @"modify";
NSLog(@"--%@--4-", strTest);
});
dispatch_async(concurrentQueue, ^{
NSLog(@"--%@--5-", strTest);
});
??2:
// 創(chuàng)建隊列組
dispatch_group_t group = dispatch_group_create();
// 創(chuàng)建信號量,并且設(shè)置值為10
dispatch_semaphore_t semaphore = dispatch_semaphore_create(10);
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
for (int i = 0; i < 100; i++)
{ // 由于是異步執(zhí)行的,所以每次循環(huán)Block里面的dispatch_semaphore_signal根本還沒有執(zhí)行就會執(zhí)行dispatch_semaphore_wait,從而semaphore-1.當(dāng)循環(huán)10此后,semaphore等于0,則會阻塞線程,直到執(zhí)行了Block的dispatch_semaphore_signal 才會繼續(xù)執(zhí)行
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
dispatch_group_async(group, queue, ^{
NSLog(@"%i",i);
sleep(2);
// 每次發(fā)送信號則semaphore會+1,
dispatch_semaphore_signal(semaphore);
});
}