Swift4.0开发笔记

目录
1、ATS配置
2、状态栏全局变亮白
3、懒加载
4、内存泄漏
5、常用的第三方库
6、反射机制
7、运行时
8、MD5加密
9、聊天界面
10、多线程GCD
11、 启动图尺寸大小
12 、权限

1、ATS配置

App 网络http请求已被禁止,需要在Info.plist文件配置。

   NSAppTransportSecurity

    NSAllowsArbitraryLoads
    

2、状态栏全局变亮白

 UIApplication.shared.statusBarStyle = .lightContent

还需要在Info.plist文件配置:

UIViewControllerBasedStatusBarAppearance
    

3、懒加载

lazy var mainScrollView:UIScrollView = {()-> UIScrollView in
        let scrollView = UIScrollView()
        return scrollView
    }()

4、内存泄漏

解决闭包循环引用[weak self]

//ESPullToRefresh上拉加载
 var footer: ESRefreshProtocol & ESRefreshAnimatorProtocol
 footer = ESRefreshFooterAnimator.init(frame: CGRect.zero) 
 homeTableView.es.addInfiniteScrolling(animator: footer) { [weak self] in
         self?.pageArray[tag]+=1
         self?.initData(tag:tag+1,page:(self?.pageArray[tag]) ?? 1)
     }

Timer释放内存

var timer:Timer?
 override func viewDidLoad() {
        super.viewDidLoad()
        if #available(iOS 10.0, *) {
            timer  = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { (timer)  in
                 print("定时器执行")
            })
        } else {
            timer=Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(write), userInfo: nil, repeats: true)
        }
         timer?.fire() //启动定时器
        //timer?.fireDate=Date.distantFuture //暂停定时器
}
@objc func write(){
       print("定时器执行")
 }
    
deinit{
      timer?.invalidate()
      timer=nil
      print("销毁定时器")
   }

CADisplayLink释放内存

let displayLink = CADisplayLink.init(target: self, selector: #selector(write))
displayLink?.frameInterval = 1
displayLink?.add(to: .current, forMode: .commonModes)
//displayLink?.isPaused=false//暂停或开始定时器

//销毁定时器必须先执行(deinit在这之后执行)
displayLink?.invalidate()
//然后再执行
displayLink=nil

WKWebView释放内存

//遵守WKScriptMessageHandler协议
 webView = WKWebView.init(frame: self.view.bounds)
 let request=URLRequest.init(url: URL.init(string: "http://www.jianshu.com/u/665ff1bc9038")!)
 webView?.load(request)
 webView?.configuration.userContentController.add(self, name: "Delete")
 self.view.addSubview(webView!)

//实现代理方法
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        if "Delete" == message.name {
        }
    }

//销毁WKWebView对象必须先执行(deinit在这之后执行)
webView?.configuration.userContentController.removeScriptMessageHandler(forName: "Delete")
//然后再执行
webView=nil

NotificationCenter通知

//发送通知
let center = NotificationCenter.default
center.post(name: NSNotification.Name(rawValue: "Notification"), object: "传单个值")
center.post(name: NSNotification.Name(rawValue: "Notification_More"), object: nil, userInfo: ["name":"星星编程","experience":"3年"])

