【Coding】【1】iOS常用代码(一)

本文最后更新于:2021年12月22日 上午

【Coding】系列目录


目录

1. 信号量

2. NSCopying与NSMutableCopying

3. 单例

4. Group Notify

5. Operation Dependency

6. 延迟执行

7. 视图转换与判定

  (1). 判定点在不在视图内部

  (2). 视图转换

8. 系统字典转模型

9. 读取文件

  (1). 读取Data

  (2). 读取Image

10. FMDB创建数据库


内容

1. 信号量

创建信号量->等待信号量->提高信号量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

dispatch_semaphore_t signal;

signal = dispatch_semaphore_create(0);

__block long x = 0;

NSLog(@"0 --> x:%ld",x);

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(@"sleep 1");
sleep(1);
NSLog(@"sleep 1 finish, begin signal 1");
x = dispatch_semaphore_signal(signal);
NSLog(@"signal 1 --> x:%ld",x);

NSLog(@"sleep 2");
sleep(2);
NSLog(@"sleep 2 finish, begin signal 2");
x = dispatch_semaphore_signal(signal);
NSLog(@"signal 2 --> x:%ld",x);

NSLog(@"sleep 3");
sleep(3);
NSLog(@"sleep 3 finish, begin signal 3");
x = dispatch_semaphore_signal(signal);
NSLog(@"signal 3 --> x:%ld",x);
});

NSLog(@"wait 1 begin");
x = dispatch_semaphore_wait(signal, DISPATCH_TIME_FOREVER);
NSLog(@"wait 1 finish");
NSLog(@"wait 1 --> x:%ld",x);

NSLog(@"wait 2 begin");
x = dispatch_semaphore_wait(signal, DISPATCH_TIME_FOREVER);
NSLog(@"wait 2 finish");
NSLog(@"wait 2 --> x:%ld",x);

NSLog(@"wait 3 begin");
x = dispatch_semaphore_wait(signal, DISPATCH_TIME_FOREVER);
NSLog(@"wait 3 finish");
NSLog(@"wait 3 --> x:%ld",x);

2. NSCopying与NSMutableCopying

NSCopying用法

1
2
3
4
5
6
7
8
- (id)copyWithZone:(nullable NSZone *)zone {
Person *model = [[[self class] allocWithZone:zone] init];
model.firstName = self.firstName;
model.lastName = self.lastName;
//未公开的成员
model->_nickName = _nickName;
return model;
}

NSMutableCopying用法

1
2
3
4
5
6
7
8
- (id)mutableCopyWithZone:(nullable NSZone *)zone {
Person *model = [[[self class] allocWithZone:zone] init];
model.firstName = self.firstName.mutableCopy;
model.lastName = self.lastName.mutableCopy;
//未公开的成员
model->_nickName = _nickName.mutableCopy;
return model;
}

3. 单例

Objc

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
static AppSingleton * __instance;

+ (instancetype)shareInstance {

return [self alloc];
}

+(instancetype)allocWithZone:(struct _NSZone *)zone {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
__instance = [[super allocWithZone:zone] init];
});

return __instance;
}

-(id)copyWithZone:(NSZone *)zone {
return self;
}

- (instancetype)init {
if (self = [super init]) {

}
return self;
}

Swift

1
2
3
4
5
6
7
8
class Singleton {
static let sharedInstance: Singleton = {
let instance = Singleton()
// setup code

return instance
}()
}

4. Group Notify

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// 全局变量group
dispatch_group_t group = dispatch_group_create();
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

// 进入组(进入组和离开组必须成对出现, 否则会造成死锁)
dispatch_group_enter(group);
dispatch_group_async(group, queue, ^{
NSLog(@"1");
//离开组
dispatch_group_leave(group);
});

dispatch_group_enter(group);
dispatch_group_async(group, queue, ^{
NSLog(@"2");
dispatch_group_leave(group);
});

dispatch_group_notify(group, queue, ^{ // 监听组里所有线程完成的情况
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSLog(@"任务1,2已完成");
});
});

