苹果实现内存对齐方案
苹果实现内存字节对齐的代码如下:
#ifdef __LP64__
# define WORD_SHIFT 3UL
# define WORD_MASK 7UL
# define WORD_BITS 64
#else
# define WORD_SHIFT 2UL
# define WORD_MASK 3UL
# define WORD_BITS 32
#endif
static inline uint32_t word_align(uint32_t x) {
return (x + WORD_MASK) & ~WORD_MASK;
}
不同方案对比:
func word_align(x: UInt32) -> UInt32 {
// return (x + 7) / 8 * 8 //方案1,相对位运算效率要低
// return ((x + 7) >> 3) << 3 //方案2,通过右移左移,低三位清0
return (x + 7) & (~7) //苹果方案,另一种低三位清0方式
}
联合体union经常用MASK取出某几位的值
Optional的实用扩展
在swift中经常要对Optional类型进行判空处理,所以对其进行扩展方便使用:
extension Optional {
/// 可选值为空的时候返回 true
var isNone: Bool {
switch self {
case .none:
return true
case .some:
return false
}
}
/// 可选值非空返回 true
var isSome: Bool {
return !isNone
}
}
如果是String?,同时进行空串判断可用where语句对Optional的关联的范型Wrapped进行约束:
extension Optional where Wrapped: StringProtocol {
// or : 'Wrapped: StringProtocol' replace with 'Wrapped == String'
var isNoneOrEmppty: Bool {
return isNone || self!.isEmpty
}
}
项目问题记录
scheme跳转特殊字符编码问题
在使用scheme跳转中,有可能会遇到value中含有特殊字符,如: {}等。造成URL解析失败,不能跳转,因此需要对scheme进行一次encode,对特殊字处理。
编码方法:
func addingPercentEncoding(withAllowedCharacters allowedCharacters: CharacterSet) -> String?
解码方法:
var removingPercentEncoding: String? { get }
Thread 1: Fatal error: init(coder:) has not been implemented
自定义view然后使用xib去加载这个view。运行然后就crash了:
Thread 1: Fatal error: init(coder:) has not been implemented
解决方案
将
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
改为调用父类方法就好了:
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
通用链接跳转
在配置通用链接文件apple-app-site-association的时候,path不支持字符#,带有#会没有效果。
lldb
反汇编地址: dis -s +地址
cell中label自适应
在一个cell内只有一个label的情况下,要实现cell高度自适应,需要:
1.UITableViewDelegate实现:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
2.label上下左右约束与cell关联上。
3.label设置好文字后要调用sizeToFit()方法,然后就会撑满cell了。