//接收通知
    var  center = NotificationCenter.default
    var observer:NSObjectProtocol?
    
    override func viewDidLoad() {
        super.viewDidLoad()
 
        center.addObserver(self, selector: #selector(receive), name: NSNotification.Name(rawValue: "Notification"), object: nil)
        
      observer =  center.addObserver(forName: NSNotification.Name(rawValue: "Notification_More"), object: nil, queue: OperationQueue.main) { (notification) in
            print(notification.userInfo ?? "")
        }
  
    }
 
    @objc func receive(notification:Notification){
        print("接收到消息:" + "\(notification.object ?? "")")
    }
  
    deinit {
        //center.removeObserver(self)//销毁所以通知中心的监听,不能销毁NSObjectProtocol的监听
        center.removeObserver(self, name: NSNotification.Name(rawValue: "Notification"), object: nil)
       // center.removeObserver(observer ?? self)//销毁NSObjectProtocol的监听
        center.removeObserver(observer ?? self, name: NSNotification.Name(rawValue: "Notification_More"), object: nil)
        
        print("移除通知监听")
    }

5、常用的第三方库

网络请求和生成Model的框架:AlamofireObjectMapper
首页图片轮播框架:GLLoopView
图片加载框架:Kingfisher
上拉刷新下拉加载框架:ESPullToRefresh

6、反射机制

Mirror

class Book : NSObject {
    var name:String?   //书名
    var author:String? //作者
    var pages:Int?     //页数
}

        let book = Book()
        book.name = ""
        book.author = "星星编程"
        book.pages = 100
       
        //是否是Book类的一个实例或实例的任何类继承自Book类
        if book.isKind(of: Book.classForCoder()){
            print("book是Book的一个实例")
        }
        
       //是否是Book类的一个实例
        if book.isMember(of: Book.classForCoder()) {
            print("book是Book的一个实例")
        }

      //判断self是否实现了aa方法
        if self.responds(to: #selector(aa)){
            print("aa")
        }

      //发送一个消息到指定消息的接收器,并返回结果
       self.perform(#selector(aa))
        
        //将对象进行反射
        let mirror = Mirror(reflecting: book)
        print("对象类型:\(mirror.subjectType)")
        print("对象子元素个数:\(mirror.children.count)")
        
        print("--- 对象子元素的属性名和属性值分别如下 ---")
        for case let (key?, value) in mirror.children {
            print("属性:\(key)     值:\(value)")
        }

NSClassFromString

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
 
        window = UIWindow()
        window?.backgroundColor = UIColor.white

        //设置跟控制器要添加命名空间(默认是项目名称,最好不要有特殊符号)
        let clsName = "StarsSwift.ViewController"
        let cls = NSClassFromString(clsName) as? UIViewController.Type
        //使用类来创建视图控制器
        let vc = cls?.init()

        window?.rootViewController = vc
        window?.makeKeyAndVisible()
        return true
    }

7、运行时

//通过KVC给对象赋值
 let book = Book(dict: ["name" : "" , "author" : "星星编程" ,"introduction" : "假如编程欺骗了你,你依旧义无反顾的热爱编程,这才叫真爱。" ])
     
      print("书名:\(book.name ?? "") 作者:\(book.name ?? "") 简介:\(book.introduction ?? "")")

       //打印通过运行时获取类的属性
        print(Book.propertyList())

//书类
class Book : NSObject{
    @objc var name:String?   //书名
    @objc var author:String? //作者
    @objc var introduction:String?  //简介
    
    init(dict:[String:Any]) {
        super.init()
        self.setValuesForKeys(dict)
    }
    
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        
    }
    
    class func propertyList()->[String]{
        
        var count:UInt32=0
        //获取类的属性列表,返回属性列表数组
        let list=class_copyPropertyList(self, &count)
        var propertyList=[String]()
        for i in 0..

8、MD5加密

//
//  String+MD5.swift
//  StarsSwift
//
//  Created by 李永飞 on 2017/10/26.
//  Copyright © 2017年 李永飞. All rights reserved.
//

import Foundation


extension String  {
    var md5: String {
        if let data = self.data(using: .utf8, allowLossyConversion: true) {
            
            let message = data.withUnsafeBytes { bytes -> [UInt8] in
                return Array(UnsafeBufferPointer(start: bytes, count: data.count))
            }
            
            let MD5Calculator = MD5(message)
            let MD5Data = MD5Calculator.calculate()
            
            var MD5String = String()
            for c in MD5Data {
                MD5String += String(format: "%02x", c)
            }
            return MD5String
            
        } else {
            return self
        }
    }
}

9、聊天界面

Swift4.0开发笔记_第1张图片
消息列表.png

Swift4.0开发笔记_第2张图片
好友列表.png

Swift4.0开发笔记_第3张图片
聊天界面.png

10、多线程GCD

加载网络数据及时更新UI

 DispatchQueue.global().async {
            //加载网络数据
            DispatchQueue.main.async(execute: {
                //更新UI
            })
        }

延迟加载

 DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
             //更新UI
        })

DispatchGroup

 let group = DispatchGroup()
 let queueTask1 = DispatchQueue(label: "book")
 queueTask1.async(group: group) {
       print("任务1" )
  }
 let queueTask2 = DispatchQueue(label: "video")
 queueTask2.async(group: group) {
      print("任务2" )
 }
 group.notify(queue: DispatchQueue.main) {
      print("任务完成" )
 }

DispatchWorkItem

let queueTask = DispatchQueue(label: "queueTask", attributes: .concurrent)
let workItem1 = DispatchWorkItem {
       print("WorkItem1")
 }
let workItem2 = DispatchWorkItem {
       print("WorkItem2")
 }
queueTask.async(execute: workItem1)
queueTask.async(execute: workItem2)

DispatchGroup和DispatchWorkItem一起使用

 let group = DispatchGroup()
 let queueTask1 = DispatchQueue(label: "book")
 queueTask1.async(group: group) {
       print("任务1" )
  }
 let queueTask2 = DispatchQueue(label: "video")
 queueTask2.async(group: group) {
      print("任务2" )
 }
let queueTask = DispatchQueue(label: "queueTask", attributes: .concurrent)
let workItem1 = DispatchWorkItem {
       print("WorkItem1")
 }
let workItem2 = DispatchWorkItem {
       print("WorkItem2")
 }
 queueTask.async(group: group, execute: workItem1)
 queueTask.async(group: group, execute: workItem2)
 group.notify(queue: DispatchQueue.main) {
      print("任务完成" )
 }

11、 启动图尺寸大小

iPhone Portrait iOS 11+ iPhone X (1125×2436) @3x

iPhone Portrait iOS 8,9-Retina HD 5.5 (1242×2208) @3x
iPhone Portrait iOS 8,9-Retina HD 4.7 (750×1334) @2x

iPhone Portrait iOS 7,8,9-2x (640×960) @2x
iPhone Portrait iOS 7,8,9-Retina 4 (640×1136) @2x

iPhone Portrait iOS 5,6-1x (320×480) @1x
iPhone Portrait iOS 5,6-2x (640×960) @2x
iPhone Portrait iOS 5,6-Retina4 (640×1136) @2x

12、 权限

通讯录 NSContactsUsageDescription
麦克风 NSMicrophoneUsageDescription
相册 NSPhotoLibraryUsageDescription
相机 NSCameraUsageDescription
添加图片到相册 NSPhotoLibraryAddUsageDescription
持续获取地理位置 NSLocationAlwaysUsageDescription
使用时获取地理位置 NSLocationWhenInUseUsageDescription
蓝牙 NSBluetoothPeripheralUsageDescription
语音转文字 NSSpeechRecognitionUsageDescription
日历 NSCalendarsUsageDescription

你可能感兴趣的:(Swift4.0开发笔记)