5. Operation Dependency

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//创建队列
NSOperationQueue *queue=[[NSOperationQueue alloc] init];

//创建操作
NSBlockOperation *operation1=[NSBlockOperation blockOperationWithBlock:^(){
NSLog(@"执行第1次操作,线程:%@",[NSThread currentThread]);
}];
NSBlockOperation *operation2=[NSBlockOperation blockOperationWithBlock:^(){
NSLog(@"执行第2次操作,线程:%@",[NSThread currentThread]);
}];
NSBlockOperation *operation3=[NSBlockOperation blockOperationWithBlock:^(){
NSLog(@"执行第3次操作,线程:%@",[NSThread currentThread]);
}];

//添加依赖
[operation1 addDependency:operation2];
[operation2 addDependency:operation3];

//将操作添加到队列中去
[queue addOperation:operation1];
[queue addOperation:operation2];
[queue addOperation:operation3];

6. 延迟执行

OC
1
2
3
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

});

Swift

1
2
3
DispatchQueue.main.asyncAfter(deadline: .now() + DispatchTimeInterval.seconds(2)) {

}

7. 视图转换与判定

(1). 判定点在不在视图内部

1
2
3
4
5
6
7
8
CGPoint point = [tap locationInView:self.extraView.superview];

if (CGRectContainsPoint(self.extraView.frame, point)) {
NSLog(@"包含");
}else {
NSLog(@"不包含");
}

(2). 视图转换

坐标点转换

1
2
- (CGPoint)convertPoint:(CGPoint)point fromView:(UIView *)view;
- (CGPoint)convertPoint:(CGPoint)point toView:(UIView *)view;

区域转换

1
2
- (CGRect)convertRect:(CGRect)rect fromView:(UIView *)view;
- (CGRect)convertRect:(CGRect)rect toView:(UIView *)view;

8. 系统字典转模型

有两个model,一个Weather,一个Weathers
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

@interface Weathers : NSObject

/// 城市个数
@property (nonatomic, assign) NSInteger count;

/// 多个城市的天气数组
@property (nonatomic, copy) NSArray<Weather *> *list;

/// 服务端返回的是id
@property (nonatomic, copy) NSString *iden;

- (instancetype)initWithDictionary:(NSDictionary *)dictionary;

@end

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
@implementation Weathers

- (instancetype)initWithDictionary:(NSDictionary *)dictionary {
if ([dictionary isKindOfClass:[NSDictionary class]]) {
if (self = [super init]) {
[self setValuesForKeysWithDictionary:dictionary];
}
return self;
} else {
return nil;
}
}

- (void)setValue:(id)value forKey:(NSString *)key {
if ([value isKindOfClass:[NSNull class]]) {
return;
}
if ([value isKindOfClass:[NSArray class]]) {
if ([key isEqualToString:@"list"]) {
NSMutableArray *array = @[].mutableCopy;
for (NSDictionary *dic in value) {
MVVMWeather *w = [[MVVMWeather alloc] initWithDictionary:dic];
[array addObject:w];
}
self.list = array;
}
}

[super setValue:value forKey:key];
}

// ignore undefined key
- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
if ([key isEqualToString:@"id"]) {
_iden = value;
return;
}
}

@end

9. 读取文件

(1).读取Data

1
2
NSFileManager *fm = [NSFileManager defaultManager];
NSData *data = [fm contentsAtPath:filePath];
1
NSData *data = [NSData dataWithContentsOfFile:filePath];

(2).读取Image

1
UIImage *image = [UIImage imageWithContentsOfFile:filePath];

10. FMDB创建数据库

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
func createDb(inPath path: String) {

// 1.通过路径创建数据库
let db = FMDatabase(path: path)

// 2.打开数据库
if db.open() {
let sql = "CREATE TABLE IF NOT EXISTS t_name (ip TEXT, password TEXT, PRIMARY KEY(ip));"
let success = db.executeUpdate(sql, withArgumentsIn: [])
if (success) {
print("创建表成功")
} else {
print("创建表失败")
}
} else {
print("打开失败")
}
}

联系方式

邮箱: adrenine@163.com