Swift笔记 - 15.选择器、String、桥接、可选协议、KVC、KVO、关联属性、资源管理
Swift笔记 - 15.选择器、String、桥接、可选协议、KVC、KVO、关联属性、资源管理
选择器
- Swift中依然可以使用选择器,使用
#selector(name)
定义一个选择器- 必须是被
@objcMembers
或@objc
修饰的方法才可以定义选择器
- 必须是被
@objcMembers class Person: NSObiect {
func test1(v1: Int) { print ("test1") }
func test2(v1: Int, v2: Int) { print("test2(v1:v2:)") }
func test2(_ v1: Double, _ v2: Double) { print("test2(_:_:)") }
func run() {
perform(#selector(test1))
perform(#selector(test1(v1:)))
perform(#selector(test2(v1:v2: )))
perform(#selector(test2(_: : ))) -> Void))
perform(#selector(test2 as (Double, Double) -> Void)!
}
}
String
- String的插入删除
var str = "1 2"
// 1 2
str.insert(".", at: str.endIndex)
/1 12 3 4
str.insert(contentsof: "3_4", at: str.endIndex)
// 1666 2 3 4
str.insert (contentsOf: "666", at: str.index(after: str.startIndex))
// 1666 2 3 8884
str.insert (contentsOf: "888", at: str.index(before: str.endIndex))
// 1666hello 2 3 8884
str.insert(contentsOf: "hello", at: str.index(str.startIndex, offsetBy: 4))
// 666hello 2 3 8884
str.remove(at: str.firstIndex(of: "1") !)
// hello 2 3 8884
str.removeAll { $0 == "6" }
var range = str.index(str.endIndex, offsetBy: -4)..<str.index(before: str.endIndex)
// hello 2 3 4
str.removeSubrange ( range)
- SubString
- String可以通过下标、
prefix
、suffix
等截取子串,子串类型不是String,而是Substring
- String可以通过下标、
var str = "1 2 3 4 5"
// 1 2
var substr1 = str.prefix(3)
11 45
var substr2 = str.suffix(3)
// 1 2
var range = str.startIndex..<str.index(str.startIndex, offsetBy: 3)
var substr3 = str[range]
// 最初的String. 1_2_3_4_5
print (substr3. base)
// Substring -> String
var str2 = String(substr3)
- Substring和它的base,共享字符串数据
-
Substring转为String时,会重新分配新的内存存储字符串数据
- String 相关的协议
Bidirectionalcollection
协议包含的部分内容startIndex
、endIndex
属性、index
方法String
、Array
都遵守了这个协议
RangeReplaceablecollection
协议包含的部分内容append
、insert
、remove
方法String
、Array
都遵守了这个协议
Dictionary
、Set
也有实现上述协议中声明的一些方法,只是并没有遵守上述协议
- String 与 NSString
- String 与 NSString之间可以随时随地桥接转换
- 如果你觉得 String 的API过于复杂难用。可以考虑将 String转为NSString
- String 与 NSString之间可以随时随地桥接转换
var str1: String = "jack"
var str2: NSString = "rose"
var str3 = str1 as NSString
var str4 = str2 as String
// ja
var str5 = str3.substring(with: NSRange(location: 0, length: 2))
print(str5)
- 比较字符串内容是否等价
- String使用==运算符
- NSString使用isEqual方法,也可以使用==运算符(本质还是调用了isEqual方法)
Swift、OC桥接转换表
只能被class继承的协议
protocol Runnablel: AnyObject {}
protocol Runnable2: class {}
@obic protocol Runnable3 {}
- 被
@objc
修饰的协议,还可以暴露给OC去遵守实现
可选协议
- 可以通过
@objc
定义可选协议,这种协议只能被class
遵守
@objc protocol Runnable {
func run1()
@objc optional func run2()
func run3()
}
class Dog: Runnable {
func run3() { print ("Dog run3") }
func run1() { print ("Dog run1") }
}
var d = Dog()
d.run1() // Dog run1
d.run3 () // Dog run3
@objc dynamic
- 被
@objc dynamic
修饰的内容会具有动态性,比如调用方法会走runtime那一套流程
class Dog: NSObject {
@objc dynamic func test1() {}
func test2() {}
}
var d = Dog()
d.test1()
d.test2()
KVC/KVO
- Swift支持KVC\KVO的条件
- 属性所在的类、监听器最终继承自
NSObject
- 用
@objc dynamic
修饰对应的属性
- 属性所在的类、监听器最终继承自
class Observer: NSObject (
override func observeValue(forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey : Any]?,
context: UnsafeMutableRawPointer?){
print ("observeValue", change?[.newKey] as Any)
}
}
class Person: NSObject {
@objc dynamic var age: Int =
var observer: Observer = Observer()
override init() {
super. init
self.addObserver(observer, forKeyPath: "aqe", options: .new, context: nil)
}
deinit {
self. removeObserver(observer, forKeyPath: "age")
}
}
var p = Person()
// observeValue Optional(20)
p.age = 20
// observeValue Optional(25)
p.setValue(25, forKey: "age")
- block方式的KVO
class Person: NSObject {
@objc dynamic var age: Int = 0
var observation: NSKeyValueObservation?
override init() {
super.init()
observation = observe(\Person.age, options: .new) {
(person, change) in
print (change.newValue as Any)
}
}
}
var p = Person()
// Optional(20)
p.age = 20
// Optional(25)
p.setValue(25, forKey: "age")
关联属性
- 在Swift中,
class
依然可以使用关联对象- 默认情况,
extension
不可以增加存储属性 - 借助关联对象,可以实现类似
extension
为class
增加存储属性的效果
- 默认情况,
class Person {}
extension Person {
private static var AGE KEY: Void?
var age: Int {
get {
(objc_getAssociatedObject(self, &Self.AGE KEY) as? Int) ?? 0
}
set {
objc_setAssociatedObject(self, &Self.AGE_KEY, newValue, .OBJC_ASSOCIATION_ASSIGN)
}
}
}
var p = Person()
print(p.age) // 0
p.age = 10
print(p.age) // 10
资源名管理
let img = UIImage(named: "logo")
let btn = UIButton(type: .custom)
btn.setTitle("添加", for: .normal)
performSegue(withIdentifier: "login_main", sender: self)
let img = VIImage(R.image.logo)
let btn = UIButton(type: .custom)
btn.setTitle(R.string.add, for: .normal)
performSegue(withIdentifier: R.segue.login_main, sender: self)
enum R {
enum string: String {
case add = "添加"
}
enum image: String {
case logo
}
enum segue: String {
case login_main
}
}
- 参考Android的资源名管理方式
extension UIImage {
convenience init?(_ name: R.image) {
self.init(named: name.rawValue)
}
}
extension UIViewController {
func performSegue(withIdentifier identifier: R.segue, sender: Any?)
performSeque(withIdentifier: identifier.rawValue, sender: sender)
}
}
extension Button {
func setTitle(_ title: R.string, for state: UIControl.State) {
setTitle(title.rawvalue, for: state)
}
}
- 其他思路
let img = UIImage(named: "logo")
let font = UIFont(name: "Arial", size: 14)
let img = R.image.logo
let font = R.font.arial(14)
enum R {
enum image {
static var logo = UIImage(named: "logo")
}
enum font {
static func arial(_ size: CGFloat) -> UIFont? {
UIFont (name: "Arial", size: size)
}
}
}
多线程
public typealias Task = () -> Void
public static func async(_ task: @escaping Task) (
_async(task)
}
public static func async(_ task: @escaping Task, mainTask: @escaping Task) (
_async(task, mainTask)
}
private static func _async(_ task: @escaping Task, mainTask: Task? = nil) (
let item = DispatchWorkIten(block: task)
DispatchQueue.global().async(execute: item)
if let main = mainTask {
item.notify(queue: DispatchQueue.main, execute: main)
}
}
- 延迟
@discardableResult
public static func delay(_ seconds: Double, block: @escaping Task) -> DispatchworkItem {
let item = DispatchWorkItem(block: block)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + seconds, execute: item)
return item
}
- 异步延迟
@discardableResult
public static func asyncDelay(_ seconds: Double, _ task: @escaping Task) -> DispatchworkItem {
return _asyncDelay(seconds, task)
}
@discardableResult
public static func asyncDelay(_ seconds: Double, _ task: @escaping Task, _ mainTask: @escaping Task) -> DispatchworkItem {
return _asyncDelay(seconds; task, mainTask)
}
private static func _asyncDelay(_ seconds: Double, _ task: @escaping Task, _ mainTask: Task? = nil) -> DispatchworkItem {
let item = DispatchworkItem(block: task)
DispatchQueue.global().asyncAfter(deadline: DispatchTime.now() + seconds,
execute: item)
if let main = mainTask {
item.notify(queue: DispatchQueue.main, execute: main)
}
return item
}
- once
dispatchonce
在Swift中已被废弃,取而代之- 可以用类型属性或者全局变量\常量
- 默认白带
lazy + dispatch_once
效果
let age1: Int = {
print (666)
return 10
}()
class ViewController: UViewController
static let age: Int = {
print (888)
return 20
}()
override func viewDidLoad(){
super. viewDidLoadO
print (age1)
print (age1)
// 666 10 10
print(ViewController.age2)
print(ViewController.age2)
// 888 20 20
}
}
- 加锁
public struct Cache {
private static var data = [String: Any](https://luowei.github.io/list/)
private static var lock = DispatchSemaphore(value: 1) //信号量加锁
private static var lock = NSLock() //NSLock加锁
private static var lock = NSRecursiveLock() //递归锁,可递归调用
public static func get(_ key: String) -> Any? {
data[key]
}
public static func set(_ key: String, _ value: Any) {
//lock.wait()
//defer { lock.signal() )
lock.lock()
defer { lock.unlock() }
data[key] = value
}
}