NSURL
- +URLWithString:relativeToURL:
可以根据一个 base URL 地址和关联字符串来构造 URL。
NSURL *url = [NSURL URLWithString:@"..." relativeToURL: baseURL];
NSDictionary
- addEntriesFromDictionary:dic
使用来拼接字典,为现有字典体添加数据
[params addEntriesFromDictionary:(NSDictionary *)newParams];
dispatch_ _semaphore__t semaphore
多线程之间的同步
信号量为0则阻塞线程,大于0则不会阻塞。则我们通过改变信号量的值,来控制是否阻塞线程,从而达到线程同步。
- 创建信号量,可以设置信号量的资源数。0表示没有资源,调用dispatch_semaphore_wait会立即等待。
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
- 等待信号,当信号总量少于0的时候就会一直等待,否则就可以正常的执行,并让信号总量-1
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
- 发送一个信号,信号总量+1如果等待线程被唤醒则返回非0,否则返回0。
dispatch_semaphore_signal(semaphore);
🌰1:
//并发队列
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:
// 创建队列组
dispatch_group_t group = dispatch_group_create();
// 创建信号量,并且设置值为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++)
{ // 由于是异步执行的,所以每次循环Block里面的dispatch_semaphore_signal根本还没有执行就会执行dispatch_semaphore_wait,从而semaphore-1.当循环10此后,semaphore等于0,则会阻塞线程,直到执行了Block的dispatch_semaphore_signal 才会继续执行
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
dispatch_group_async(group, queue, ^{
NSLog(@"%i",i);
sleep(2);
// 每次发送信号则semaphore会+1,
dispatch_semaphore_signal(semaphore);
});
}