Swift笔记 - 15.选择器、String、桥接、可选协议、KVC、KVO、关联属性、资源管理

Swift笔记 - 15.选择器、String、桥接、可选协议、KVC、KVO、关联属性、资源管理

选择器

@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

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)
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)
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)

Swift、OC桥接转换表

只能被class继承的协议

protocol Runnablel: AnyObject {}
protocol Runnable2: class {}
@obic protocol Runnable3 {}

可选协议

@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

class Dog: NSObject {
    @objc dynamic func test1() {}
    func test2() {}
}
var d = Dog()
d.test1()
d.test2()

KVC/KVO

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")
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")

关联属性

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
    }
}
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
}
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
    }
}

版权所有,转载请注明出处 luowei.github.io.