Repository navigation
Expand file tree
/
Copy pathdb.json
More file actions
1 lines (1 loc) · 471 KB
/
Copy pathdb.json
File metadata and controls
1 lines (1 loc) · 471 KB
1
{"meta":{"version":1,"warehouse":"2.2.0"},"models":{"Asset":[{"_id":"source/CNAME","path":"CNAME","modified":0,"renderable":0},{"_id":"themes/jacman/source/css/style.styl","path":"css/style.styl","modified":0,"renderable":1},{"_id":"themes/jacman/source/fancybox/blank.gif","path":"fancybox/blank.gif","modified":0,"renderable":1},{"_id":"themes/jacman/source/fancybox/fancybox_loading@2x.gif","path":"fancybox/fancybox_loading@2x.gif","modified":0,"renderable":1},{"_id":"themes/jacman/source/fancybox/fancybox_loading.gif","path":"fancybox/fancybox_loading.gif","modified":0,"renderable":1},{"_id":"themes/jacman/source/fancybox/fancybox_overlay.png","path":"fancybox/fancybox_overlay.png","modified":0,"renderable":1},{"_id":"themes/jacman/source/fancybox/fancybox_sprite.png","path":"fancybox/fancybox_sprite.png","modified":0,"renderable":1},{"_id":"themes/jacman/source/fancybox/fancybox_sprite@2x.png","path":"fancybox/fancybox_sprite@2x.png","modified":0,"renderable":1},{"_id":"themes/jacman/source/fancybox/jquery.fancybox.css","path":"fancybox/jquery.fancybox.css","modified":0,"renderable":1},{"_id":"themes/jacman/source/fancybox/jquery.fancybox.js","path":"fancybox/jquery.fancybox.js","modified":0,"renderable":1},{"_id":"themes/jacman/source/fancybox/jquery.fancybox.pack.js","path":"fancybox/jquery.fancybox.pack.js","modified":0,"renderable":1},{"_id":"themes/jacman/source/font/FontAwesome.otf","path":"font/FontAwesome.otf","modified":0,"renderable":1},{"_id":"themes/jacman/source/font/coveredbyyourgrace-webfont.eot","path":"font/coveredbyyourgrace-webfont.eot","modified":0,"renderable":1},{"_id":"themes/jacman/source/font/coveredbyyourgrace-webfont.ttf","path":"font/coveredbyyourgrace-webfont.ttf","modified":0,"renderable":1},{"_id":"themes/jacman/source/font/coveredbyyourgrace-webfont.woff","path":"font/coveredbyyourgrace-webfont.woff","modified":0,"renderable":1},{"_id":"themes/jacman/source/font/fontawesome-webfont.eot","path":"font/fontawesome-webfont.eot","modified":0,"renderable":1},{"_id":"themes/jacman/source/font/fontawesome-webfont.woff","path":"font/fontawesome-webfont.woff","modified":0,"renderable":1},{"_id":"themes/jacman/source/font/fontdiao.eot","path":"font/fontdiao.eot","modified":0,"renderable":1},{"_id":"themes/jacman/source/font/fontdiao.ttf","path":"font/fontdiao.ttf","modified":0,"renderable":1},{"_id":"themes/jacman/source/font/fontdiao.woff","path":"font/fontdiao.woff","modified":0,"renderable":1},{"_id":"themes/jacman/source/img/author.jpg","path":"img/author.jpg","modified":0,"renderable":1},{"_id":"themes/jacman/source/img/author111.jpg","path":"img/author111.jpg","modified":0,"renderable":1},{"_id":"themes/jacman/source/img/cc-by-nc-nd.svg","path":"img/cc-by-nc-nd.svg","modified":0,"renderable":1},{"_id":"themes/jacman/source/img/cc-by-nc-sa.svg","path":"img/cc-by-nc-sa.svg","modified":0,"renderable":1},{"_id":"themes/jacman/source/img/cc-by-nc.svg","path":"img/cc-by-nc.svg","modified":0,"renderable":1},{"_id":"themes/jacman/source/img/cc-by-nd.svg","path":"img/cc-by-nd.svg","modified":0,"renderable":1},{"_id":"themes/jacman/source/img/cc-by-sa.svg","path":"img/cc-by-sa.svg","modified":0,"renderable":1},{"_id":"themes/jacman/source/img/cc-by.svg","path":"img/cc-by.svg","modified":0,"renderable":1},{"_id":"themes/jacman/source/img/cc-zero.svg","path":"img/cc-zero.svg","modified":0,"renderable":1},{"_id":"themes/jacman/source/img/favicon.ico","path":"img/favicon.ico","modified":0,"renderable":1},{"_id":"themes/jacman/source/img/jacman.jpg","path":"img/jacman.jpg","modified":0,"renderable":1},{"_id":"themes/jacman/source/img/logo.svg","path":"img/logo.svg","modified":0,"renderable":1},{"_id":"themes/jacman/source/img/scrollup.png","path":"img/scrollup.png","modified":0,"renderable":1},{"_id":"themes/jacman/source/js/gallery.js","path":"js/gallery.js","modified":0,"renderable":1},{"_id":"themes/jacman/source/js/jquery.imagesloaded.min.js","path":"js/jquery.imagesloaded.min.js","modified":0,"renderable":1},{"_id":"themes/jacman/source/js/jquery.qrcode-0.12.0.min.js","path":"js/jquery.qrcode-0.12.0.min.js","modified":0,"renderable":1},{"_id":"themes/jacman/source/js/totop.js","path":"js/totop.js","modified":0,"renderable":1},{"_id":"themes/jacman/source/font/coveredbyyourgrace-webfont.svg","path":"font/coveredbyyourgrace-webfont.svg","modified":0,"renderable":1},{"_id":"themes/jacman/source/font/fontawesome-webfont.ttf","path":"font/fontawesome-webfont.ttf","modified":0,"renderable":1},{"_id":"themes/jacman/source/font/fontdiao.svg","path":"font/fontdiao.svg","modified":0,"renderable":1},{"_id":"themes/jacman/source/img/logo.png","path":"img/logo.png","modified":0,"renderable":1},{"_id":"themes/jacman/source/js/jquery-2.0.3.min.js","path":"js/jquery-2.0.3.min.js","modified":0,"renderable":1},{"_id":"themes/jacman/source/fancybox/helpers/fancybox_buttons.png","path":"fancybox/helpers/fancybox_buttons.png","modified":0,"renderable":1},{"_id":"themes/jacman/source/fancybox/helpers/jquery.fancybox-buttons.js","path":"fancybox/helpers/jquery.fancybox-buttons.js","modified":0,"renderable":1},{"_id":"themes/jacman/source/fancybox/helpers/jquery.fancybox-thumbs.css","path":"fancybox/helpers/jquery.fancybox-thumbs.css","modified":0,"renderable":1},{"_id":"themes/jacman/source/fancybox/helpers/jquery.fancybox-buttons.css","path":"fancybox/helpers/jquery.fancybox-buttons.css","modified":0,"renderable":1},{"_id":"themes/jacman/source/fancybox/helpers/jquery.fancybox-media.js","path":"fancybox/helpers/jquery.fancybox-media.js","modified":0,"renderable":1},{"_id":"themes/jacman/source/fancybox/helpers/jquery.fancybox-thumbs.js","path":"fancybox/helpers/jquery.fancybox-thumbs.js","modified":0,"renderable":1},{"_id":"themes/jacman/source/font/fontawesome-webfont.svg","path":"font/fontawesome-webfont.svg","modified":0,"renderable":1},{"_id":"themes/jacman/source/img/banner.jpg","path":"img/banner.jpg","modified":0,"renderable":1}],"Cache":[{"_id":"source/.DS_Store","hash":"879ec735973c9feeea5a51eef298804a9e23d74c","modified":1490192230000},{"_id":"source/CNAME","hash":"60c3545ec32560291686752e361422d9ee28e88c","modified":1488294753000},{"_id":"source/baidu_verify_8XV1gIYn4a.html","hash":"2e0d65c77f7187f62c129bfb56dc3e4c4f746240","modified":1488332963000},{"_id":"themes/jacman/LICENSE","hash":"931516aa36c53eb7843c83d82662eb50cc3c4367","modified":1488245347000},{"_id":"themes/jacman/.DS_Store","hash":"725462407654e4f5a04c5d95fff4e371ff2c48b3","modified":1488256916000},{"_id":"themes/jacman/README.md","hash":"75a5c9fbd7c9cec4d2f277042d2fee550e4936be","modified":1488245347000},{"_id":"themes/jacman/README_zh.md","hash":"d6014b16eaccc97dc54a7779c9e36003752410e1","modified":1488245347000},{"_id":"themes/jacman/_config.yml","hash":"194bf6e6b9c20b44716797ff8f702a40ccc05cf0","modified":1488687055000},{"_id":"source/_posts/2015-06-20-Carthage.md","hash":"7117feb2a0d91dc55872c67177a1b333346d558b","modified":1488687277000},{"_id":"source/_posts/.DS_Store","hash":"df2fbeb1400acda0909a32c1cf6bf492f1121e07","modified":1488254487000},{"_id":"source/_posts/2015-06-20-UIColor进制转换.md","hash":"26aaa644d3178f380ed4bfbfc66a0e75403ed84b","modified":1488687321000},{"_id":"source/_posts/2015-08-03-weakSelf与strongSelf.md","hash":"86308440e89d793c991ecaffd24dfb9160cc6b7a","modified":1488687470000},{"_id":"source/_posts/2015-06-20-Cell拖动.md","hash":"04f259f1a88820fce162ee78c487cbc38807f8f5","modified":1488687481000},{"_id":"source/_posts/2015-08-03-成员变量与属性.md","hash":"0a27eb64a904a328f7f62118ba829b34b7ac5dd5","modified":1488687458000},{"_id":"source/_posts/2015-08-05-快把你的bash换掉吧.md","hash":"939e5a809bc0d73e146144f3053a959ce3478ab4","modified":1488687443000},{"_id":"source/_posts/2015-08-12-使用SKPSMTPMessage发送邮件.md","hash":"86d4438f592c8b2a38ffc32c62f482fb0d63b456","modified":1488687421000},{"_id":"source/_posts/2015-08-26-UITableView的分割线.md","hash":"93053fc7c7fb50060151c953ad3241d68e584225","modified":1488687404000},{"_id":"source/_posts/2017-01-23-快速了解JavaScript中的函数.md","hash":"bd929fa4be66cbc7577c49a81f6225c26a8e3305","modified":1488687370000},{"_id":"source/_posts/2017-02-28-iOS中英文混合排序.md","hash":"c039d8600f6a6e4b1562f6a3e742b2501729a2b0","modified":1488687351000},{"_id":"source/_posts/2017-03-04-iOS开发神器Reveal使用指南.md","hash":"1fcb40cd580e8d3ec648e3d426adb7ede602f9a0","modified":1490191874000},{"_id":"source/_posts/2017-01-22-Effective Objective-C 2.0:编写高质量iOS与OS X代码的52个有效方法-.md","hash":"07eaacbb5972009cfcc363b08aeb965a66ef0205","modified":1488687386000},{"_id":"themes/jacman/languages/default.yml","hash":"eea72d6138497287c0b3f4bd93e4f6f62b7aff37","modified":1488245347000},{"_id":"themes/jacman/languages/zh-CN.yml","hash":"1f3b9d00dd4322352b0c9c82a76dc9865a616d41","modified":1488245347000},{"_id":"themes/jacman/languages/zh-TW.yml","hash":"61a02ba818d641579a86fcd7f5926ab1e6ab5f70","modified":1488245347000},{"_id":"themes/jacman/layout/archive.ejs","hash":"a18842e3d719fe3ca9b977a6995f8facc75c8673","modified":1488245347000},{"_id":"themes/jacman/layout/category.ejs","hash":"9b740fc33f6f028df60f0bc4312bf3ebd03aa8ea","modified":1488245347000},{"_id":"themes/jacman/layout/index.ejs","hash":"75cef2172c286994af412e11ab7f4f5a0daaf1f5","modified":1488245347000},{"_id":"themes/jacman/layout/layout.ejs","hash":"5b4289a4526899809b9c2facea535367ff51ba2b","modified":1488245347000},{"_id":"themes/jacman/layout/page.ejs","hash":"bd6bbf2ea8e183bd835867ff617dc6366b56748c","modified":1488245347000},{"_id":"themes/jacman/scripts/fancybox.js","hash":"aa411cd072399df1ddc8e2181a3204678a5177d9","modified":1488245347000},{"_id":"themes/jacman/layout/post.ejs","hash":"3114134775bdde5a83cf14feb019606fa2b2b2be","modified":1488245347000},{"_id":"themes/jacman/layout/tag.ejs","hash":"45150a2365768b6b67880193c9264ad2bb4814db","modified":1488245347000},{"_id":"themes/jacman/source/.DS_Store","hash":"8e2df1a9a9f49abd2ba6bcfd38f350355d184b4a","modified":1488247113000},{"_id":"themes/jacman/layout/_partial/after_footer.ejs","hash":"c703b0c25139b8a5f8f9d24a334a07905e2b7987","modified":1488245347000},{"_id":"themes/jacman/layout/_partial/analytics.ejs","hash":"697601996220fe0a0f9cd628be67dec3c86ae2aa","modified":1488245347000},{"_id":"themes/jacman/layout/_partial/archive.ejs","hash":"2c7395e7563fe016521712a645c28a13f952d52a","modified":1488245347000},{"_id":"themes/jacman/layout/_partial/article.ejs","hash":"261ecacb8456f4cb972632b6a9103860fa63b9a3","modified":1488245347000},{"_id":"themes/jacman/layout/_partial/article_row.ejs","hash":"4cb855d91ece7f67b2ca0992fffa55472d0b9c93","modified":1488245347000},{"_id":"themes/jacman/layout/_partial/categories.ejs","hash":"8a52d0344d5bce1925cf586ed73c11192925209b","modified":1488245347000},{"_id":"themes/jacman/layout/_partial/footer.ejs","hash":"5f80bf6c6ddcf8c28c4599cd1540b14b25d54f18","modified":1488245347000},{"_id":"themes/jacman/layout/_partial/mathjax.ejs","hash":"d42994ac696f52ba99c1cbac382cd76d5b04a3e8","modified":1488245347000},{"_id":"themes/jacman/layout/_partial/pagination.ejs","hash":"6146ac37dfb4f8613090bc52b3fc8cfa911a186a","modified":1488245347000},{"_id":"themes/jacman/layout/_partial/head.ejs","hash":"761941be4922cd3c177c8130296b909bf7db5c09","modified":1488245347000},{"_id":"themes/jacman/layout/_partial/header.ejs","hash":"18515612344ff048b9372b91b7eef6f3b143801f","modified":1488245347000},{"_id":"themes/jacman/layout/_partial/search.ejs","hash":"1083824a6c6c3df02767f2f3b727aee78ebb76ec","modified":1488245347000},{"_id":"themes/jacman/layout/_partial/sidebar.ejs","hash":"c4f527fff0070fbe65919053a16224412317f40d","modified":1488245347000},{"_id":"themes/jacman/layout/_partial/tags.ejs","hash":"b33b2b5d08f1d53a8de25a95f660f7f1cea7b3cb","modified":1488245347000},{"_id":"themes/jacman/layout/_partial/tinysou_search.ejs","hash":"06ecddc8a9d40b480fe2e958af1dab857a9d5441","modified":1488245347000},{"_id":"themes/jacman/layout/_partial/totop.ejs","hash":"bea5bb7cb9350b8af7d97a8d223af63a5b30ab78","modified":1488245347000},{"_id":"themes/jacman/layout/_widget/archive.ejs","hash":"39ea6b7888406fbd1b4cf236ebd718e881493374","modified":1488245347000},{"_id":"themes/jacman/layout/_widget/douban.ejs","hash":"e3820c36169e88663e6c9177666b2904c1ce47e6","modified":1488245347000},{"_id":"themes/jacman/layout/_widget/github-card.ejs","hash":"5c759b6ea214bac56a393247de27e67ce73fb33f","modified":1488245347000},{"_id":"themes/jacman/layout/_widget/links.ejs","hash":"e49868063439c2092cdf9a8ec82cc295b0e42f66","modified":1488245347000},{"_id":"themes/jacman/layout/_widget/category.ejs","hash":"c1fae96b5053da021bcc04ab2ce5c2c8d30de8a2","modified":1488245347000},{"_id":"themes/jacman/layout/_widget/rss.ejs","hash":"0a4b5f2a2e36a1d504fe2e7c6c8372cbb4628aab","modified":1488245347000},{"_id":"themes/jacman/layout/_widget/tagcloud.ejs","hash":"10a1001189d5c28ce6d42494563b9637c302b454","modified":1488245347000},{"_id":"themes/jacman/layout/_widget/weibo.ejs","hash":"a31c2b223d0feb2a227e203cac9e5d13b7d328a8","modified":1488245347000},{"_id":"themes/jacman/layout/_widget/tag.ejs","hash":"7e82ad9c916b9ce871b2f65ce8f283c5ba47947b","modified":1488245347000},{"_id":"themes/jacman/source/css/style.styl","hash":"a0a45af186a72ae68979bf26f2a5d0d2303189ca","modified":1488245347000},{"_id":"themes/jacman/source/fancybox/blank.gif","hash":"2daeaa8b5f19f0bc209d976c02bd6acb51b00b0a","modified":1488245347000},{"_id":"themes/jacman/source/fancybox/fancybox_loading@2x.gif","hash":"273b123496a42ba45c3416adb027cd99745058b0","modified":1488245347000},{"_id":"themes/jacman/source/fancybox/fancybox_loading.gif","hash":"1a755fb2599f3a313cc6cfdb14df043f8c14a99c","modified":1488245347000},{"_id":"themes/jacman/source/fancybox/fancybox_overlay.png","hash":"b3a4ee645ba494f52840ef8412015ba0f465dbe0","modified":1488245347000},{"_id":"themes/jacman/source/fancybox/fancybox_sprite.png","hash":"17df19f97628e77be09c352bf27425faea248251","modified":1488245347000},{"_id":"themes/jacman/source/fancybox/fancybox_sprite@2x.png","hash":"30c58913f327e28f466a00f4c1ac8001b560aed8","modified":1488245347000},{"_id":"themes/jacman/source/fancybox/jquery.fancybox.css","hash":"aaa582fb9eb4b7092dc69fcb2d5b1c20cca58ab6","modified":1488245347000},{"_id":"themes/jacman/source/fancybox/jquery.fancybox.js","hash":"d08b03a42d5c4ba456ef8ba33116fdbb7a9cabed","modified":1488245347000},{"_id":"themes/jacman/source/fancybox/jquery.fancybox.pack.js","hash":"9e0d51ca1dbe66f6c0c7aefd552dc8122e694a6e","modified":1488245347000},{"_id":"themes/jacman/source/font/FontAwesome.otf","hash":"b5b4f9be85f91f10799e87a083da1d050f842734","modified":1488245347000},{"_id":"themes/jacman/source/font/coveredbyyourgrace-webfont.eot","hash":"a17d0f10534303e40f210c506ebb8703fa23b7de","modified":1488245347000},{"_id":"themes/jacman/source/font/coveredbyyourgrace-webfont.ttf","hash":"194ccb4acf77a03dc25bcc174edb266143704fec","modified":1488245347000},{"_id":"themes/jacman/source/font/coveredbyyourgrace-webfont.woff","hash":"c6f8dc1a2f6ce914f120e80a876b8fd77b98888e","modified":1488245347000},{"_id":"themes/jacman/source/font/fontawesome-webfont.eot","hash":"7619748fe34c64fb157a57f6d4ef3678f63a8f5e","modified":1488245347000},{"_id":"themes/jacman/source/font/fontawesome-webfont.woff","hash":"04c3bf56d87a0828935bd6b4aee859995f321693","modified":1488245347000},{"_id":"themes/jacman/source/font/fontdiao.eot","hash":"9544a0d7ba208989302bc4da5a184faeb0e883c9","modified":1488245347000},{"_id":"themes/jacman/source/font/fontdiao.ttf","hash":"ee9fd7be2493c9bf6d2841044e69a0830d9d3fab","modified":1488245347000},{"_id":"themes/jacman/source/font/fontdiao.woff","hash":"71f54eb6e98aa28cafeb04aab71c0e5b349ea89f","modified":1488245347000},{"_id":"themes/jacman/source/img/author.jpg","hash":"8799b599c0ae954785566996338509e9b3da50b1","modified":1485067032000},{"_id":"themes/jacman/source/img/author111.jpg","hash":"2a292e681b4c6c975eec9c8c356d99647a465542","modified":1488245347000},{"_id":"themes/jacman/source/img/cc-by-nc-nd.svg","hash":"c6524ece3f8039a5f612feaf865d21ec8a794564","modified":1488245347000},{"_id":"themes/jacman/source/img/cc-by-nc-sa.svg","hash":"3031be41e8753c70508aa88e84ed8f4f653f157e","modified":1488245347000},{"_id":"themes/jacman/source/img/cc-by-nc.svg","hash":"8d39b39d88f8501c0d27f8df9aae47136ebc59b7","modified":1488245347000},{"_id":"themes/jacman/source/img/cc-by-nd.svg","hash":"c563508ce9ced1e66948024ba1153400ac0e0621","modified":1488245347000},{"_id":"themes/jacman/source/img/cc-by-sa.svg","hash":"aa4742d733c8af8d38d4c183b8adbdcab045872e","modified":1488245347000},{"_id":"themes/jacman/source/img/cc-by.svg","hash":"28a0a4fe355a974a5e42f68031652b76798d4f7e","modified":1488245347000},{"_id":"themes/jacman/source/img/cc-zero.svg","hash":"87669bf8ac268a91d027a0a4802c92a1473e9030","modified":1488245347000},{"_id":"themes/jacman/source/img/favicon.ico","hash":"2d22a3e0c7905a894e832c831dd91c29c209c7a5","modified":1488245347000},{"_id":"themes/jacman/source/img/jacman.jpg","hash":"0ba14a4a5e3be012826fc713c33479912126d34e","modified":1488245347000},{"_id":"themes/jacman/source/img/logo.svg","hash":"9ae38f7225c38624faeb7b74996efa9de7bf065b","modified":1488245347000},{"_id":"themes/jacman/source/img/scrollup.png","hash":"2137d4f1739aa8aa3fcb0348c3ddf1e41d62f2e3","modified":1488245347000},{"_id":"themes/jacman/source/js/gallery.js","hash":"f8a4ba7fb8349cca374a3c69fff9b2bf21f742ed","modified":1488245347000},{"_id":"themes/jacman/source/js/jquery.imagesloaded.min.js","hash":"4109837b1f6477bacc6b095a863b1b95b1b3693f","modified":1488245347000},{"_id":"themes/jacman/source/js/jquery.qrcode-0.12.0.min.js","hash":"57c3987166a26415a71292162690e82c21e315ad","modified":1488245347000},{"_id":"themes/jacman/source/js/totop.js","hash":"cad23c5ea7163d1e5c05a0fd3ef9233469da10cb","modified":1488245347000},{"_id":"themes/jacman/source/font/coveredbyyourgrace-webfont.svg","hash":"eabdb262d8e246865dfb56031f01ff6e8d2f9d53","modified":1488245347000},{"_id":"themes/jacman/source/font/fontawesome-webfont.ttf","hash":"7f09c97f333917034ad08fa7295e916c9f72fd3f","modified":1488245347000},{"_id":"themes/jacman/source/font/fontdiao.svg","hash":"334a94e6a66a8b089be7315d876bec93efe38d2b","modified":1488245347000},{"_id":"themes/jacman/source/img/logo.png","hash":"fd08d12d1fa147cf894e8f8327e38f1758de32ed","modified":1488245347000},{"_id":"themes/jacman/source/js/jquery-2.0.3.min.js","hash":"a0ae3697b0ab8c0e8bd3186c80db42abd6d97a8d","modified":1488245347000},{"_id":"themes/jacman/layout/_partial/post/catetags.ejs","hash":"0e37bababc8f4659f5b59a552a946b46d89e4158","modified":1488245347000},{"_id":"themes/jacman/layout/_partial/post/article.ejs","hash":"b09e3acea7076e1f01dfe0c2295e19951ea09437","modified":1488245347000},{"_id":"themes/jacman/layout/_partial/post/comment.ejs","hash":"c88bc8f5805173920a5fdd7e9234a850e3d8e151","modified":1488245347000},{"_id":"themes/jacman/layout/_partial/post/footer.ejs","hash":"b12ec08a5845a3d8c01257614f1dfead879c87d2","modified":1488245347000},{"_id":"themes/jacman/layout/_partial/post/gallery.ejs","hash":"fafc2501d7e65983b0f5c2b58151ca12e57c0574","modified":1488245347000},{"_id":"themes/jacman/layout/_partial/post/header.ejs","hash":"36a705942b691abe0d643ea8afa339981b32f6f2","modified":1488245347000},{"_id":"themes/jacman/layout/_partial/post/jiathis.ejs","hash":"d7f5960039ac74924559ab6ba03c64457b8f0966","modified":1488245347000},{"_id":"themes/jacman/layout/_partial/post/pagination.ejs","hash":"7de9c07a4c968429a8088c31a28b7f3a993ded1b","modified":1488245347000},{"_id":"themes/jacman/source/css/_base/font.styl","hash":"c8a0faf43b08e37ad07a5669db76d595da966159","modified":1488245347000},{"_id":"themes/jacman/source/css/_base/public.styl","hash":"f016180726019927b9a835ed01e04d153f27a149","modified":1488245347000},{"_id":"themes/jacman/source/css/_base/variable.styl","hash":"cb652eb83c28a208743fabab92de896f8b7cbf7b","modified":1488245347000},{"_id":"themes/jacman/source/css/_partial/article.styl","hash":"c69641b4a34a8c62986b335414413dbde26de25e","modified":1488245347000},{"_id":"themes/jacman/source/css/_partial/aside.styl","hash":"506fde1d67ce750452cbe84bee01a19c7d027c5e","modified":1488245347000},{"_id":"themes/jacman/source/css/_partial/duoshuo.styl","hash":"e85f1192283f043115c272a9deb3cb6ced793990","modified":1488245347000},{"_id":"themes/jacman/source/css/_partial/footer.styl","hash":"1911613a19b605a58f801c21b03b5d4c83b90f9c","modified":1488245347000},{"_id":"themes/jacman/source/css/_partial/gallery.styl","hash":"7246809f4ce3166ec1b259bf475cae1a48e29aad","modified":1488245347000},{"_id":"themes/jacman/source/css/_partial/header.styl","hash":"5121ceb712be3f2dde98b8b6e589b546e19eab8f","modified":1488245347000},{"_id":"themes/jacman/source/css/_partial/helper.styl","hash":"1136600932b97534b88465bf05ef313630b2de3d","modified":1488245347000},{"_id":"themes/jacman/source/css/_partial/totop.styl","hash":"96363d7c5aaed5f649667fc0752a62620a67e872","modified":1488245347000},{"_id":"themes/jacman/source/css/_partial/index.styl","hash":"a72ff14effd276015264f870f47ed8f8413bf5d3","modified":1488245347000},{"_id":"themes/jacman/source/fancybox/helpers/fancybox_buttons.png","hash":"e385b139516c6813dcd64b8fc431c364ceafe5f3","modified":1488245347000},{"_id":"themes/jacman/source/fancybox/helpers/jquery.fancybox-buttons.js","hash":"dc3645529a4bf72983a39fa34c1eb9146e082019","modified":1488245347000},{"_id":"themes/jacman/source/fancybox/helpers/jquery.fancybox-thumbs.css","hash":"4ac329c16a5277592fc12a37cca3d72ca4ec292f","modified":1488245347000},{"_id":"themes/jacman/source/fancybox/helpers/jquery.fancybox-buttons.css","hash":"1a9d8e5c22b371fcc69d4dbbb823d9c39f04c0c8","modified":1488245347000},{"_id":"themes/jacman/source/fancybox/helpers/jquery.fancybox-media.js","hash":"294420f9ff20f4e3584d212b0c262a00a96ecdb3","modified":1488245347000},{"_id":"themes/jacman/source/fancybox/helpers/jquery.fancybox-thumbs.js","hash":"47da1ae5401c24b5c17cc18e2730780f5c1a7a0c","modified":1488245347000},{"_id":"themes/jacman/source/font/fontawesome-webfont.svg","hash":"46fcc0194d75a0ddac0a038aee41b23456784814","modified":1488245347000},{"_id":"themes/jacman/source/img/banner.jpg","hash":"5104860c4f8b2e84ef734ba6c37fe7a288bf0d74","modified":1488245347000},{"_id":"themes/jacman/source/css/_base/highlight/highlight.styl","hash":"91b62bfc58390b0d5db782a75be6965ee3665eb3","modified":1488245347000},{"_id":"themes/jacman/source/css/_base/highlight/theme.styl","hash":"e3a59bd427ba37a54ead9eeba9a5356b3f720a48","modified":1488245347000},{"_id":"public/baidu_verify_8XV1gIYn4a.html","hash":"1987a28e6cf613c0a35f1750d9d364d87cfeb157","modified":1490191920311},{"_id":"public/archives/index.html","hash":"ae259818dfb642e0d89dce5ea7eef115bc7516d8","modified":1490196852530},{"_id":"public/archives/page/2/index.html","hash":"f51a5b7dca7c069d906a26e83dbde0bc4e05125a","modified":1490196852562},{"_id":"public/archives/2015/index.html","hash":"44dd1fe854c4e09f780d046886c5963e588eab6b","modified":1490196852563},{"_id":"public/archives/2015/06/index.html","hash":"ba9cd4b610c7692b310530b3f41874e284854f1e","modified":1490196852563},{"_id":"public/archives/2015/08/index.html","hash":"71e0d079db9aa470ac5716844adbd22bc37bcae2","modified":1490196852563},{"_id":"public/archives/2017/index.html","hash":"4dea0262098d46ece84c938d1416fbc3eeb2ec9b","modified":1490196852563},{"_id":"public/archives/2017/01/index.html","hash":"99b8957f04e81fe196c04ab3ea21e304dd13e37f","modified":1490196852565},{"_id":"public/archives/2017/02/index.html","hash":"733d87740523cf6d9090a73857017bc433fee572","modified":1490196852565},{"_id":"public/archives/2017/03/index.html","hash":"cbb222ba709718abbee3c611f0204238624676b4","modified":1490196852565},{"_id":"public/categories/iOS/index.html","hash":"e824002b58bbd32c7e7d01ccf3bdb42124b1539b","modified":1490196852565},{"_id":"public/categories/Mac工具/index.html","hash":"827a70fcca06ccdba879c5634768aa202e46a969","modified":1490196852565},{"_id":"public/categories/JavaScript/index.html","hash":"040a8424a080378c5e6fb32e274bf7a3ed5e3715","modified":1490196852565},{"_id":"public/page/2/index.html","hash":"e943ff4ea1087194714de70f5a77a4cf2dcca856","modified":1490196852565},{"_id":"public/tags/iOS工具/index.html","hash":"0980de6b56f403451eac8394b676cc543fd300dc","modified":1490196852565},{"_id":"public/tags/iOS/index.html","hash":"063ea4208cbf0c57ee12ef9ae688e30acc4685c6","modified":1490196852565},{"_id":"public/tags/Mac工具/index.html","hash":"fc0d1a4eed5470d30861f71912c7ac774d6489f5","modified":1490196852566},{"_id":"public/tags/随笔/index.html","hash":"d8a75092470eeef117079112f382558a60f43972","modified":1490196852567},{"_id":"public/tags/读书笔记/index.html","hash":"f7f164bac612acad399f11dfe4c6d1b03ab9a570","modified":1490196852567},{"_id":"public/2017/03/04/2017-03-04-iOS开发神器Reveal使用指南/index.html","hash":"7825cdaefb81896712bc322145036a24496764eb","modified":1490196852567},{"_id":"public/2017/02/28/2017-02-28-iOS中英文混合排序/index.html","hash":"58c464c252ceb3e061ba4087204d563233d9a2e6","modified":1490196852567},{"_id":"public/2017/01/23/2017-01-23-快速了解JavaScript中的函数/index.html","hash":"87d4d1c533c723330ba24153bf293597672ba10b","modified":1490196852567},{"_id":"public/2017/01/22/2017-01-22-Effective Objective-C 2.0:编写高质量iOS与OS X代码的52个有效方法-/index.html","hash":"3cfd6a95058a57e7e095278054268cf1a724b53e","modified":1490196852567},{"_id":"public/2015/08/26/2015-08-26-UITableView的分割线/index.html","hash":"be40f762b3862b78e07ce6d4716e1489f9cb4a48","modified":1490196852567},{"_id":"public/2015/08/12/2015-08-12-使用SKPSMTPMessage发送邮件/index.html","hash":"c363e0ca07e31fb60cacf8d6cfbf306a1e41639a","modified":1490196852570},{"_id":"public/2015/08/05/2015-08-05-快把你的bash换掉吧/index.html","hash":"548fc0847e4c9701ae52c594d92b8d8fd208550e","modified":1490196852570},{"_id":"public/2015/08/03/2015-08-03-weakSelf与strongSelf/index.html","hash":"05aa56c30653cec80b0bba9753310e7cb3c63478","modified":1490196852571},{"_id":"public/2015/08/03/2015-08-03-成员变量与属性/index.html","hash":"2958afa961eba185527da32d064e391a97118f70","modified":1490196852572},{"_id":"public/2015/06/20/2015-06-20-Cell拖动/index.html","hash":"04879c44836301317d96e26a5f96d60c2cb13e06","modified":1490196852572},{"_id":"public/2015/06/20/2015-06-20-UIColor进制转换/index.html","hash":"ebbc02bf13c22445db6081ebf56eea748aa481fb","modified":1490196852572},{"_id":"public/2015/06/19/2015-06-20-Carthage/index.html","hash":"625ee575900f3e06f5056ab6cb3278b63a49e6c6","modified":1490196852572},{"_id":"public/index.html","hash":"4389f53fa78702cc24734d04ec3a3af1e695dde1","modified":1490196852572},{"_id":"source/_posts/2017-03-22-Python爬虫实践.md","hash":"cf67418f9b22dbd1b14e2dcc30ed6de33a7f0ee3","modified":1490196720000},{"_id":"public/categories/Python/index.html","hash":"38bd1dd9e4baae8b38523f40a90dba3bb37c2c55","modified":1490196852576},{"_id":"public/tags/Python/index.html","hash":"b73bf1a24377b9a1710e879c80001ede40a7f5f1","modified":1490196852577},{"_id":"public/2017/03/22/2017-03-22-Python爬虫实践/index.html","hash":"09c2cb2c28be3a9ffbb5769a2e62924624431802","modified":1490196852577}],"Category":[{"name":"iOS","_id":"cj0l1pta800030er904gg70hz"},{"name":"Mac工具","_id":"cj0l1ptaz000l0er9tysqqva3"},{"name":"JavaScript","_id":"cj0l1ptb6000u0er92o8x0h45"},{"name":"Python","_id":"cj0l4nlzc000172r99wvlz96d"}],"Data":[],"Page":[{"_content":"8XV1gIYn4a","source":"baidu_verify_8XV1gIYn4a.html","raw":"8XV1gIYn4a","date":"2017-03-01T01:49:30.000Z","updated":"2017-03-01T01:49:23.000Z","path":"baidu_verify_8XV1gIYn4a.html","title":"","comments":1,"layout":"page","_id":"cj0l1pt9800000er9xms1kigb","content":"8XV1gIYn4a","excerpt":"","more":"8XV1gIYn4a"}],"Post":[{"layout":"post","title":"Cocoa新的依赖工具:Carthage","date":"2015-06-18T16:00:00.000Z","comments":1,"keywords":"Carthage","publish":true,"description":"Cocoa新的依赖工具:Carthage","_content":"谈到iOS的管理第三方类库的依赖工具,大家可能会先想到[CocoaPods](https://github.com/cocoapods/cocoapods),`CocoaPods`支持丰富的第三方库,文档等,是iOS开发者有力的开发工具,但是其优缺点非常的明显。\n<!-- more -->\n## 前言\n优点:\n\n* 支持丰富的第三方类库,文档\n* 有一大批开发者维护,稳定性较好\n\n缺点:\n\n* 改变项目文件结构,对项目具有较强侵入性\n* 依赖于Xcode workspace文件\n\n那么就来说说我们今天的主角[Carthage](https://github.com/Carthage/Carthage),它也是一款iOS第三方类库的依赖工具,它的原理是使用`Xcodebuild`编译框架的二进制文件,最终生成`.framework`静态库。\n\n优点:\n\n* 使用灵活,对项目无侵入性\n* 直接导入生成的`.framework`文件,简单方便\n\n缺点:\n\n* 维护的开发者较少,目前还不太稳定\n* 支持的类库也没有`CocoaPods`那么多\n* `Carthage` 是由 `Swift` 语言写的,只支持动态框架,只支持 iOS8+\n\n其实个人还是比较喜欢`Carthage`,因为它很灵活,对项目的侵入性不大,相信`Carthage`以后会更加的稳定、全面,那么替代`CocoaPods`也将是指日可待。\n\n## 安装\n\n推荐使用`Homebrew`进行安装,简单方便,易于维护:\n\n安装前最好先 update 一下:\n\t\n\tbrew update\n\t\n然后再安装:\n\n\tbrew install carthage\n\t\n当然,你也可以从`Github`的最新release中找到,按照引导一步步安装即可。\n## 简介\nCarthage 的大致工作流程如下:\n\n* 创建一个`Cartfile`文件,写好你要哪些依赖库\n* 执行 `carthage update` 命令下载源代码并自动编译为 `.framework`\n* 把编译后的`.framework`直接拖到项目中即可,或者是在`Linked FrameWorks and Libraries`中添加\n\n执行`carthage update`命令后,项目目录大致如下:\n\n\tCartfile\n\tCartfile.resolved\n\tCarthage\n \t\t- Build\n \t\t- iOS\n \t\t\t- xxxx.framework\n \t- Mac\n \t- xxxx.framework\n \t- Checkouts\n \t- xxxx\n \t- ...\n\txxx.xcodeproj\n\t...\n\n* `Cartfile`文件用来标注你需要哪些依赖库,对应版本或者`Git`分支 (需要提交到`Git`)\n* `Cartfile.resolved`文件用来跟踪项目当前所用的依赖版本号,为了保持多端开发一致 (需要提交到`Git`)\n* `Carthage`文件夹用来存放依赖库的源文件和编译后的文件 (不需要提交到`Git`)\n\n## 使用\n在项目的根目录创建`Cartfile`文件,类似于`CocoaPods`的`Podfile`文件:\n\n\ttouch Cartfile\n编辑`Carthage`文件,添加所需依赖库:\n\t\n\tvi Cartfile\n例如我要添加`SwiftyJSON`,只需在`Carthage`文件中加入\n\t\n\tgithub \"SwiftyJSON/SwiftyJSON\" \n\n然后保存,执行`update`即可导入最新版本的`SwiftyJSON`\n\t\n\tcarthage update\n当然,如果你需要导入指定版本,可以参照[官方说明](https://github.com/Carthage/Carthage/blob/master/Documentation/Artifacts.md#cartfile),对`Carthage`文件进行修改。\n\n最后,将`Carthage/Build/iOS/SwiftyJSON.framework`导入项目即可使用。\n\n## 问题\n按照上面的步骤进行`update`,可能不会生成`SwiftyJSON.framework`,这也是我遇到的一个蛋疼的问题,其他的第三方库:比如`Alamofire`,都是没有问题的,我的猜测应该是`SwiftyJSON`的问题,下面是解决方法:进入Carthage/Checkouts/SwiftyJSON目录内,将Example.xcodeproj文件拖入Example文件夹中。其实你只需将`Example.xcodeproj`文件拖入`Carthage/Checkouts/SwiftyJSON`的子目录当中去,随便一个子目录都行,因为`Example`文件夹中放的是`SwiftyJSON`的`demo`,所以还是放入`Example`中比较好。\n\n## 结尾\n\n希望`Carthage`可以走的越来越远,让开发更加的高效,便捷。\n\n","source":"_posts/2015-06-20-Carthage.md","raw":"---\nlayout: post\ntitle: \"Cocoa新的依赖工具:Carthage\"\ndate: 2015-06-19\ncomments: true\ncategories: iOS\ntags: [iOS工具]\nkeywords: Carthage\npublish: true\ndescription: Cocoa新的依赖工具:Carthage\n---\n谈到iOS的管理第三方类库的依赖工具,大家可能会先想到[CocoaPods](https://github.com/cocoapods/cocoapods),`CocoaPods`支持丰富的第三方库,文档等,是iOS开发者有力的开发工具,但是其优缺点非常的明显。\n<!-- more -->\n## 前言\n优点:\n\n* 支持丰富的第三方类库,文档\n* 有一大批开发者维护,稳定性较好\n\n缺点:\n\n* 改变项目文件结构,对项目具有较强侵入性\n* 依赖于Xcode workspace文件\n\n那么就来说说我们今天的主角[Carthage](https://github.com/Carthage/Carthage),它也是一款iOS第三方类库的依赖工具,它的原理是使用`Xcodebuild`编译框架的二进制文件,最终生成`.framework`静态库。\n\n优点:\n\n* 使用灵活,对项目无侵入性\n* 直接导入生成的`.framework`文件,简单方便\n\n缺点:\n\n* 维护的开发者较少,目前还不太稳定\n* 支持的类库也没有`CocoaPods`那么多\n* `Carthage` 是由 `Swift` 语言写的,只支持动态框架,只支持 iOS8+\n\n其实个人还是比较喜欢`Carthage`,因为它很灵活,对项目的侵入性不大,相信`Carthage`以后会更加的稳定、全面,那么替代`CocoaPods`也将是指日可待。\n\n## 安装\n\n推荐使用`Homebrew`进行安装,简单方便,易于维护:\n\n安装前最好先 update 一下:\n\t\n\tbrew update\n\t\n然后再安装:\n\n\tbrew install carthage\n\t\n当然,你也可以从`Github`的最新release中找到,按照引导一步步安装即可。\n## 简介\nCarthage 的大致工作流程如下:\n\n* 创建一个`Cartfile`文件,写好你要哪些依赖库\n* 执行 `carthage update` 命令下载源代码并自动编译为 `.framework`\n* 把编译后的`.framework`直接拖到项目中即可,或者是在`Linked FrameWorks and Libraries`中添加\n\n执行`carthage update`命令后,项目目录大致如下:\n\n\tCartfile\n\tCartfile.resolved\n\tCarthage\n \t\t- Build\n \t\t- iOS\n \t\t\t- xxxx.framework\n \t- Mac\n \t- xxxx.framework\n \t- Checkouts\n \t- xxxx\n \t- ...\n\txxx.xcodeproj\n\t...\n\n* `Cartfile`文件用来标注你需要哪些依赖库,对应版本或者`Git`分支 (需要提交到`Git`)\n* `Cartfile.resolved`文件用来跟踪项目当前所用的依赖版本号,为了保持多端开发一致 (需要提交到`Git`)\n* `Carthage`文件夹用来存放依赖库的源文件和编译后的文件 (不需要提交到`Git`)\n\n## 使用\n在项目的根目录创建`Cartfile`文件,类似于`CocoaPods`的`Podfile`文件:\n\n\ttouch Cartfile\n编辑`Carthage`文件,添加所需依赖库:\n\t\n\tvi Cartfile\n例如我要添加`SwiftyJSON`,只需在`Carthage`文件中加入\n\t\n\tgithub \"SwiftyJSON/SwiftyJSON\" \n\n然后保存,执行`update`即可导入最新版本的`SwiftyJSON`\n\t\n\tcarthage update\n当然,如果你需要导入指定版本,可以参照[官方说明](https://github.com/Carthage/Carthage/blob/master/Documentation/Artifacts.md#cartfile),对`Carthage`文件进行修改。\n\n最后,将`Carthage/Build/iOS/SwiftyJSON.framework`导入项目即可使用。\n\n## 问题\n按照上面的步骤进行`update`,可能不会生成`SwiftyJSON.framework`,这也是我遇到的一个蛋疼的问题,其他的第三方库:比如`Alamofire`,都是没有问题的,我的猜测应该是`SwiftyJSON`的问题,下面是解决方法:进入Carthage/Checkouts/SwiftyJSON目录内,将Example.xcodeproj文件拖入Example文件夹中。其实你只需将`Example.xcodeproj`文件拖入`Carthage/Checkouts/SwiftyJSON`的子目录当中去,随便一个子目录都行,因为`Example`文件夹中放的是`SwiftyJSON`的`demo`,所以还是放入`Example`中比较好。\n\n## 结尾\n\n希望`Carthage`可以走的越来越远,让开发更加的高效,便捷。\n\n","slug":"2015-06-20-Carthage","published":1,"updated":"2017-03-05T04:14:37.000Z","photos":[],"link":"","_id":"cj0l1pt9y00010er95l7simo0","content":"<p>谈到iOS的管理第三方类库的依赖工具,大家可能会先想到<a href=\"https://github.com/cocoapods/cocoapods\" target=\"_blank\" rel=\"external\">CocoaPods</a>,<code>CocoaPods</code>支持丰富的第三方库,文档等,是iOS开发者有力的开发工具,但是其优缺点非常的明显。<br><a id=\"more\"></a></p>\n<h2 id=\"前言\"><a href=\"#前言\" class=\"headerlink\" title=\"前言\"></a>前言</h2><p>优点:</p>\n<ul>\n<li>支持丰富的第三方类库,文档</li>\n<li>有一大批开发者维护,稳定性较好</li>\n</ul>\n<p>缺点:</p>\n<ul>\n<li>改变项目文件结构,对项目具有较强侵入性</li>\n<li>依赖于Xcode workspace文件</li>\n</ul>\n<p>那么就来说说我们今天的主角<a href=\"https://github.com/Carthage/Carthage\" target=\"_blank\" rel=\"external\">Carthage</a>,它也是一款iOS第三方类库的依赖工具,它的原理是使用<code>Xcodebuild</code>编译框架的二进制文件,最终生成<code>.framework</code>静态库。</p>\n<p>优点:</p>\n<ul>\n<li>使用灵活,对项目无侵入性</li>\n<li>直接导入生成的<code>.framework</code>文件,简单方便</li>\n</ul>\n<p>缺点:</p>\n<ul>\n<li>维护的开发者较少,目前还不太稳定</li>\n<li>支持的类库也没有<code>CocoaPods</code>那么多</li>\n<li><code>Carthage</code> 是由 <code>Swift</code> 语言写的,只支持动态框架,只支持 iOS8+</li>\n</ul>\n<p>其实个人还是比较喜欢<code>Carthage</code>,因为它很灵活,对项目的侵入性不大,相信<code>Carthage</code>以后会更加的稳定、全面,那么替代<code>CocoaPods</code>也将是指日可待。</p>\n<h2 id=\"安装\"><a href=\"#安装\" class=\"headerlink\" title=\"安装\"></a>安装</h2><p>推荐使用<code>Homebrew</code>进行安装,简单方便,易于维护:</p>\n<p>安装前最好先 update 一下:</p>\n<pre><code>brew update\n</code></pre><p>然后再安装:</p>\n<pre><code>brew install carthage\n</code></pre><p>当然,你也可以从<code>Github</code>的最新release中找到,按照引导一步步安装即可。</p>\n<h2 id=\"简介\"><a href=\"#简介\" class=\"headerlink\" title=\"简介\"></a>简介</h2><p>Carthage 的大致工作流程如下:</p>\n<ul>\n<li>创建一个<code>Cartfile</code>文件,写好你要哪些依赖库</li>\n<li>执行 <code>carthage update</code> 命令下载源代码并自动编译为 <code>.framework</code></li>\n<li>把编译后的<code>.framework</code>直接拖到项目中即可,或者是在<code>Linked FrameWorks and Libraries</code>中添加</li>\n</ul>\n<p>执行<code>carthage update</code>命令后,项目目录大致如下:</p>\n<pre><code>Cartfile\nCartfile.resolved\nCarthage\n - Build\n - iOS\n - xxxx.framework\n - Mac\n - xxxx.framework\n - Checkouts\n - xxxx\n - ...\nxxx.xcodeproj\n...\n</code></pre><ul>\n<li><code>Cartfile</code>文件用来标注你需要哪些依赖库,对应版本或者<code>Git</code>分支 (需要提交到<code>Git</code>)</li>\n<li><code>Cartfile.resolved</code>文件用来跟踪项目当前所用的依赖版本号,为了保持多端开发一致 (需要提交到<code>Git</code>)</li>\n<li><code>Carthage</code>文件夹用来存放依赖库的源文件和编译后的文件 (不需要提交到<code>Git</code>)</li>\n</ul>\n<h2 id=\"使用\"><a href=\"#使用\" class=\"headerlink\" title=\"使用\"></a>使用</h2><p>在项目的根目录创建<code>Cartfile</code>文件,类似于<code>CocoaPods</code>的<code>Podfile</code>文件:</p>\n<pre><code>touch Cartfile\n</code></pre><p>编辑<code>Carthage</code>文件,添加所需依赖库:</p>\n<pre><code>vi Cartfile\n</code></pre><p>例如我要添加<code>SwiftyJSON</code>,只需在<code>Carthage</code>文件中加入</p>\n<pre><code>github "SwiftyJSON/SwiftyJSON" \n</code></pre><p>然后保存,执行<code>update</code>即可导入最新版本的<code>SwiftyJSON</code></p>\n<pre><code>carthage update\n</code></pre><p>当然,如果你需要导入指定版本,可以参照<a href=\"https://github.com/Carthage/Carthage/blob/master/Documentation/Artifacts.md#cartfile\" target=\"_blank\" rel=\"external\">官方说明</a>,对<code>Carthage</code>文件进行修改。</p>\n<p>最后,将<code>Carthage/Build/iOS/SwiftyJSON.framework</code>导入项目即可使用。</p>\n<h2 id=\"问题\"><a href=\"#问题\" class=\"headerlink\" title=\"问题\"></a>问题</h2><p>按照上面的步骤进行<code>update</code>,可能不会生成<code>SwiftyJSON.framework</code>,这也是我遇到的一个蛋疼的问题,其他的第三方库:比如<code>Alamofire</code>,都是没有问题的,我的猜测应该是<code>SwiftyJSON</code>的问题,下面是解决方法:进入Carthage/Checkouts/SwiftyJSON目录内,将Example.xcodeproj文件拖入Example文件夹中。其实你只需将<code>Example.xcodeproj</code>文件拖入<code>Carthage/Checkouts/SwiftyJSON</code>的子目录当中去,随便一个子目录都行,因为<code>Example</code>文件夹中放的是<code>SwiftyJSON</code>的<code>demo</code>,所以还是放入<code>Example</code>中比较好。</p>\n<h2 id=\"结尾\"><a href=\"#结尾\" class=\"headerlink\" title=\"结尾\"></a>结尾</h2><p>希望<code>Carthage</code>可以走的越来越远,让开发更加的高效,便捷。</p>\n","excerpt":"<p>谈到iOS的管理第三方类库的依赖工具,大家可能会先想到<a href=\"https://github.com/cocoapods/cocoapods\">CocoaPods</a>,<code>CocoaPods</code>支持丰富的第三方库,文档等,是iOS开发者有力的开发工具,但是其优缺点非常的明显。<br>","more":"</p>\n<h2 id=\"前言\"><a href=\"#前言\" class=\"headerlink\" title=\"前言\"></a>前言</h2><p>优点:</p>\n<ul>\n<li>支持丰富的第三方类库,文档</li>\n<li>有一大批开发者维护,稳定性较好</li>\n</ul>\n<p>缺点:</p>\n<ul>\n<li>改变项目文件结构,对项目具有较强侵入性</li>\n<li>依赖于Xcode workspace文件</li>\n</ul>\n<p>那么就来说说我们今天的主角<a href=\"https://github.com/Carthage/Carthage\">Carthage</a>,它也是一款iOS第三方类库的依赖工具,它的原理是使用<code>Xcodebuild</code>编译框架的二进制文件,最终生成<code>.framework</code>静态库。</p>\n<p>优点:</p>\n<ul>\n<li>使用灵活,对项目无侵入性</li>\n<li>直接导入生成的<code>.framework</code>文件,简单方便</li>\n</ul>\n<p>缺点:</p>\n<ul>\n<li>维护的开发者较少,目前还不太稳定</li>\n<li>支持的类库也没有<code>CocoaPods</code>那么多</li>\n<li><code>Carthage</code> 是由 <code>Swift</code> 语言写的,只支持动态框架,只支持 iOS8+</li>\n</ul>\n<p>其实个人还是比较喜欢<code>Carthage</code>,因为它很灵活,对项目的侵入性不大,相信<code>Carthage</code>以后会更加的稳定、全面,那么替代<code>CocoaPods</code>也将是指日可待。</p>\n<h2 id=\"安装\"><a href=\"#安装\" class=\"headerlink\" title=\"安装\"></a>安装</h2><p>推荐使用<code>Homebrew</code>进行安装,简单方便,易于维护:</p>\n<p>安装前最好先 update 一下:</p>\n<pre><code>brew update\n</code></pre><p>然后再安装:</p>\n<pre><code>brew install carthage\n</code></pre><p>当然,你也可以从<code>Github</code>的最新release中找到,按照引导一步步安装即可。</p>\n<h2 id=\"简介\"><a href=\"#简介\" class=\"headerlink\" title=\"简介\"></a>简介</h2><p>Carthage 的大致工作流程如下:</p>\n<ul>\n<li>创建一个<code>Cartfile</code>文件,写好你要哪些依赖库</li>\n<li>执行 <code>carthage update</code> 命令下载源代码并自动编译为 <code>.framework</code></li>\n<li>把编译后的<code>.framework</code>直接拖到项目中即可,或者是在<code>Linked FrameWorks and Libraries</code>中添加</li>\n</ul>\n<p>执行<code>carthage update</code>命令后,项目目录大致如下:</p>\n<pre><code>Cartfile\nCartfile.resolved\nCarthage\n - Build\n - iOS\n - xxxx.framework\n - Mac\n - xxxx.framework\n - Checkouts\n - xxxx\n - ...\nxxx.xcodeproj\n...\n</code></pre><ul>\n<li><code>Cartfile</code>文件用来标注你需要哪些依赖库,对应版本或者<code>Git</code>分支 (需要提交到<code>Git</code>)</li>\n<li><code>Cartfile.resolved</code>文件用来跟踪项目当前所用的依赖版本号,为了保持多端开发一致 (需要提交到<code>Git</code>)</li>\n<li><code>Carthage</code>文件夹用来存放依赖库的源文件和编译后的文件 (不需要提交到<code>Git</code>)</li>\n</ul>\n<h2 id=\"使用\"><a href=\"#使用\" class=\"headerlink\" title=\"使用\"></a>使用</h2><p>在项目的根目录创建<code>Cartfile</code>文件,类似于<code>CocoaPods</code>的<code>Podfile</code>文件:</p>\n<pre><code>touch Cartfile\n</code></pre><p>编辑<code>Carthage</code>文件,添加所需依赖库:</p>\n<pre><code>vi Cartfile\n</code></pre><p>例如我要添加<code>SwiftyJSON</code>,只需在<code>Carthage</code>文件中加入</p>\n<pre><code>github "SwiftyJSON/SwiftyJSON" \n</code></pre><p>然后保存,执行<code>update</code>即可导入最新版本的<code>SwiftyJSON</code></p>\n<pre><code>carthage update\n</code></pre><p>当然,如果你需要导入指定版本,可以参照<a href=\"https://github.com/Carthage/Carthage/blob/master/Documentation/Artifacts.md#cartfile\">官方说明</a>,对<code>Carthage</code>文件进行修改。</p>\n<p>最后,将<code>Carthage/Build/iOS/SwiftyJSON.framework</code>导入项目即可使用。</p>\n<h2 id=\"问题\"><a href=\"#问题\" class=\"headerlink\" title=\"问题\"></a>问题</h2><p>按照上面的步骤进行<code>update</code>,可能不会生成<code>SwiftyJSON.framework</code>,这也是我遇到的一个蛋疼的问题,其他的第三方库:比如<code>Alamofire</code>,都是没有问题的,我的猜测应该是<code>SwiftyJSON</code>的问题,下面是解决方法:进入Carthage/Checkouts/SwiftyJSON目录内,将Example.xcodeproj文件拖入Example文件夹中。其实你只需将<code>Example.xcodeproj</code>文件拖入<code>Carthage/Checkouts/SwiftyJSON</code>的子目录当中去,随便一个子目录都行,因为<code>Example</code>文件夹中放的是<code>SwiftyJSON</code>的<code>demo</code>,所以还是放入<code>Example</code>中比较好。</p>\n<h2 id=\"结尾\"><a href=\"#结尾\" class=\"headerlink\" title=\"结尾\"></a>结尾</h2><p>希望<code>Carthage</code>可以走的越来越远,让开发更加的高效,便捷。</p>"},{"layout":"post","title":"weakSelf与strongSelf","date":"2015-08-02T16:00:00.000Z","comments":1,"keywords":"Carthage","publish":true,"description":"weakSelf与strongSelf","_content":"对于weakSelf与strongSelf的一些理解。\n<!-- more -->\n\n## weakSelf\n\n`weakSelf`的作用是防止`retain`环的出现而导致内存泄露,通过将一方设置为弱引用就可防止`retain`环的出现。比如说像代理,一般都是用的`weak`来进行声明的,这样就是防止循环应用它的写法大致有这几种:\n```\n// 1.AFNetworking的写法\n__weak __typeof(&*self) weakSelf = self;\n// 2.\n__weak __typeof(self) weakSelf = self;\n// 3.\n__weak TTViewController *weakSelf = self;\n// 4.\n__weak id weakSelf = self;\t\n```\n\n上述的四种写法在现有的版本都是正确的,可以随意使用。\n\n## strongSelf\n\n`strongSelf`就是强引用的`self`,使用该关键字声明后可以保证在使用时不会被销毁掉,来看一下下面的代码:\n```\n// 弱引用防止retain环\n__weak __typeof(self)weakSelf = self;\nAFNetworkReachabilityStatusBlock callback = ^(AFNetworkReachabilityStatus status) {\n// 强引用防止使用时被销毁掉\n __strong __typeof(weakSelf)strongSelf = weakSelf;\n strongSelf.networkReachabilityStatus = status;\n if (strongSelf.networkReachabilityStatusBlock) {\n strongSelf.networkReachabilityStatusBlock(status);\n }\n};\n```\n\n上面是开源网络框架`AFNetworking`的一段源代码,在处理网络请求时,因为网络请求的延时性,异步性很可能我们的`self`已经被销毁了,但是我们还需要请求继续执行下去,那么我们就不能让`self`被销毁掉,`strongSelf`正是来解决这一问题的,它保证了`self`不会在`block`执行时被销毁。\n\n`strongSelf`的一般写法:\n```\n__strong __typeof(weakSelf)strongSelf = weakSelf;\n\n```\n\n","source":"_posts/2015-08-03-weakSelf与strongSelf.md","raw":"---\nlayout: post\ntitle: \"weakSelf与strongSelf\"\ndate: 2015-08-03\ncomments: true\ncategories: iOS\ntags: [iOS]\nkeywords: Carthage\npublish: true\ndescription: weakSelf与strongSelf\n---\n对于weakSelf与strongSelf的一些理解。\n<!-- more -->\n\n## weakSelf\n\n`weakSelf`的作用是防止`retain`环的出现而导致内存泄露,通过将一方设置为弱引用就可防止`retain`环的出现。比如说像代理,一般都是用的`weak`来进行声明的,这样就是防止循环应用它的写法大致有这几种:\n```\n// 1.AFNetworking的写法\n__weak __typeof(&*self) weakSelf = self;\n// 2.\n__weak __typeof(self) weakSelf = self;\n// 3.\n__weak TTViewController *weakSelf = self;\n// 4.\n__weak id weakSelf = self;\t\n```\n\n上述的四种写法在现有的版本都是正确的,可以随意使用。\n\n## strongSelf\n\n`strongSelf`就是强引用的`self`,使用该关键字声明后可以保证在使用时不会被销毁掉,来看一下下面的代码:\n```\n// 弱引用防止retain环\n__weak __typeof(self)weakSelf = self;\nAFNetworkReachabilityStatusBlock callback = ^(AFNetworkReachabilityStatus status) {\n// 强引用防止使用时被销毁掉\n __strong __typeof(weakSelf)strongSelf = weakSelf;\n strongSelf.networkReachabilityStatus = status;\n if (strongSelf.networkReachabilityStatusBlock) {\n strongSelf.networkReachabilityStatusBlock(status);\n }\n};\n```\n\n上面是开源网络框架`AFNetworking`的一段源代码,在处理网络请求时,因为网络请求的延时性,异步性很可能我们的`self`已经被销毁了,但是我们还需要请求继续执行下去,那么我们就不能让`self`被销毁掉,`strongSelf`正是来解决这一问题的,它保证了`self`不会在`block`执行时被销毁。\n\n`strongSelf`的一般写法:\n```\n__strong __typeof(weakSelf)strongSelf = weakSelf;\n\n```\n\n","slug":"2015-08-03-weakSelf与strongSelf","published":1,"updated":"2017-03-05T04:17:50.000Z","photos":[],"link":"","_id":"cj0l1pta300020er9d75o18cw","content":"<p>对于weakSelf与strongSelf的一些理解。<br><a id=\"more\"></a></p>\n<h2 id=\"weakSelf\"><a href=\"#weakSelf\" class=\"headerlink\" title=\"weakSelf\"></a>weakSelf</h2><p><code>weakSelf</code>的作用是防止<code>retain</code>环的出现而导致内存泄露,通过将一方设置为弱引用就可防止<code>retain</code>环的出现。比如说像代理,一般都是用的<code>weak</code>来进行声明的,这样就是防止循环应用它的写法大致有这几种:<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div></pre></td><td class=\"code\"><pre><div class=\"line\">// 1.AFNetworking的写法</div><div class=\"line\">__weak __typeof(&*self) weakSelf = self;</div><div class=\"line\">// 2.</div><div class=\"line\">__weak __typeof(self) weakSelf = self;</div><div class=\"line\">// 3.</div><div class=\"line\">__weak TTViewController *weakSelf = self;</div><div class=\"line\">// 4.</div><div class=\"line\">__weak id weakSelf = self;</div></pre></td></tr></table></figure></p>\n<p>上述的四种写法在现有的版本都是正确的,可以随意使用。</p>\n<h2 id=\"strongSelf\"><a href=\"#strongSelf\" class=\"headerlink\" title=\"strongSelf\"></a>strongSelf</h2><p><code>strongSelf</code>就是强引用的<code>self</code>,使用该关键字声明后可以保证在使用时不会被销毁掉,来看一下下面的代码:<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div></pre></td><td class=\"code\"><pre><div class=\"line\">// 弱引用防止retain环</div><div class=\"line\">__weak __typeof(self)weakSelf = self;</div><div class=\"line\">AFNetworkReachabilityStatusBlock callback = ^(AFNetworkReachabilityStatus status) {</div><div class=\"line\">// 强引用防止使用时被销毁掉</div><div class=\"line\"> __strong __typeof(weakSelf)strongSelf = weakSelf;</div><div class=\"line\"> strongSelf.networkReachabilityStatus = status;</div><div class=\"line\"> if (strongSelf.networkReachabilityStatusBlock) {</div><div class=\"line\"> strongSelf.networkReachabilityStatusBlock(status);</div><div class=\"line\"> }</div><div class=\"line\">};</div></pre></td></tr></table></figure></p>\n<p>上面是开源网络框架<code>AFNetworking</code>的一段源代码,在处理网络请求时,因为网络请求的延时性,异步性很可能我们的<code>self</code>已经被销毁了,但是我们还需要请求继续执行下去,那么我们就不能让<code>self</code>被销毁掉,<code>strongSelf</code>正是来解决这一问题的,它保证了<code>self</code>不会在<code>block</code>执行时被销毁。</p>\n<p><code>strongSelf</code>的一般写法:<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div></pre></td><td class=\"code\"><pre><div class=\"line\">__strong __typeof(weakSelf)strongSelf = weakSelf;</div></pre></td></tr></table></figure></p>\n","excerpt":"<p>对于weakSelf与strongSelf的一些理解。<br>","more":"</p>\n<h2 id=\"weakSelf\"><a href=\"#weakSelf\" class=\"headerlink\" title=\"weakSelf\"></a>weakSelf</h2><p><code>weakSelf</code>的作用是防止<code>retain</code>环的出现而导致内存泄露,通过将一方设置为弱引用就可防止<code>retain</code>环的出现。比如说像代理,一般都是用的<code>weak</code>来进行声明的,这样就是防止循环应用它的写法大致有这几种:<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div></pre></td><td class=\"code\"><pre><div class=\"line\">// 1.AFNetworking的写法</div><div class=\"line\">__weak __typeof(&*self) weakSelf = self;</div><div class=\"line\">// 2.</div><div class=\"line\">__weak __typeof(self) weakSelf = self;</div><div class=\"line\">// 3.</div><div class=\"line\">__weak TTViewController *weakSelf = self;</div><div class=\"line\">// 4.</div><div class=\"line\">__weak id weakSelf = self;</div></pre></td></tr></table></figure></p>\n<p>上述的四种写法在现有的版本都是正确的,可以随意使用。</p>\n<h2 id=\"strongSelf\"><a href=\"#strongSelf\" class=\"headerlink\" title=\"strongSelf\"></a>strongSelf</h2><p><code>strongSelf</code>就是强引用的<code>self</code>,使用该关键字声明后可以保证在使用时不会被销毁掉,来看一下下面的代码:<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div></pre></td><td class=\"code\"><pre><div class=\"line\">// 弱引用防止retain环</div><div class=\"line\">__weak __typeof(self)weakSelf = self;</div><div class=\"line\">AFNetworkReachabilityStatusBlock callback = ^(AFNetworkReachabilityStatus status) {</div><div class=\"line\">// 强引用防止使用时被销毁掉</div><div class=\"line\"> __strong __typeof(weakSelf)strongSelf = weakSelf;</div><div class=\"line\"> strongSelf.networkReachabilityStatus = status;</div><div class=\"line\"> if (strongSelf.networkReachabilityStatusBlock) {</div><div class=\"line\"> strongSelf.networkReachabilityStatusBlock(status);</div><div class=\"line\"> }</div><div class=\"line\">};</div></pre></td></tr></table></figure></p>\n<p>上面是开源网络框架<code>AFNetworking</code>的一段源代码,在处理网络请求时,因为网络请求的延时性,异步性很可能我们的<code>self</code>已经被销毁了,但是我们还需要请求继续执行下去,那么我们就不能让<code>self</code>被销毁掉,<code>strongSelf</code>正是来解决这一问题的,它保证了<code>self</code>不会在<code>block</code>执行时被销毁。</p>\n<p><code>strongSelf</code>的一般写法:<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div></pre></td><td class=\"code\"><pre><div class=\"line\">__strong __typeof(weakSelf)strongSelf = weakSelf;</div></pre></td></tr></table></figure></p>"},{"layout":"post","title":" UIColor与十六进制字符串互转(整理)","date":"2015-06-19T16:00:00.000Z","comments":1,"keywords":"Carthage","publish":true,"description":"UIColor与十六进制字符串互转(整理)","_content":"因为项目中用到了UIColor与十六进制字符串互转,于是就整理了一下,以供参阅。\n<!-- more -->\n\n## UIColor转十六进制字符串\n方法一:经过测试发现部分颜色会转化为#fffff(五个f),转化残缺导致最后颜色无法还原,不推荐使用。\n\t\n```\n// UIColor转#ffffff格式的字符串\n+ (NSString *)hexFromUIColor:(UIColor *)color\n{\n if (CGColorGetNumberOfComponents(color.CGColor) < 4) {\n const CGFloat *components = CGColorGetComponents(color.CGColor);\n color = [UIColor colorWithRed:components[0]\n green:components[0]\n blue:components[0]\n alpha:components[1]];\n }\n \nif (CGColorSpaceGetModel(CGColorGetColorSpace(color.CGColor)) != kCGColorSpaceModelRGB) {\n return [NSString stringWithFormat:@\"#FFFFFF\"];\n}\n \nreturn [NSString stringWithFormat:@\"#%x%x%x\", (int)((CGColorGetComponents(color.CGColor))[0]*255.0),\n (int)((CGColorGetComponents(color.CGColor))[1]*255.0),\n (int)((CGColorGetComponents(color.CGColor))[2]*255.0)];\n}\n```\n\n方法二:完美转化为#ffffff格式,暂未发现问题,推荐使用。\n\n```\n// UIColor转#ffffff格式的字符串\n+ (NSString *)hexStringFromColor:(UIColor *)color {\n const CGFloat *components = CGColorGetComponents(color.CGColor);\n \n CGFloat r = components[0];\n CGFloat g = components[1];\n CGFloat b = components[2];\n \n return [NSString stringWithFormat:@\"#%02lX%02lX%02lX\",\n lroundf(r * 255),\n lroundf(g * 255),\n lroundf(b * 255)];\n}\n```\n\n## 十六进制字符串转UIColor\n\n方法一:\n```\n+ (CGFloat) colorComponentFrom: (NSString *) string start: (NSUInteger) start length: (NSUInteger) length {\n NSString *substring = [string substringWithRange: NSMakeRange(start, length)];\n NSString *fullHex = length == 2 ? substring : [NSString stringWithFormat: @\"%@%@\", substring, substring];\n unsigned hexComponent;\n [[NSScanner scannerWithString: fullHex] scanHexInt: &hexComponent];\n return hexComponent / 255.0;\n}\n \n+ (UIColor *) colorWithHexString: (NSString *) hexString {\n NSString *colorString = [[hexString stringByReplacingOccurrencesOfString: @\"#\" withString: @\"\"] uppercaseString];\n CGFloat alpha, red, blue, green;\n switch ([colorString length]) {\n case 3: // #RGB\n alpha = 1.0f;\n red = [self colorComponentFrom: colorString start: 0 length: 1];\n green = [self colorComponentFrom: colorString start: 1 length: 1];\n blue = [self colorComponentFrom: colorString start: 2 length: 1];\n break;\n case 4: // #ARGB\n alpha = [self colorComponentFrom: colorString start: 0 length: 1];\n red = [self colorComponentFrom: colorString start: 1 length: 1];\n green = [self colorComponentFrom: colorString start: 2 length: 1];\n blue = [self colorComponentFrom: colorString start: 3 length: 1];\n break;\n case 6: // #RRGGBB\n alpha = 1.0f;\n red = [self colorComponentFrom: colorString start: 0 length: 2];\n green = [self colorComponentFrom: colorString start: 2 length: 2];\n blue = [self colorComponentFrom: colorString start: 4 length: 2];\n break;\n case 8: // #AARRGGBB\n alpha = [self colorComponentFrom: colorString start: 0 length: 2];\n red = [self colorComponentFrom: colorString start: 2 length: 2];\n green = [self colorComponentFrom: colorString start: 4 length: 2];\n blue = [self colorComponentFrom: colorString start: 6 length: 2];\n break;\n default:\n return nil;\n }\n return [UIColor colorWithRed: red green: green blue: blue alpha: alpha];\n}\n```\n方法二:\n```\n+ (UIColor *)colorWithHexString:(NSString *)hexString alpha:(CGFloat)alphaValue {\n NSString *cString = [[hexString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];\n if (cString.length < 6)\n return [UIColor clearColor];\n if ([cString hasPrefix:@\"0X\"])\n cString = [cString substringFromIndex:2];\n if ([cString hasPrefix:@\"#\"])\n cString = [cString substringFromIndex:1];\n if (cString.length != 6)\n return [UIColor clearColor];\n NSRange range;\n range.location = 0;\n range.length = 2;\n NSString *rString = [cString substringWithRange:range];\n range.location = 2;\n NSString *gString = [cString substringWithRange:range];\n range.location = 4;\n NSString *bString = [cString substringWithRange:range];\n unsigned int r, g, b;\n [[NSScanner scannerWithString:rString] scanHexInt:&r];\n [[NSScanner scannerWithString:gString] scanHexInt:&g];\n [[NSScanner scannerWithString:bString] scanHexInt:&b];\n // 注意:myColor是自定义宏\n //#define myColor(R, G, B, A) [UIColor colorWithRed:R/255.0 green:G/255.0 blue:B/255.0 alpha:A]\n return myColor(r, g, b, alphaValue);\n}\n```\n\n","source":"_posts/2015-06-20-UIColor进制转换.md","raw":"---\nlayout: post\ntitle: \" UIColor与十六进制字符串互转(整理)\"\ndate: 2015-06-20\ncomments: true\ncategories: iOS\ntags: [iOS]\nkeywords: Carthage\npublish: true\ndescription: UIColor与十六进制字符串互转(整理)\n---\n因为项目中用到了UIColor与十六进制字符串互转,于是就整理了一下,以供参阅。\n<!-- more -->\n\n## UIColor转十六进制字符串\n方法一:经过测试发现部分颜色会转化为#fffff(五个f),转化残缺导致最后颜色无法还原,不推荐使用。\n\t\n```\n// UIColor转#ffffff格式的字符串\n+ (NSString *)hexFromUIColor:(UIColor *)color\n{\n if (CGColorGetNumberOfComponents(color.CGColor) < 4) {\n const CGFloat *components = CGColorGetComponents(color.CGColor);\n color = [UIColor colorWithRed:components[0]\n green:components[0]\n blue:components[0]\n alpha:components[1]];\n }\n \nif (CGColorSpaceGetModel(CGColorGetColorSpace(color.CGColor)) != kCGColorSpaceModelRGB) {\n return [NSString stringWithFormat:@\"#FFFFFF\"];\n}\n \nreturn [NSString stringWithFormat:@\"#%x%x%x\", (int)((CGColorGetComponents(color.CGColor))[0]*255.0),\n (int)((CGColorGetComponents(color.CGColor))[1]*255.0),\n (int)((CGColorGetComponents(color.CGColor))[2]*255.0)];\n}\n```\n\n方法二:完美转化为#ffffff格式,暂未发现问题,推荐使用。\n\n```\n// UIColor转#ffffff格式的字符串\n+ (NSString *)hexStringFromColor:(UIColor *)color {\n const CGFloat *components = CGColorGetComponents(color.CGColor);\n \n CGFloat r = components[0];\n CGFloat g = components[1];\n CGFloat b = components[2];\n \n return [NSString stringWithFormat:@\"#%02lX%02lX%02lX\",\n lroundf(r * 255),\n lroundf(g * 255),\n lroundf(b * 255)];\n}\n```\n\n## 十六进制字符串转UIColor\n\n方法一:\n```\n+ (CGFloat) colorComponentFrom: (NSString *) string start: (NSUInteger) start length: (NSUInteger) length {\n NSString *substring = [string substringWithRange: NSMakeRange(start, length)];\n NSString *fullHex = length == 2 ? substring : [NSString stringWithFormat: @\"%@%@\", substring, substring];\n unsigned hexComponent;\n [[NSScanner scannerWithString: fullHex] scanHexInt: &hexComponent];\n return hexComponent / 255.0;\n}\n \n+ (UIColor *) colorWithHexString: (NSString *) hexString {\n NSString *colorString = [[hexString stringByReplacingOccurrencesOfString: @\"#\" withString: @\"\"] uppercaseString];\n CGFloat alpha, red, blue, green;\n switch ([colorString length]) {\n case 3: // #RGB\n alpha = 1.0f;\n red = [self colorComponentFrom: colorString start: 0 length: 1];\n green = [self colorComponentFrom: colorString start: 1 length: 1];\n blue = [self colorComponentFrom: colorString start: 2 length: 1];\n break;\n case 4: // #ARGB\n alpha = [self colorComponentFrom: colorString start: 0 length: 1];\n red = [self colorComponentFrom: colorString start: 1 length: 1];\n green = [self colorComponentFrom: colorString start: 2 length: 1];\n blue = [self colorComponentFrom: colorString start: 3 length: 1];\n break;\n case 6: // #RRGGBB\n alpha = 1.0f;\n red = [self colorComponentFrom: colorString start: 0 length: 2];\n green = [self colorComponentFrom: colorString start: 2 length: 2];\n blue = [self colorComponentFrom: colorString start: 4 length: 2];\n break;\n case 8: // #AARRGGBB\n alpha = [self colorComponentFrom: colorString start: 0 length: 2];\n red = [self colorComponentFrom: colorString start: 2 length: 2];\n green = [self colorComponentFrom: colorString start: 4 length: 2];\n blue = [self colorComponentFrom: colorString start: 6 length: 2];\n break;\n default:\n return nil;\n }\n return [UIColor colorWithRed: red green: green blue: blue alpha: alpha];\n}\n```\n方法二:\n```\n+ (UIColor *)colorWithHexString:(NSString *)hexString alpha:(CGFloat)alphaValue {\n NSString *cString = [[hexString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];\n if (cString.length < 6)\n return [UIColor clearColor];\n if ([cString hasPrefix:@\"0X\"])\n cString = [cString substringFromIndex:2];\n if ([cString hasPrefix:@\"#\"])\n cString = [cString substringFromIndex:1];\n if (cString.length != 6)\n return [UIColor clearColor];\n NSRange range;\n range.location = 0;\n range.length = 2;\n NSString *rString = [cString substringWithRange:range];\n range.location = 2;\n NSString *gString = [cString substringWithRange:range];\n range.location = 4;\n NSString *bString = [cString substringWithRange:range];\n unsigned int r, g, b;\n [[NSScanner scannerWithString:rString] scanHexInt:&r];\n [[NSScanner scannerWithString:gString] scanHexInt:&g];\n [[NSScanner scannerWithString:bString] scanHexInt:&b];\n // 注意:myColor是自定义宏\n //#define myColor(R, G, B, A) [UIColor colorWithRed:R/255.0 green:G/255.0 blue:B/255.0 alpha:A]\n return myColor(r, g, b, alphaValue);\n}\n```\n\n","slug":"2015-06-20-UIColor进制转换","published":1,"updated":"2017-03-05T04:15:21.000Z","photos":[],"link":"","_id":"cj0l1ptac00050er9iih2lbw9","content":"<p>因为项目中用到了UIColor与十六进制字符串互转,于是就整理了一下,以供参阅。<br><a id=\"more\"></a></p>\n<h2 id=\"UIColor转十六进制字符串\"><a href=\"#UIColor转十六进制字符串\" class=\"headerlink\" title=\"UIColor转十六进制字符串\"></a>UIColor转十六进制字符串</h2><p>方法一:经过测试发现部分颜色会转化为#fffff(五个f),转化残缺导致最后颜色无法还原,不推荐使用。</p>\n<figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div><div class=\"line\">13</div><div class=\"line\">14</div><div class=\"line\">15</div><div class=\"line\">16</div><div class=\"line\">17</div><div class=\"line\">18</div><div class=\"line\">19</div></pre></td><td class=\"code\"><pre><div class=\"line\">// UIColor转#ffffff格式的字符串</div><div class=\"line\">+ (NSString *)hexFromUIColor:(UIColor *)color</div><div class=\"line\">{</div><div class=\"line\"> if (CGColorGetNumberOfComponents(color.CGColor) < 4) {</div><div class=\"line\"> const CGFloat *components = CGColorGetComponents(color.CGColor);</div><div class=\"line\"> color = [UIColor colorWithRed:components[0]</div><div class=\"line\"> green:components[0]</div><div class=\"line\"> blue:components[0]</div><div class=\"line\"> alpha:components[1]];</div><div class=\"line\"> }</div><div class=\"line\"> </div><div class=\"line\">if (CGColorSpaceGetModel(CGColorGetColorSpace(color.CGColor)) != kCGColorSpaceModelRGB) {</div><div class=\"line\"> return [NSString stringWithFormat:@"#FFFFFF"];</div><div class=\"line\">}</div><div class=\"line\"> </div><div class=\"line\">return [NSString stringWithFormat:@"#%x%x%x", (int)((CGColorGetComponents(color.CGColor))[0]*255.0),</div><div class=\"line\"> (int)((CGColorGetComponents(color.CGColor))[1]*255.0),</div><div class=\"line\"> (int)((CGColorGetComponents(color.CGColor))[2]*255.0)];</div><div class=\"line\">}</div></pre></td></tr></table></figure>\n<p>方法二:完美转化为#ffffff格式,暂未发现问题,推荐使用。</p>\n<figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div><div class=\"line\">13</div></pre></td><td class=\"code\"><pre><div class=\"line\">// UIColor转#ffffff格式的字符串</div><div class=\"line\">+ (NSString *)hexStringFromColor:(UIColor *)color {</div><div class=\"line\"> const CGFloat *components = CGColorGetComponents(color.CGColor);</div><div class=\"line\"> </div><div class=\"line\"> CGFloat r = components[0];</div><div class=\"line\"> CGFloat g = components[1];</div><div class=\"line\"> CGFloat b = components[2];</div><div class=\"line\"> </div><div class=\"line\"> return [NSString stringWithFormat:@"#%02lX%02lX%02lX",</div><div class=\"line\"> lroundf(r * 255),</div><div class=\"line\"> lroundf(g * 255),</div><div class=\"line\"> lroundf(b * 255)];</div><div class=\"line\">}</div></pre></td></tr></table></figure>\n<h2 id=\"十六进制字符串转UIColor\"><a href=\"#十六进制字符串转UIColor\" class=\"headerlink\" title=\"十六进制字符串转UIColor\"></a>十六进制字符串转UIColor</h2><p>方法一:<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div><div class=\"line\">13</div><div class=\"line\">14</div><div class=\"line\">15</div><div class=\"line\">16</div><div class=\"line\">17</div><div class=\"line\">18</div><div class=\"line\">19</div><div class=\"line\">20</div><div class=\"line\">21</div><div class=\"line\">22</div><div class=\"line\">23</div><div class=\"line\">24</div><div class=\"line\">25</div><div class=\"line\">26</div><div class=\"line\">27</div><div class=\"line\">28</div><div class=\"line\">29</div><div class=\"line\">30</div><div class=\"line\">31</div><div class=\"line\">32</div><div class=\"line\">33</div><div class=\"line\">34</div><div class=\"line\">35</div><div class=\"line\">36</div><div class=\"line\">37</div><div class=\"line\">38</div><div class=\"line\">39</div><div class=\"line\">40</div><div class=\"line\">41</div></pre></td><td class=\"code\"><pre><div class=\"line\">+ (CGFloat) colorComponentFrom: (NSString *) string start: (NSUInteger) start length: (NSUInteger) length {</div><div class=\"line\"> NSString *substring = [string substringWithRange: NSMakeRange(start, length)];</div><div class=\"line\"> NSString *fullHex = length == 2 ? substring : [NSString stringWithFormat: @"%@%@", substring, substring];</div><div class=\"line\"> unsigned hexComponent;</div><div class=\"line\"> [[NSScanner scannerWithString: fullHex] scanHexInt: &hexComponent];</div><div class=\"line\"> return hexComponent / 255.0;</div><div class=\"line\">}</div><div class=\"line\"> </div><div class=\"line\">+ (UIColor *) colorWithHexString: (NSString *) hexString {</div><div class=\"line\"> NSString *colorString = [[hexString stringByReplacingOccurrencesOfString: @"#" withString: @""] uppercaseString];</div><div class=\"line\"> CGFloat alpha, red, blue, green;</div><div class=\"line\"> switch ([colorString length]) {</div><div class=\"line\"> case 3: // #RGB</div><div class=\"line\"> alpha = 1.0f;</div><div class=\"line\"> red = [self colorComponentFrom: colorString start: 0 length: 1];</div><div class=\"line\"> green = [self colorComponentFrom: colorString start: 1 length: 1];</div><div class=\"line\"> blue = [self colorComponentFrom: colorString start: 2 length: 1];</div><div class=\"line\"> break;</div><div class=\"line\"> case 4: // #ARGB</div><div class=\"line\"> alpha = [self colorComponentFrom: colorString start: 0 length: 1];</div><div class=\"line\"> red = [self colorComponentFrom: colorString start: 1 length: 1];</div><div class=\"line\"> green = [self colorComponentFrom: colorString start: 2 length: 1];</div><div class=\"line\"> blue = [self colorComponentFrom: colorString start: 3 length: 1];</div><div class=\"line\"> break;</div><div class=\"line\"> case 6: // #RRGGBB</div><div class=\"line\"> alpha = 1.0f;</div><div class=\"line\"> red = [self colorComponentFrom: colorString start: 0 length: 2];</div><div class=\"line\"> green = [self colorComponentFrom: colorString start: 2 length: 2];</div><div class=\"line\"> blue = [self colorComponentFrom: colorString start: 4 length: 2];</div><div class=\"line\"> break;</div><div class=\"line\"> case 8: // #AARRGGBB</div><div class=\"line\"> alpha = [self colorComponentFrom: colorString start: 0 length: 2];</div><div class=\"line\"> red = [self colorComponentFrom: colorString start: 2 length: 2];</div><div class=\"line\"> green = [self colorComponentFrom: colorString start: 4 length: 2];</div><div class=\"line\"> blue = [self colorComponentFrom: colorString start: 6 length: 2];</div><div class=\"line\"> break;</div><div class=\"line\"> default:</div><div class=\"line\"> return nil;</div><div class=\"line\"> }</div><div class=\"line\"> return [UIColor colorWithRed: red green: green blue: blue alpha: alpha];</div><div class=\"line\">}</div></pre></td></tr></table></figure></p>\n<p>方法二:<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div><div class=\"line\">13</div><div class=\"line\">14</div><div class=\"line\">15</div><div class=\"line\">16</div><div class=\"line\">17</div><div class=\"line\">18</div><div class=\"line\">19</div><div class=\"line\">20</div><div class=\"line\">21</div><div class=\"line\">22</div><div class=\"line\">23</div><div class=\"line\">24</div><div class=\"line\">25</div><div class=\"line\">26</div></pre></td><td class=\"code\"><pre><div class=\"line\">+ (UIColor *)colorWithHexString:(NSString *)hexString alpha:(CGFloat)alphaValue {</div><div class=\"line\"> NSString *cString = [[hexString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];</div><div class=\"line\"> if (cString.length < 6)</div><div class=\"line\"> return [UIColor clearColor];</div><div class=\"line\"> if ([cString hasPrefix:@"0X"])</div><div class=\"line\"> cString = [cString substringFromIndex:2];</div><div class=\"line\"> if ([cString hasPrefix:@"#"])</div><div class=\"line\"> cString = [cString substringFromIndex:1];</div><div class=\"line\"> if (cString.length != 6)</div><div class=\"line\"> return [UIColor clearColor];</div><div class=\"line\"> NSRange range;</div><div class=\"line\"> range.location = 0;</div><div class=\"line\"> range.length = 2;</div><div class=\"line\"> NSString *rString = [cString substringWithRange:range];</div><div class=\"line\"> range.location = 2;</div><div class=\"line\"> NSString *gString = [cString substringWithRange:range];</div><div class=\"line\"> range.location = 4;</div><div class=\"line\"> NSString *bString = [cString substringWithRange:range];</div><div class=\"line\"> unsigned int r, g, b;</div><div class=\"line\"> [[NSScanner scannerWithString:rString] scanHexInt:&r];</div><div class=\"line\"> [[NSScanner scannerWithString:gString] scanHexInt:&g];</div><div class=\"line\"> [[NSScanner scannerWithString:bString] scanHexInt:&b];</div><div class=\"line\"> // 注意:myColor是自定义宏</div><div class=\"line\"> //#define myColor(R, G, B, A) [UIColor colorWithRed:R/255.0 green:G/255.0 blue:B/255.0 alpha:A]</div><div class=\"line\"> return myColor(r, g, b, alphaValue);</div><div class=\"line\">}</div></pre></td></tr></table></figure></p>\n","excerpt":"<p>因为项目中用到了UIColor与十六进制字符串互转,于是就整理了一下,以供参阅。<br>","more":"</p>\n<h2 id=\"UIColor转十六进制字符串\"><a href=\"#UIColor转十六进制字符串\" class=\"headerlink\" title=\"UIColor转十六进制字符串\"></a>UIColor转十六进制字符串</h2><p>方法一:经过测试发现部分颜色会转化为#fffff(五个f),转化残缺导致最后颜色无法还原,不推荐使用。</p>\n<figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div><div class=\"line\">13</div><div class=\"line\">14</div><div class=\"line\">15</div><div class=\"line\">16</div><div class=\"line\">17</div><div class=\"line\">18</div><div class=\"line\">19</div></pre></td><td class=\"code\"><pre><div class=\"line\">// UIColor转#ffffff格式的字符串</div><div class=\"line\">+ (NSString *)hexFromUIColor:(UIColor *)color</div><div class=\"line\">{</div><div class=\"line\"> if (CGColorGetNumberOfComponents(color.CGColor) < 4) {</div><div class=\"line\"> const CGFloat *components = CGColorGetComponents(color.CGColor);</div><div class=\"line\"> color = [UIColor colorWithRed:components[0]</div><div class=\"line\"> green:components[0]</div><div class=\"line\"> blue:components[0]</div><div class=\"line\"> alpha:components[1]];</div><div class=\"line\"> }</div><div class=\"line\"> </div><div class=\"line\">if (CGColorSpaceGetModel(CGColorGetColorSpace(color.CGColor)) != kCGColorSpaceModelRGB) {</div><div class=\"line\"> return [NSString stringWithFormat:@"#FFFFFF"];</div><div class=\"line\">}</div><div class=\"line\"> </div><div class=\"line\">return [NSString stringWithFormat:@"#%x%x%x", (int)((CGColorGetComponents(color.CGColor))[0]*255.0),</div><div class=\"line\"> (int)((CGColorGetComponents(color.CGColor))[1]*255.0),</div><div class=\"line\"> (int)((CGColorGetComponents(color.CGColor))[2]*255.0)];</div><div class=\"line\">}</div></pre></td></tr></table></figure>\n<p>方法二:完美转化为#ffffff格式,暂未发现问题,推荐使用。</p>\n<figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div><div class=\"line\">13</div></pre></td><td class=\"code\"><pre><div class=\"line\">// UIColor转#ffffff格式的字符串</div><div class=\"line\">+ (NSString *)hexStringFromColor:(UIColor *)color {</div><div class=\"line\"> const CGFloat *components = CGColorGetComponents(color.CGColor);</div><div class=\"line\"> </div><div class=\"line\"> CGFloat r = components[0];</div><div class=\"line\"> CGFloat g = components[1];</div><div class=\"line\"> CGFloat b = components[2];</div><div class=\"line\"> </div><div class=\"line\"> return [NSString stringWithFormat:@"#%02lX%02lX%02lX",</div><div class=\"line\"> lroundf(r * 255),</div><div class=\"line\"> lroundf(g * 255),</div><div class=\"line\"> lroundf(b * 255)];</div><div class=\"line\">}</div></pre></td></tr></table></figure>\n<h2 id=\"十六进制字符串转UIColor\"><a href=\"#十六进制字符串转UIColor\" class=\"headerlink\" title=\"十六进制字符串转UIColor\"></a>十六进制字符串转UIColor</h2><p>方法一:<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div><div class=\"line\">13</div><div class=\"line\">14</div><div class=\"line\">15</div><div class=\"line\">16</div><div class=\"line\">17</div><div class=\"line\">18</div><div class=\"line\">19</div><div class=\"line\">20</div><div class=\"line\">21</div><div class=\"line\">22</div><div class=\"line\">23</div><div class=\"line\">24</div><div class=\"line\">25</div><div class=\"line\">26</div><div class=\"line\">27</div><div class=\"line\">28</div><div class=\"line\">29</div><div class=\"line\">30</div><div class=\"line\">31</div><div class=\"line\">32</div><div class=\"line\">33</div><div class=\"line\">34</div><div class=\"line\">35</div><div class=\"line\">36</div><div class=\"line\">37</div><div class=\"line\">38</div><div class=\"line\">39</div><div class=\"line\">40</div><div class=\"line\">41</div></pre></td><td class=\"code\"><pre><div class=\"line\">+ (CGFloat) colorComponentFrom: (NSString *) string start: (NSUInteger) start length: (NSUInteger) length {</div><div class=\"line\"> NSString *substring = [string substringWithRange: NSMakeRange(start, length)];</div><div class=\"line\"> NSString *fullHex = length == 2 ? substring : [NSString stringWithFormat: @"%@%@", substring, substring];</div><div class=\"line\"> unsigned hexComponent;</div><div class=\"line\"> [[NSScanner scannerWithString: fullHex] scanHexInt: &hexComponent];</div><div class=\"line\"> return hexComponent / 255.0;</div><div class=\"line\">}</div><div class=\"line\"> </div><div class=\"line\">+ (UIColor *) colorWithHexString: (NSString *) hexString {</div><div class=\"line\"> NSString *colorString = [[hexString stringByReplacingOccurrencesOfString: @"#" withString: @""] uppercaseString];</div><div class=\"line\"> CGFloat alpha, red, blue, green;</div><div class=\"line\"> switch ([colorString length]) {</div><div class=\"line\"> case 3: // #RGB</div><div class=\"line\"> alpha = 1.0f;</div><div class=\"line\"> red = [self colorComponentFrom: colorString start: 0 length: 1];</div><div class=\"line\"> green = [self colorComponentFrom: colorString start: 1 length: 1];</div><div class=\"line\"> blue = [self colorComponentFrom: colorString start: 2 length: 1];</div><div class=\"line\"> break;</div><div class=\"line\"> case 4: // #ARGB</div><div class=\"line\"> alpha = [self colorComponentFrom: colorString start: 0 length: 1];</div><div class=\"line\"> red = [self colorComponentFrom: colorString start: 1 length: 1];</div><div class=\"line\"> green = [self colorComponentFrom: colorString start: 2 length: 1];</div><div class=\"line\"> blue = [self colorComponentFrom: colorString start: 3 length: 1];</div><div class=\"line\"> break;</div><div class=\"line\"> case 6: // #RRGGBB</div><div class=\"line\"> alpha = 1.0f;</div><div class=\"line\"> red = [self colorComponentFrom: colorString start: 0 length: 2];</div><div class=\"line\"> green = [self colorComponentFrom: colorString start: 2 length: 2];</div><div class=\"line\"> blue = [self colorComponentFrom: colorString start: 4 length: 2];</div><div class=\"line\"> break;</div><div class=\"line\"> case 8: // #AARRGGBB</div><div class=\"line\"> alpha = [self colorComponentFrom: colorString start: 0 length: 2];</div><div class=\"line\"> red = [self colorComponentFrom: colorString start: 2 length: 2];</div><div class=\"line\"> green = [self colorComponentFrom: colorString start: 4 length: 2];</div><div class=\"line\"> blue = [self colorComponentFrom: colorString start: 6 length: 2];</div><div class=\"line\"> break;</div><div class=\"line\"> default:</div><div class=\"line\"> return nil;</div><div class=\"line\"> }</div><div class=\"line\"> return [UIColor colorWithRed: red green: green blue: blue alpha: alpha];</div><div class=\"line\">}</div></pre></td></tr></table></figure></p>\n<p>方法二:<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div><div class=\"line\">13</div><div class=\"line\">14</div><div class=\"line\">15</div><div class=\"line\">16</div><div class=\"line\">17</div><div class=\"line\">18</div><div class=\"line\">19</div><div class=\"line\">20</div><div class=\"line\">21</div><div class=\"line\">22</div><div class=\"line\">23</div><div class=\"line\">24</div><div class=\"line\">25</div><div class=\"line\">26</div></pre></td><td class=\"code\"><pre><div class=\"line\">+ (UIColor *)colorWithHexString:(NSString *)hexString alpha:(CGFloat)alphaValue {</div><div class=\"line\"> NSString *cString = [[hexString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];</div><div class=\"line\"> if (cString.length < 6)</div><div class=\"line\"> return [UIColor clearColor];</div><div class=\"line\"> if ([cString hasPrefix:@"0X"])</div><div class=\"line\"> cString = [cString substringFromIndex:2];</div><div class=\"line\"> if ([cString hasPrefix:@"#"])</div><div class=\"line\"> cString = [cString substringFromIndex:1];</div><div class=\"line\"> if (cString.length != 6)</div><div class=\"line\"> return [UIColor clearColor];</div><div class=\"line\"> NSRange range;</div><div class=\"line\"> range.location = 0;</div><div class=\"line\"> range.length = 2;</div><div class=\"line\"> NSString *rString = [cString substringWithRange:range];</div><div class=\"line\"> range.location = 2;</div><div class=\"line\"> NSString *gString = [cString substringWithRange:range];</div><div class=\"line\"> range.location = 4;</div><div class=\"line\"> NSString *bString = [cString substringWithRange:range];</div><div class=\"line\"> unsigned int r, g, b;</div><div class=\"line\"> [[NSScanner scannerWithString:rString] scanHexInt:&r];</div><div class=\"line\"> [[NSScanner scannerWithString:gString] scanHexInt:&g];</div><div class=\"line\"> [[NSScanner scannerWithString:bString] scanHexInt:&b];</div><div class=\"line\"> // 注意:myColor是自定义宏</div><div class=\"line\"> //#define myColor(R, G, B, A) [UIColor colorWithRed:R/255.0 green:G/255.0 blue:B/255.0 alpha:A]</div><div class=\"line\"> return myColor(r, g, b, alphaValue);</div><div class=\"line\">}</div></pre></td></tr></table></figure></p>"},{"layout":"post","title":"iOS自定义长按手势,随意拖动Cell","date":"2015-06-19T16:00:00.000Z","comments":1,"keywords":"Carthage","publish":true,"description":"iOS自定义长按手势,随意拖动Cell","_content":"\n有时候项目可能会需要对Cell进行拖动,那么具体如何实现,下面我将详细阐述。\n<!-- more -->\n\n## 起因\n\n* 最近在做一个项目,要对UITableViewCell进行拖动蹂躏,具体效果如下:\n\n \n\t\n* 本来打算用UIRespon这几个方法来做,最后发现在UITableViewController中这几个方法不会被响应,具体原因详情见[Stack Overflow](http://stackoverflow.com/questions/8785184/touchesbegan-method-not-called-in-uitableviewcontroller-class-in-iphone),于是就选择了使用长按手势来实现,好吧,废话不多少了,直接上料子。\n\n## 经过\n### 思考\n\n让我们来理清思路,大致分为这几步\n\t\n* 首先创建手势并添加,响应手势定义的方法。\n* 接下根据长按手势的三种状态,分别是起始,改变,结束,在这三种不同状态下我们可以做一些事情。我的思路是在长按手势开始时为cell创建一个快照(可以理解为把cell截成一张图),然后把cell隐藏,之后我们移动的过程中对cell的快照进行操作,等到移动完毕,也就是长按手势结束,显示cell,然后就可以把快照无情的抛弃了。\n* \n### 开动\n\n```\n#pragma mark 设置长按拖动cell\n- (void)setLongPressDrag\n{\n UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressGestureRecognized:)];\n [self.tableView addGestureRecognizer:longPress];\n}\n```\n这个就是创建并添加长按手势,很简单,不再赘述。\n\t\n```\n#pragma mark 创建cell的快照\n- (UIView *)customSnapshoFromView:(UIView *)inputView {\n // 用cell的图层生成UIImage,方便一会显示\n UIGraphicsBeginImageContextWithOptions(inputView.bounds.size, NO, 0);\n [inputView.layer renderInContext:UIGraphicsGetCurrentContext()];\n UIImage *image = UIGraphicsGetImageFromCurrentImageContext();\n UIGraphicsEndImageContext();\n // 自定义这个快照的样子(下面的一些参数可以自己随意设置)\n UIView *snapshot = [[UIImageView alloc] initWithImage:image];\n snapshot.layer.masksToBounds = NO;\n snapshot.layer.cornerRadius = 0.0;\n snapshot.layer.shadowOffset = CGSizeMake(-5.0, 0.0);\n snapshot.layer.shadowRadius = 5.0;\n snapshot.layer.shadowOpacity = 0.4;\n return snapshot;\n}\n\n为cell创建一个快照,等会就可以用上它了。\n\npragma mark 长按手势方法\n- (void)longPressGestureRecognized:(id)sender {\n UILongPressGestureRecognizer *longPress = (UILongPressGestureRecognizer *)sender;\n UIGestureRecognizerState state = longPress.state;\n CGPoint location = [longPress locationInView:self.tableView];\n NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];\n static UIView *snapshot = nil;\n static NSIndexPath *sourceIndexPath = nil;\n\n switch (state) {\n // 已经开始按下\n case UIGestureRecognizerStateBegan: {\n // 判断是不是按在了cell上面\n if (indexPath) {\n sourceIndexPath = indexPath;\n UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];\n // 为拖动的cell添加一个快照\n snapshot = [self customSnapshoFromView:cell];\n // 添加快照至tableView中\n __block CGPoint center = cell.center;\n snapshot.center = center;\n snapshot.alpha = 0.0;\n [self.tableView addSubview:snapshot];\n // 按下的瞬间执行动画\n [UIView animateWithDuration:0.25 animations:^{\n center.y = location.y;\n snapshot.center = center;\n snapshot.transform = CGAffineTransformMakeScale(1.05, 1.05);\n snapshot.alpha = 0.98;\n cell.alpha = 0.0;\n \n } completion:^(BOOL finished) {\n \n cell.hidden = YES;\n \n }];\n }\n break;\n }\n // 移动过程中\n case UIGestureRecognizerStateChanged: {\n // 这里保持数组里面只有最新的两次触摸点的坐标\n [self.touchPoints addObject:[NSValue valueWithCGPoint:location]];\n if (self.touchPoints.count > 2) {\n [self.touchPoints removeObjectAtIndex:0];\n }\n CGPoint center = snapshot.center;\n // 快照随触摸点y值移动(当然也可以根据触摸点的y轴移动量来移动)\n center.y = location.y;\n // 快照随触摸点x值改变量移动\n CGPoint Ppoint = [[self.touchPoints firstObject] CGPointValue];\n CGPoint Npoint = [[self.touchPoints lastObject] CGPointValue];\n CGFloat moveX = Npoint.x - Ppoint.x;\n center.x += moveX;\n snapshot.center = center;\n NSLog(@\"%@---%f----%@\", self.touchPoints, moveX, NSStringFromCGPoint(center));\n NSLog(@\"%@\", NSStringFromCGRect(snapshot.frame));\n // 是否移动了\n if (indexPath && ![indexPath isEqual:sourceIndexPath]) {\n \n // 更新数组中的内容\n\t [self.dataArray exchangeObjectAtIndex:\n\t indexPath.row withObjectAtIndex:sourceIndexPath.row];\n \n // 把cell移动至指定行\n [self.tableView moveRowAtIndexPath:sourceIndexPath toIndexPath:indexPath];\n \n // 存储改变后indexPath的值,以便下次比较\n sourceIndexPath = indexPath;\n }\n break;\n }\n // 长按手势取消状态\n default: {\n // 清除操作\n // 清空数组,非常重要,不然会发生坐标突变!\n [self.touchPoints removeAllObjects];\n UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:sourceIndexPath];\n cell.hidden = NO;\n cell.alpha = 0.0;\n // 将快照恢复到初始状态\n [UIView animateWithDuration:0.25 animations:^{\n snapshot.center = cell.center;\n snapshot.transform = CGAffineTransformIdentity;\n snapshot.alpha = 0.0;\n cell.alpha = 1.0;\n \n } completion:^(BOOL finished) {\n \n sourceIndexPath = nil;\n [snapshot removeFromSuperview];\n snapshot = nil;\n \n }];\n \n break;\n }\n }\n \n}\n\n```\n长按手势的响应方法,这里创建cell快照,并对快照进行坐标的改变。需要注意的是在长按手势结束的时候一定要把存放触摸点坐标的数组清空,不然下次再继续点击的时候,如果点击的位置距离上次较远,cell快照会突然大幅度移动。\n## 结语\n感谢那位外国网友提供的一些思路及技巧,大家如果发现有任何问题,请告知[光之晨曦_](http://weibo.com/p/1005052211006995/home?from=page_100505&mod=TAB#place),互相交流,寻求技术的巅峰。\n\n\n","source":"_posts/2015-06-20-Cell拖动.md","raw":"---\nlayout: post\ntitle: \"iOS自定义长按手势,随意拖动Cell\"\ndate: 2015-06-20\ncomments: true\ncategories: iOS\ntags: [iOS]\nkeywords: Carthage\npublish: true\ndescription: iOS自定义长按手势,随意拖动Cell\n---\n\n有时候项目可能会需要对Cell进行拖动,那么具体如何实现,下面我将详细阐述。\n<!-- more -->\n\n## 起因\n\n* 最近在做一个项目,要对UITableViewCell进行拖动蹂躏,具体效果如下:\n\n \n\t\n* 本来打算用UIRespon这几个方法来做,最后发现在UITableViewController中这几个方法不会被响应,具体原因详情见[Stack Overflow](http://stackoverflow.com/questions/8785184/touchesbegan-method-not-called-in-uitableviewcontroller-class-in-iphone),于是就选择了使用长按手势来实现,好吧,废话不多少了,直接上料子。\n\n## 经过\n### 思考\n\n让我们来理清思路,大致分为这几步\n\t\n* 首先创建手势并添加,响应手势定义的方法。\n* 接下根据长按手势的三种状态,分别是起始,改变,结束,在这三种不同状态下我们可以做一些事情。我的思路是在长按手势开始时为cell创建一个快照(可以理解为把cell截成一张图),然后把cell隐藏,之后我们移动的过程中对cell的快照进行操作,等到移动完毕,也就是长按手势结束,显示cell,然后就可以把快照无情的抛弃了。\n* \n### 开动\n\n```\n#pragma mark 设置长按拖动cell\n- (void)setLongPressDrag\n{\n UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressGestureRecognized:)];\n [self.tableView addGestureRecognizer:longPress];\n}\n```\n这个就是创建并添加长按手势,很简单,不再赘述。\n\t\n```\n#pragma mark 创建cell的快照\n- (UIView *)customSnapshoFromView:(UIView *)inputView {\n // 用cell的图层生成UIImage,方便一会显示\n UIGraphicsBeginImageContextWithOptions(inputView.bounds.size, NO, 0);\n [inputView.layer renderInContext:UIGraphicsGetCurrentContext()];\n UIImage *image = UIGraphicsGetImageFromCurrentImageContext();\n UIGraphicsEndImageContext();\n // 自定义这个快照的样子(下面的一些参数可以自己随意设置)\n UIView *snapshot = [[UIImageView alloc] initWithImage:image];\n snapshot.layer.masksToBounds = NO;\n snapshot.layer.cornerRadius = 0.0;\n snapshot.layer.shadowOffset = CGSizeMake(-5.0, 0.0);\n snapshot.layer.shadowRadius = 5.0;\n snapshot.layer.shadowOpacity = 0.4;\n return snapshot;\n}\n\n为cell创建一个快照,等会就可以用上它了。\n\npragma mark 长按手势方法\n- (void)longPressGestureRecognized:(id)sender {\n UILongPressGestureRecognizer *longPress = (UILongPressGestureRecognizer *)sender;\n UIGestureRecognizerState state = longPress.state;\n CGPoint location = [longPress locationInView:self.tableView];\n NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];\n static UIView *snapshot = nil;\n static NSIndexPath *sourceIndexPath = nil;\n\n switch (state) {\n // 已经开始按下\n case UIGestureRecognizerStateBegan: {\n // 判断是不是按在了cell上面\n if (indexPath) {\n sourceIndexPath = indexPath;\n UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];\n // 为拖动的cell添加一个快照\n snapshot = [self customSnapshoFromView:cell];\n // 添加快照至tableView中\n __block CGPoint center = cell.center;\n snapshot.center = center;\n snapshot.alpha = 0.0;\n [self.tableView addSubview:snapshot];\n // 按下的瞬间执行动画\n [UIView animateWithDuration:0.25 animations:^{\n center.y = location.y;\n snapshot.center = center;\n snapshot.transform = CGAffineTransformMakeScale(1.05, 1.05);\n snapshot.alpha = 0.98;\n cell.alpha = 0.0;\n \n } completion:^(BOOL finished) {\n \n cell.hidden = YES;\n \n }];\n }\n break;\n }\n // 移动过程中\n case UIGestureRecognizerStateChanged: {\n // 这里保持数组里面只有最新的两次触摸点的坐标\n [self.touchPoints addObject:[NSValue valueWithCGPoint:location]];\n if (self.touchPoints.count > 2) {\n [self.touchPoints removeObjectAtIndex:0];\n }\n CGPoint center = snapshot.center;\n // 快照随触摸点y值移动(当然也可以根据触摸点的y轴移动量来移动)\n center.y = location.y;\n // 快照随触摸点x值改变量移动\n CGPoint Ppoint = [[self.touchPoints firstObject] CGPointValue];\n CGPoint Npoint = [[self.touchPoints lastObject] CGPointValue];\n CGFloat moveX = Npoint.x - Ppoint.x;\n center.x += moveX;\n snapshot.center = center;\n NSLog(@\"%@---%f----%@\", self.touchPoints, moveX, NSStringFromCGPoint(center));\n NSLog(@\"%@\", NSStringFromCGRect(snapshot.frame));\n // 是否移动了\n if (indexPath && ![indexPath isEqual:sourceIndexPath]) {\n \n // 更新数组中的内容\n\t [self.dataArray exchangeObjectAtIndex:\n\t indexPath.row withObjectAtIndex:sourceIndexPath.row];\n \n // 把cell移动至指定行\n [self.tableView moveRowAtIndexPath:sourceIndexPath toIndexPath:indexPath];\n \n // 存储改变后indexPath的值,以便下次比较\n sourceIndexPath = indexPath;\n }\n break;\n }\n // 长按手势取消状态\n default: {\n // 清除操作\n // 清空数组,非常重要,不然会发生坐标突变!\n [self.touchPoints removeAllObjects];\n UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:sourceIndexPath];\n cell.hidden = NO;\n cell.alpha = 0.0;\n // 将快照恢复到初始状态\n [UIView animateWithDuration:0.25 animations:^{\n snapshot.center = cell.center;\n snapshot.transform = CGAffineTransformIdentity;\n snapshot.alpha = 0.0;\n cell.alpha = 1.0;\n \n } completion:^(BOOL finished) {\n \n sourceIndexPath = nil;\n [snapshot removeFromSuperview];\n snapshot = nil;\n \n }];\n \n break;\n }\n }\n \n}\n\n```\n长按手势的响应方法,这里创建cell快照,并对快照进行坐标的改变。需要注意的是在长按手势结束的时候一定要把存放触摸点坐标的数组清空,不然下次再继续点击的时候,如果点击的位置距离上次较远,cell快照会突然大幅度移动。\n## 结语\n感谢那位外国网友提供的一些思路及技巧,大家如果发现有任何问题,请告知[光之晨曦_](http://weibo.com/p/1005052211006995/home?from=page_100505&mod=TAB#place),互相交流,寻求技术的巅峰。\n\n\n","slug":"2015-06-20-Cell拖动","published":1,"updated":"2017-03-05T04:18:01.000Z","photos":[],"link":"","_id":"cj0l1ptad00060er9clkr9rbk","content":"<p>有时候项目可能会需要对Cell进行拖动,那么具体如何实现,下面我将详细阐述。<br><a id=\"more\"></a></p>\n<h2 id=\"起因\"><a href=\"#起因\" class=\"headerlink\" title=\"起因\"></a>起因</h2><ul>\n<li><p>最近在做一个项目,要对UITableViewCell进行拖动蹂躏,具体效果如下:</p>\n<p> <img src=\"http://img.blog.csdn.net/20150429173037927\" alt=\"这里写图片描述\"></p>\n</li>\n<li><p>本来打算用UIRespon这几个方法来做,最后发现在UITableViewController中这几个方法不会被响应,具体原因详情见<a href=\"http://stackoverflow.com/questions/8785184/touchesbegan-method-not-called-in-uitableviewcontroller-class-in-iphone\" target=\"_blank\" rel=\"external\">Stack Overflow</a>,于是就选择了使用长按手势来实现,好吧,废话不多少了,直接上料子。</p>\n</li>\n</ul>\n<h2 id=\"经过\"><a href=\"#经过\" class=\"headerlink\" title=\"经过\"></a>经过</h2><h3 id=\"思考\"><a href=\"#思考\" class=\"headerlink\" title=\"思考\"></a>思考</h3><p>让我们来理清思路,大致分为这几步</p>\n<ul>\n<li>首先创建手势并添加,响应手势定义的方法。</li>\n<li>接下根据长按手势的三种状态,分别是起始,改变,结束,在这三种不同状态下我们可以做一些事情。我的思路是在长按手势开始时为cell创建一个快照(可以理解为把cell截成一张图),然后把cell隐藏,之后我们移动的过程中对cell的快照进行操作,等到移动完毕,也就是长按手势结束,显示cell,然后就可以把快照无情的抛弃了。</li>\n<li><h3 id=\"开动\"><a href=\"#开动\" class=\"headerlink\" title=\"开动\"></a>开动</h3></li>\n</ul>\n<figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div></pre></td><td class=\"code\"><pre><div class=\"line\">#pragma mark 设置长按拖动cell</div><div class=\"line\">- (void)setLongPressDrag</div><div class=\"line\">{</div><div class=\"line\"> UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressGestureRecognized:)];</div><div class=\"line\"> [self.tableView addGestureRecognizer:longPress];</div><div class=\"line\">}</div></pre></td></tr></table></figure>\n<p>这个就是创建并添加长按手势,很简单,不再赘述。</p>\n<figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div><div class=\"line\">13</div><div class=\"line\">14</div><div class=\"line\">15</div><div class=\"line\">16</div><div class=\"line\">17</div><div class=\"line\">18</div><div class=\"line\">19</div><div class=\"line\">20</div><div class=\"line\">21</div><div class=\"line\">22</div><div class=\"line\">23</div><div class=\"line\">24</div><div class=\"line\">25</div><div class=\"line\">26</div><div class=\"line\">27</div><div class=\"line\">28</div><div class=\"line\">29</div><div class=\"line\">30</div><div class=\"line\">31</div><div class=\"line\">32</div><div class=\"line\">33</div><div class=\"line\">34</div><div class=\"line\">35</div><div class=\"line\">36</div><div class=\"line\">37</div><div class=\"line\">38</div><div class=\"line\">39</div><div class=\"line\">40</div><div class=\"line\">41</div><div class=\"line\">42</div><div class=\"line\">43</div><div class=\"line\">44</div><div class=\"line\">45</div><div class=\"line\">46</div><div class=\"line\">47</div><div class=\"line\">48</div><div class=\"line\">49</div><div class=\"line\">50</div><div class=\"line\">51</div><div class=\"line\">52</div><div class=\"line\">53</div><div class=\"line\">54</div><div class=\"line\">55</div><div class=\"line\">56</div><div class=\"line\">57</div><div class=\"line\">58</div><div class=\"line\">59</div><div class=\"line\">60</div><div class=\"line\">61</div><div class=\"line\">62</div><div class=\"line\">63</div><div class=\"line\">64</div><div class=\"line\">65</div><div class=\"line\">66</div><div class=\"line\">67</div><div class=\"line\">68</div><div class=\"line\">69</div><div class=\"line\">70</div><div class=\"line\">71</div><div class=\"line\">72</div><div class=\"line\">73</div><div class=\"line\">74</div><div class=\"line\">75</div><div class=\"line\">76</div><div class=\"line\">77</div><div class=\"line\">78</div><div class=\"line\">79</div><div class=\"line\">80</div><div class=\"line\">81</div><div class=\"line\">82</div><div class=\"line\">83</div><div class=\"line\">84</div><div class=\"line\">85</div><div class=\"line\">86</div><div class=\"line\">87</div><div class=\"line\">88</div><div class=\"line\">89</div><div class=\"line\">90</div><div class=\"line\">91</div><div class=\"line\">92</div><div class=\"line\">93</div><div class=\"line\">94</div><div class=\"line\">95</div><div class=\"line\">96</div><div class=\"line\">97</div><div class=\"line\">98</div><div class=\"line\">99</div><div class=\"line\">100</div><div class=\"line\">101</div><div class=\"line\">102</div><div class=\"line\">103</div><div class=\"line\">104</div><div class=\"line\">105</div><div class=\"line\">106</div><div class=\"line\">107</div><div class=\"line\">108</div><div class=\"line\">109</div><div class=\"line\">110</div><div class=\"line\">111</div><div class=\"line\">112</div><div class=\"line\">113</div><div class=\"line\">114</div><div class=\"line\">115</div><div class=\"line\">116</div><div class=\"line\">117</div><div class=\"line\">118</div><div class=\"line\">119</div></pre></td><td class=\"code\"><pre><div class=\"line\">#pragma mark 创建cell的快照</div><div class=\"line\">- (UIView *)customSnapshoFromView:(UIView *)inputView {</div><div class=\"line\"> // 用cell的图层生成UIImage,方便一会显示</div><div class=\"line\"> UIGraphicsBeginImageContextWithOptions(inputView.bounds.size, NO, 0);</div><div class=\"line\"> [inputView.layer renderInContext:UIGraphicsGetCurrentContext()];</div><div class=\"line\"> UIImage *image = UIGraphicsGetImageFromCurrentImageContext();</div><div class=\"line\"> UIGraphicsEndImageContext();</div><div class=\"line\"> // 自定义这个快照的样子(下面的一些参数可以自己随意设置)</div><div class=\"line\"> UIView *snapshot = [[UIImageView alloc] initWithImage:image];</div><div class=\"line\"> snapshot.layer.masksToBounds = NO;</div><div class=\"line\"> snapshot.layer.cornerRadius = 0.0;</div><div class=\"line\"> snapshot.layer.shadowOffset = CGSizeMake(-5.0, 0.0);</div><div class=\"line\"> snapshot.layer.shadowRadius = 5.0;</div><div class=\"line\"> snapshot.layer.shadowOpacity = 0.4;</div><div class=\"line\"> return snapshot;</div><div class=\"line\">}</div><div class=\"line\"></div><div class=\"line\">为cell创建一个快照,等会就可以用上它了。</div><div class=\"line\"></div><div class=\"line\">pragma mark 长按手势方法</div><div class=\"line\">- (void)longPressGestureRecognized:(id)sender {</div><div class=\"line\"> UILongPressGestureRecognizer *longPress = (UILongPressGestureRecognizer *)sender;</div><div class=\"line\"> UIGestureRecognizerState state = longPress.state;</div><div class=\"line\"> CGPoint location = [longPress locationInView:self.tableView];</div><div class=\"line\"> NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];</div><div class=\"line\"> static UIView *snapshot = nil;</div><div class=\"line\"> static NSIndexPath *sourceIndexPath = nil;</div><div class=\"line\"></div><div class=\"line\"> switch (state) {</div><div class=\"line\"> // 已经开始按下</div><div class=\"line\"> case UIGestureRecognizerStateBegan: {</div><div class=\"line\"> // 判断是不是按在了cell上面</div><div class=\"line\"> if (indexPath) {</div><div class=\"line\"> sourceIndexPath = indexPath;</div><div class=\"line\"> UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];</div><div class=\"line\"> // 为拖动的cell添加一个快照</div><div class=\"line\"> snapshot = [self customSnapshoFromView:cell];</div><div class=\"line\"> // 添加快照至tableView中</div><div class=\"line\"> __block CGPoint center = cell.center;</div><div class=\"line\"> snapshot.center = center;</div><div class=\"line\"> snapshot.alpha = 0.0;</div><div class=\"line\"> [self.tableView addSubview:snapshot];</div><div class=\"line\"> // 按下的瞬间执行动画</div><div class=\"line\"> [UIView animateWithDuration:0.25 animations:^{</div><div class=\"line\"> center.y = location.y;</div><div class=\"line\"> snapshot.center = center;</div><div class=\"line\"> snapshot.transform = CGAffineTransformMakeScale(1.05, 1.05);</div><div class=\"line\"> snapshot.alpha = 0.98;</div><div class=\"line\"> cell.alpha = 0.0;</div><div class=\"line\"> </div><div class=\"line\"> } completion:^(BOOL finished) {</div><div class=\"line\"> </div><div class=\"line\"> cell.hidden = YES;</div><div class=\"line\"> </div><div class=\"line\"> }];</div><div class=\"line\"> }</div><div class=\"line\"> break;</div><div class=\"line\"> }</div><div class=\"line\"> // 移动过程中</div><div class=\"line\"> case UIGestureRecognizerStateChanged: {</div><div class=\"line\"> // 这里保持数组里面只有最新的两次触摸点的坐标</div><div class=\"line\"> [self.touchPoints addObject:[NSValue valueWithCGPoint:location]];</div><div class=\"line\"> if (self.touchPoints.count > 2) {</div><div class=\"line\"> [self.touchPoints removeObjectAtIndex:0];</div><div class=\"line\"> }</div><div class=\"line\"> CGPoint center = snapshot.center;</div><div class=\"line\"> // 快照随触摸点y值移动(当然也可以根据触摸点的y轴移动量来移动)</div><div class=\"line\"> center.y = location.y;</div><div class=\"line\"> // 快照随触摸点x值改变量移动</div><div class=\"line\"> CGPoint Ppoint = [[self.touchPoints firstObject] CGPointValue];</div><div class=\"line\"> CGPoint Npoint = [[self.touchPoints lastObject] CGPointValue];</div><div class=\"line\"> CGFloat moveX = Npoint.x - Ppoint.x;</div><div class=\"line\"> center.x += moveX;</div><div class=\"line\"> snapshot.center = center;</div><div class=\"line\"> NSLog(@"%@---%f----%@", self.touchPoints, moveX, NSStringFromCGPoint(center));</div><div class=\"line\"> NSLog(@"%@", NSStringFromCGRect(snapshot.frame));</div><div class=\"line\"> // 是否移动了</div><div class=\"line\"> if (indexPath && ![indexPath isEqual:sourceIndexPath]) {</div><div class=\"line\"> </div><div class=\"line\"> // 更新数组中的内容</div><div class=\"line\">\t [self.dataArray exchangeObjectAtIndex:</div><div class=\"line\">\t indexPath.row withObjectAtIndex:sourceIndexPath.row];</div><div class=\"line\"> </div><div class=\"line\"> // 把cell移动至指定行</div><div class=\"line\"> [self.tableView moveRowAtIndexPath:sourceIndexPath toIndexPath:indexPath];</div><div class=\"line\"> </div><div class=\"line\"> // 存储改变后indexPath的值,以便下次比较</div><div class=\"line\"> sourceIndexPath = indexPath;</div><div class=\"line\"> }</div><div class=\"line\"> break;</div><div class=\"line\"> }</div><div class=\"line\"> // 长按手势取消状态</div><div class=\"line\"> default: {</div><div class=\"line\"> // 清除操作</div><div class=\"line\"> // 清空数组,非常重要,不然会发生坐标突变!</div><div class=\"line\"> [self.touchPoints removeAllObjects];</div><div class=\"line\"> UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:sourceIndexPath];</div><div class=\"line\"> cell.hidden = NO;</div><div class=\"line\"> cell.alpha = 0.0;</div><div class=\"line\"> // 将快照恢复到初始状态</div><div class=\"line\"> [UIView animateWithDuration:0.25 animations:^{</div><div class=\"line\"> snapshot.center = cell.center;</div><div class=\"line\"> snapshot.transform = CGAffineTransformIdentity;</div><div class=\"line\"> snapshot.alpha = 0.0;</div><div class=\"line\"> cell.alpha = 1.0;</div><div class=\"line\"> </div><div class=\"line\"> } completion:^(BOOL finished) {</div><div class=\"line\"> </div><div class=\"line\"> sourceIndexPath = nil;</div><div class=\"line\"> [snapshot removeFromSuperview];</div><div class=\"line\"> snapshot = nil;</div><div class=\"line\"> </div><div class=\"line\"> }];</div><div class=\"line\"> </div><div class=\"line\"> break;</div><div class=\"line\"> }</div><div class=\"line\"> }</div><div class=\"line\"> </div><div class=\"line\">}</div></pre></td></tr></table></figure>\n<p>长按手势的响应方法,这里创建cell快照,并对快照进行坐标的改变。需要注意的是在长按手势结束的时候一定要把存放触摸点坐标的数组清空,不然下次再继续点击的时候,如果点击的位置距离上次较远,cell快照会突然大幅度移动。</p>\n<h2 id=\"结语\"><a href=\"#结语\" class=\"headerlink\" title=\"结语\"></a>结语</h2><p>感谢那位外国网友提供的一些思路及技巧,大家如果发现有任何问题,请告知<a href=\"http://weibo.com/p/1005052211006995/home?from=page_100505&mod=TAB#place\" target=\"_blank\" rel=\"external\">光之晨曦_</a>,互相交流,寻求技术的巅峰。</p>\n","excerpt":"<p>有时候项目可能会需要对Cell进行拖动,那么具体如何实现,下面我将详细阐述。<br>","more":"</p>\n<h2 id=\"起因\"><a href=\"#起因\" class=\"headerlink\" title=\"起因\"></a>起因</h2><ul>\n<li><p>最近在做一个项目,要对UITableViewCell进行拖动蹂躏,具体效果如下:</p>\n<p> <img src=\"http://img.blog.csdn.net/20150429173037927\" alt=\"这里写图片描述\"></p>\n</li>\n<li><p>本来打算用UIRespon这几个方法来做,最后发现在UITableViewController中这几个方法不会被响应,具体原因详情见<a href=\"http://stackoverflow.com/questions/8785184/touchesbegan-method-not-called-in-uitableviewcontroller-class-in-iphone\">Stack Overflow</a>,于是就选择了使用长按手势来实现,好吧,废话不多少了,直接上料子。</p>\n</li>\n</ul>\n<h2 id=\"经过\"><a href=\"#经过\" class=\"headerlink\" title=\"经过\"></a>经过</h2><h3 id=\"思考\"><a href=\"#思考\" class=\"headerlink\" title=\"思考\"></a>思考</h3><p>让我们来理清思路,大致分为这几步</p>\n<ul>\n<li>首先创建手势并添加,响应手势定义的方法。</li>\n<li>接下根据长按手势的三种状态,分别是起始,改变,结束,在这三种不同状态下我们可以做一些事情。我的思路是在长按手势开始时为cell创建一个快照(可以理解为把cell截成一张图),然后把cell隐藏,之后我们移动的过程中对cell的快照进行操作,等到移动完毕,也就是长按手势结束,显示cell,然后就可以把快照无情的抛弃了。</li>\n<li><h3 id=\"开动\"><a href=\"#开动\" class=\"headerlink\" title=\"开动\"></a>开动</h3></li>\n</ul>\n<figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div></pre></td><td class=\"code\"><pre><div class=\"line\">#pragma mark 设置长按拖动cell</div><div class=\"line\">- (void)setLongPressDrag</div><div class=\"line\">{</div><div class=\"line\"> UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressGestureRecognized:)];</div><div class=\"line\"> [self.tableView addGestureRecognizer:longPress];</div><div class=\"line\">}</div></pre></td></tr></table></figure>\n<p>这个就是创建并添加长按手势,很简单,不再赘述。</p>\n<figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div><div class=\"line\">13</div><div class=\"line\">14</div><div class=\"line\">15</div><div class=\"line\">16</div><div class=\"line\">17</div><div class=\"line\">18</div><div class=\"line\">19</div><div class=\"line\">20</div><div class=\"line\">21</div><div class=\"line\">22</div><div class=\"line\">23</div><div class=\"line\">24</div><div class=\"line\">25</div><div class=\"line\">26</div><div class=\"line\">27</div><div class=\"line\">28</div><div class=\"line\">29</div><div class=\"line\">30</div><div class=\"line\">31</div><div class=\"line\">32</div><div class=\"line\">33</div><div class=\"line\">34</div><div class=\"line\">35</div><div class=\"line\">36</div><div class=\"line\">37</div><div class=\"line\">38</div><div class=\"line\">39</div><div class=\"line\">40</div><div class=\"line\">41</div><div class=\"line\">42</div><div class=\"line\">43</div><div class=\"line\">44</div><div class=\"line\">45</div><div class=\"line\">46</div><div class=\"line\">47</div><div class=\"line\">48</div><div class=\"line\">49</div><div class=\"line\">50</div><div class=\"line\">51</div><div class=\"line\">52</div><div class=\"line\">53</div><div class=\"line\">54</div><div class=\"line\">55</div><div class=\"line\">56</div><div class=\"line\">57</div><div class=\"line\">58</div><div class=\"line\">59</div><div class=\"line\">60</div><div class=\"line\">61</div><div class=\"line\">62</div><div class=\"line\">63</div><div class=\"line\">64</div><div class=\"line\">65</div><div class=\"line\">66</div><div class=\"line\">67</div><div class=\"line\">68</div><div class=\"line\">69</div><div class=\"line\">70</div><div class=\"line\">71</div><div class=\"line\">72</div><div class=\"line\">73</div><div class=\"line\">74</div><div class=\"line\">75</div><div class=\"line\">76</div><div class=\"line\">77</div><div class=\"line\">78</div><div class=\"line\">79</div><div class=\"line\">80</div><div class=\"line\">81</div><div class=\"line\">82</div><div class=\"line\">83</div><div class=\"line\">84</div><div class=\"line\">85</div><div class=\"line\">86</div><div class=\"line\">87</div><div class=\"line\">88</div><div class=\"line\">89</div><div class=\"line\">90</div><div class=\"line\">91</div><div class=\"line\">92</div><div class=\"line\">93</div><div class=\"line\">94</div><div class=\"line\">95</div><div class=\"line\">96</div><div class=\"line\">97</div><div class=\"line\">98</div><div class=\"line\">99</div><div class=\"line\">100</div><div class=\"line\">101</div><div class=\"line\">102</div><div class=\"line\">103</div><div class=\"line\">104</div><div class=\"line\">105</div><div class=\"line\">106</div><div class=\"line\">107</div><div class=\"line\">108</div><div class=\"line\">109</div><div class=\"line\">110</div><div class=\"line\">111</div><div class=\"line\">112</div><div class=\"line\">113</div><div class=\"line\">114</div><div class=\"line\">115</div><div class=\"line\">116</div><div class=\"line\">117</div><div class=\"line\">118</div><div class=\"line\">119</div></pre></td><td class=\"code\"><pre><div class=\"line\">#pragma mark 创建cell的快照</div><div class=\"line\">- (UIView *)customSnapshoFromView:(UIView *)inputView {</div><div class=\"line\"> // 用cell的图层生成UIImage,方便一会显示</div><div class=\"line\"> UIGraphicsBeginImageContextWithOptions(inputView.bounds.size, NO, 0);</div><div class=\"line\"> [inputView.layer renderInContext:UIGraphicsGetCurrentContext()];</div><div class=\"line\"> UIImage *image = UIGraphicsGetImageFromCurrentImageContext();</div><div class=\"line\"> UIGraphicsEndImageContext();</div><div class=\"line\"> // 自定义这个快照的样子(下面的一些参数可以自己随意设置)</div><div class=\"line\"> UIView *snapshot = [[UIImageView alloc] initWithImage:image];</div><div class=\"line\"> snapshot.layer.masksToBounds = NO;</div><div class=\"line\"> snapshot.layer.cornerRadius = 0.0;</div><div class=\"line\"> snapshot.layer.shadowOffset = CGSizeMake(-5.0, 0.0);</div><div class=\"line\"> snapshot.layer.shadowRadius = 5.0;</div><div class=\"line\"> snapshot.layer.shadowOpacity = 0.4;</div><div class=\"line\"> return snapshot;</div><div class=\"line\">}</div><div class=\"line\"></div><div class=\"line\">为cell创建一个快照,等会就可以用上它了。</div><div class=\"line\"></div><div class=\"line\">pragma mark 长按手势方法</div><div class=\"line\">- (void)longPressGestureRecognized:(id)sender {</div><div class=\"line\"> UILongPressGestureRecognizer *longPress = (UILongPressGestureRecognizer *)sender;</div><div class=\"line\"> UIGestureRecognizerState state = longPress.state;</div><div class=\"line\"> CGPoint location = [longPress locationInView:self.tableView];</div><div class=\"line\"> NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];</div><div class=\"line\"> static UIView *snapshot = nil;</div><div class=\"line\"> static NSIndexPath *sourceIndexPath = nil;</div><div class=\"line\"></div><div class=\"line\"> switch (state) {</div><div class=\"line\"> // 已经开始按下</div><div class=\"line\"> case UIGestureRecognizerStateBegan: {</div><div class=\"line\"> // 判断是不是按在了cell上面</div><div class=\"line\"> if (indexPath) {</div><div class=\"line\"> sourceIndexPath = indexPath;</div><div class=\"line\"> UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];</div><div class=\"line\"> // 为拖动的cell添加一个快照</div><div class=\"line\"> snapshot = [self customSnapshoFromView:cell];</div><div class=\"line\"> // 添加快照至tableView中</div><div class=\"line\"> __block CGPoint center = cell.center;</div><div class=\"line\"> snapshot.center = center;</div><div class=\"line\"> snapshot.alpha = 0.0;</div><div class=\"line\"> [self.tableView addSubview:snapshot];</div><div class=\"line\"> // 按下的瞬间执行动画</div><div class=\"line\"> [UIView animateWithDuration:0.25 animations:^{</div><div class=\"line\"> center.y = location.y;</div><div class=\"line\"> snapshot.center = center;</div><div class=\"line\"> snapshot.transform = CGAffineTransformMakeScale(1.05, 1.05);</div><div class=\"line\"> snapshot.alpha = 0.98;</div><div class=\"line\"> cell.alpha = 0.0;</div><div class=\"line\"> </div><div class=\"line\"> } completion:^(BOOL finished) {</div><div class=\"line\"> </div><div class=\"line\"> cell.hidden = YES;</div><div class=\"line\"> </div><div class=\"line\"> }];</div><div class=\"line\"> }</div><div class=\"line\"> break;</div><div class=\"line\"> }</div><div class=\"line\"> // 移动过程中</div><div class=\"line\"> case UIGestureRecognizerStateChanged: {</div><div class=\"line\"> // 这里保持数组里面只有最新的两次触摸点的坐标</div><div class=\"line\"> [self.touchPoints addObject:[NSValue valueWithCGPoint:location]];</div><div class=\"line\"> if (self.touchPoints.count > 2) {</div><div class=\"line\"> [self.touchPoints removeObjectAtIndex:0];</div><div class=\"line\"> }</div><div class=\"line\"> CGPoint center = snapshot.center;</div><div class=\"line\"> // 快照随触摸点y值移动(当然也可以根据触摸点的y轴移动量来移动)</div><div class=\"line\"> center.y = location.y;</div><div class=\"line\"> // 快照随触摸点x值改变量移动</div><div class=\"line\"> CGPoint Ppoint = [[self.touchPoints firstObject] CGPointValue];</div><div class=\"line\"> CGPoint Npoint = [[self.touchPoints lastObject] CGPointValue];</div><div class=\"line\"> CGFloat moveX = Npoint.x - Ppoint.x;</div><div class=\"line\"> center.x += moveX;</div><div class=\"line\"> snapshot.center = center;</div><div class=\"line\"> NSLog(@"%@---%f----%@", self.touchPoints, moveX, NSStringFromCGPoint(center));</div><div class=\"line\"> NSLog(@"%@", NSStringFromCGRect(snapshot.frame));</div><div class=\"line\"> // 是否移动了</div><div class=\"line\"> if (indexPath && ![indexPath isEqual:sourceIndexPath]) {</div><div class=\"line\"> </div><div class=\"line\"> // 更新数组中的内容</div><div class=\"line\">\t [self.dataArray exchangeObjectAtIndex:</div><div class=\"line\">\t indexPath.row withObjectAtIndex:sourceIndexPath.row];</div><div class=\"line\"> </div><div class=\"line\"> // 把cell移动至指定行</div><div class=\"line\"> [self.tableView moveRowAtIndexPath:sourceIndexPath toIndexPath:indexPath];</div><div class=\"line\"> </div><div class=\"line\"> // 存储改变后indexPath的值,以便下次比较</div><div class=\"line\"> sourceIndexPath = indexPath;</div><div class=\"line\"> }</div><div class=\"line\"> break;</div><div class=\"line\"> }</div><div class=\"line\"> // 长按手势取消状态</div><div class=\"line\"> default: {</div><div class=\"line\"> // 清除操作</div><div class=\"line\"> // 清空数组,非常重要,不然会发生坐标突变!</div><div class=\"line\"> [self.touchPoints removeAllObjects];</div><div class=\"line\"> UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:sourceIndexPath];</div><div class=\"line\"> cell.hidden = NO;</div><div class=\"line\"> cell.alpha = 0.0;</div><div class=\"line\"> // 将快照恢复到初始状态</div><div class=\"line\"> [UIView animateWithDuration:0.25 animations:^{</div><div class=\"line\"> snapshot.center = cell.center;</div><div class=\"line\"> snapshot.transform = CGAffineTransformIdentity;</div><div class=\"line\"> snapshot.alpha = 0.0;</div><div class=\"line\"> cell.alpha = 1.0;</div><div class=\"line\"> </div><div class=\"line\"> } completion:^(BOOL finished) {</div><div class=\"line\"> </div><div class=\"line\"> sourceIndexPath = nil;</div><div class=\"line\"> [snapshot removeFromSuperview];</div><div class=\"line\"> snapshot = nil;</div><div class=\"line\"> </div><div class=\"line\"> }];</div><div class=\"line\"> </div><div class=\"line\"> break;</div><div class=\"line\"> }</div><div class=\"line\"> }</div><div class=\"line\"> </div><div class=\"line\">}</div></pre></td></tr></table></figure>\n<p>长按手势的响应方法,这里创建cell快照,并对快照进行坐标的改变。需要注意的是在长按手势结束的时候一定要把存放触摸点坐标的数组清空,不然下次再继续点击的时候,如果点击的位置距离上次较远,cell快照会突然大幅度移动。</p>\n<h2 id=\"结语\"><a href=\"#结语\" class=\"headerlink\" title=\"结语\"></a>结语</h2><p>感谢那位外国网友提供的一些思路及技巧,大家如果发现有任何问题,请告知<a href=\"http://weibo.com/p/1005052211006995/home?from=page_100505&mod=TAB#place\">光之晨曦_</a>,互相交流,寻求技术的巅峰。</p>"},{"layout":"post","title":"成员变量与属性","date":"2015-08-02T16:00:00.000Z","comments":1,"keywords":"Carthage","publish":true,"description":"成员变量与属性","_content":"最近在公司的项目里面发现了很多类成员变量与属性同时出现,感觉很混乱,之前一直是在用属性`@property`声明变量,所以对两者之间的区别比较困惑,于是便仔细的探索了一番。\n<!-- more -->\n\n## 开始\n先来看一看那些让人感觉乱糟糟的成员变量与属性共用的代码吧。\n```\n@interface SearchInfoView()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,SearchCellDelegate> \n{\n UIImageView *_backGroundImg;\n NSMutableArray *_oldSearchArray; \n UIButton *_rightBtn;\n}\n@property(nonatomic, strong)UITableView *historyTableView;\n@property(nonatomic, assign)UIViewController *currentViewControll;\n@end\n```\n\n真的很乱,对于我来说真的是无法忍受,但是他们之间到底有何不同呢?\n\n## 属性\n先来说一下属性`@property`,属性可以自己生成`getter`和`setter`方法,并生成一个待下划线的成员变量,当然你还可以通过`@synthesize`关键字将实例变量重命名。在ARC下对象的存在与否全看有没有强指针的引用,我们无需去考虑计数器了,配合一些如:`strong`, `weak`, `rassign`等关键字,我们不用再去太关心内存。\n\n## 说明\niOS 5更新之后,苹果是建议以以下的方式来使用:\n```\n@interface MyViewController :UIViewController\n@property (nonatomic, retain) UIButton *myButton;\n@end\n```\n\n我看了一些著名的开源框架如:`AFNetworking`以及苹果官方代码来看,基本上很少使用成员变量了,所以我们平时尽可能的使用`@property`,在使用时还是很方便的。\n\n\n","source":"_posts/2015-08-03-成员变量与属性.md","raw":"---\nlayout: post\ntitle: \"成员变量与属性\"\ndate: 2015-08-03\ncomments: true\ncategories: iOS\ntags: [iOS]\nkeywords: Carthage\npublish: true\ndescription: 成员变量与属性\n---\n最近在公司的项目里面发现了很多类成员变量与属性同时出现,感觉很混乱,之前一直是在用属性`@property`声明变量,所以对两者之间的区别比较困惑,于是便仔细的探索了一番。\n<!-- more -->\n\n## 开始\n先来看一看那些让人感觉乱糟糟的成员变量与属性共用的代码吧。\n```\n@interface SearchInfoView()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,SearchCellDelegate> \n{\n UIImageView *_backGroundImg;\n NSMutableArray *_oldSearchArray; \n UIButton *_rightBtn;\n}\n@property(nonatomic, strong)UITableView *historyTableView;\n@property(nonatomic, assign)UIViewController *currentViewControll;\n@end\n```\n\n真的很乱,对于我来说真的是无法忍受,但是他们之间到底有何不同呢?\n\n## 属性\n先来说一下属性`@property`,属性可以自己生成`getter`和`setter`方法,并生成一个待下划线的成员变量,当然你还可以通过`@synthesize`关键字将实例变量重命名。在ARC下对象的存在与否全看有没有强指针的引用,我们无需去考虑计数器了,配合一些如:`strong`, `weak`, `rassign`等关键字,我们不用再去太关心内存。\n\n## 说明\niOS 5更新之后,苹果是建议以以下的方式来使用:\n```\n@interface MyViewController :UIViewController\n@property (nonatomic, retain) UIButton *myButton;\n@end\n```\n\n我看了一些著名的开源框架如:`AFNetworking`以及苹果官方代码来看,基本上很少使用成员变量了,所以我们平时尽可能的使用`@property`,在使用时还是很方便的。\n\n\n","slug":"2015-08-03-成员变量与属性","published":1,"updated":"2017-03-05T04:17:38.000Z","photos":[],"link":"","_id":"cj0l1ptag00070er92x287u8k","content":"<p>最近在公司的项目里面发现了很多类成员变量与属性同时出现,感觉很混乱,之前一直是在用属性<code>@property</code>声明变量,所以对两者之间的区别比较困惑,于是便仔细的探索了一番。<br><a id=\"more\"></a></p>\n<h2 id=\"开始\"><a href=\"#开始\" class=\"headerlink\" title=\"开始\"></a>开始</h2><p>先来看一看那些让人感觉乱糟糟的成员变量与属性共用的代码吧。<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div></pre></td><td class=\"code\"><pre><div class=\"line\">@interface SearchInfoView()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,SearchCellDelegate> </div><div class=\"line\">{</div><div class=\"line\"> UIImageView *_backGroundImg;</div><div class=\"line\"> NSMutableArray *_oldSearchArray; </div><div class=\"line\"> UIButton *_rightBtn;</div><div class=\"line\">}</div><div class=\"line\">@property(nonatomic, strong)UITableView *historyTableView;</div><div class=\"line\">@property(nonatomic, assign)UIViewController *currentViewControll;</div><div class=\"line\">@end</div></pre></td></tr></table></figure></p>\n<p>真的很乱,对于我来说真的是无法忍受,但是他们之间到底有何不同呢?</p>\n<h2 id=\"属性\"><a href=\"#属性\" class=\"headerlink\" title=\"属性\"></a>属性</h2><p>先来说一下属性<code>@property</code>,属性可以自己生成<code>getter</code>和<code>setter</code>方法,并生成一个待下划线的成员变量,当然你还可以通过<code>@synthesize</code>关键字将实例变量重命名。在ARC下对象的存在与否全看有没有强指针的引用,我们无需去考虑计数器了,配合一些如:<code>strong</code>, <code>weak</code>, <code>rassign</code>等关键字,我们不用再去太关心内存。</p>\n<h2 id=\"说明\"><a href=\"#说明\" class=\"headerlink\" title=\"说明\"></a>说明</h2><p>iOS 5更新之后,苹果是建议以以下的方式来使用:<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div></pre></td><td class=\"code\"><pre><div class=\"line\">@interface MyViewController :UIViewController</div><div class=\"line\">@property (nonatomic, retain) UIButton *myButton;</div><div class=\"line\">@end</div></pre></td></tr></table></figure></p>\n<p>我看了一些著名的开源框架如:<code>AFNetworking</code>以及苹果官方代码来看,基本上很少使用成员变量了,所以我们平时尽可能的使用<code>@property</code>,在使用时还是很方便的。</p>\n","excerpt":"<p>最近在公司的项目里面发现了很多类成员变量与属性同时出现,感觉很混乱,之前一直是在用属性<code>@property</code>声明变量,所以对两者之间的区别比较困惑,于是便仔细的探索了一番。<br>","more":"</p>\n<h2 id=\"开始\"><a href=\"#开始\" class=\"headerlink\" title=\"开始\"></a>开始</h2><p>先来看一看那些让人感觉乱糟糟的成员变量与属性共用的代码吧。<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div></pre></td><td class=\"code\"><pre><div class=\"line\">@interface SearchInfoView()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,SearchCellDelegate> </div><div class=\"line\">{</div><div class=\"line\"> UIImageView *_backGroundImg;</div><div class=\"line\"> NSMutableArray *_oldSearchArray; </div><div class=\"line\"> UIButton *_rightBtn;</div><div class=\"line\">}</div><div class=\"line\">@property(nonatomic, strong)UITableView *historyTableView;</div><div class=\"line\">@property(nonatomic, assign)UIViewController *currentViewControll;</div><div class=\"line\">@end</div></pre></td></tr></table></figure></p>\n<p>真的很乱,对于我来说真的是无法忍受,但是他们之间到底有何不同呢?</p>\n<h2 id=\"属性\"><a href=\"#属性\" class=\"headerlink\" title=\"属性\"></a>属性</h2><p>先来说一下属性<code>@property</code>,属性可以自己生成<code>getter</code>和<code>setter</code>方法,并生成一个待下划线的成员变量,当然你还可以通过<code>@synthesize</code>关键字将实例变量重命名。在ARC下对象的存在与否全看有没有强指针的引用,我们无需去考虑计数器了,配合一些如:<code>strong</code>, <code>weak</code>, <code>rassign</code>等关键字,我们不用再去太关心内存。</p>\n<h2 id=\"说明\"><a href=\"#说明\" class=\"headerlink\" title=\"说明\"></a>说明</h2><p>iOS 5更新之后,苹果是建议以以下的方式来使用:<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div></pre></td><td class=\"code\"><pre><div class=\"line\">@interface MyViewController :UIViewController</div><div class=\"line\">@property (nonatomic, retain) UIButton *myButton;</div><div class=\"line\">@end</div></pre></td></tr></table></figure></p>\n<p>我看了一些著名的开源框架如:<code>AFNetworking</code>以及苹果官方代码来看,基本上很少使用成员变量了,所以我们平时尽可能的使用<code>@property</code>,在使用时还是很方便的。</p>"},{"layout":"post","title":"快把你的bash换掉吧","date":"2015-08-04T16:00:00.000Z","comments":1,"keywords":"oh-my-zsh","publish":true,"description":"快把你的bash换掉吧","_content":"对于经常使用Mac终端的人而言,需要牢记大量复杂的命令,而开源的`zsh`则帮助用户减少了大脑的负荷,增加了使用的便捷性,而且还有许多主题可以随意更换,用起来更加的爽了。所以,赶紧换掉那个陈旧的`bash`吧.\n<!-- more -->\n\n## 什么是shell?\n`shell`是Linux/Unix的一个外壳,你理解成衣服也行。它负责外界与内核的交互,接收用户或其他应用程序的命令,然后把这些命令转化成内核能理解的语言,传给内核,内核是真正干活的,干完之后再把结果返回用户或应用程序。所以,工具用着不爽,当然就要更换一个效率更高的,功能更强大的,而`zsh`更是被誉为`终端的终结者`。\n\n想知道自己的电脑支持几种`shell`,可以用下面这个命令:\n```\ncat /etc/shells\n```\n\n然后你会看见:\n```\n/bin/bash\n/bin/csh\n/bin/ksh\n/bin/sh\n/bin/tcsh\n/bin/zsh\n```\n\n这样的东西。好吧,科普到此结束了。\n## oh-my-zsh\n废话不多说,我们今天的主角就是`oh-my-zsh`,它是`zsh`的一种,拥有着强大的功能和丰富的主题。在[github](https://github.com/robbyrussell/oh-my-zsh)上超过两万多颗星星。[这是](http://ohmyz.sh)官方的介绍,有兴趣的可以去看一看。\n\n## 安装\n`oh-my-zsh`的安装很简单,但是前提是你的电脑应该有`git`,输入:\n```\ngit --version\n```\n\n查看`git`版本。\n\n最简单的安装方法,在终端中输入:\n```\nsh -c \"$(curl -fsSL https://raw.github.com/robbyrussell/oh-my-zsh/master/tools/install.sh)\"\n```\n\n其他安装方法不再赘述,详情见[oh-my-zsh](https://github.com/robbyrussell/oh-my-zsh)的`github`地址。\n\n## 卸载\n\n卸载之后,终端将使用默认的`shell`,一般是`bash`。\n```\nuninstall_oh_my_zsh\n```\n\n## 主题\n[这里](https://github.com/robbyrussell/oh-my-zsh/wiki/Themes)有上百种主题,总有一款你喜欢的。想要修改主题,需要修改`.zshrc`文件,这个文件是隐藏的,所以最好在终端中修改,在终端中输入:\n```\nvi ~/.zshrc\n```\n\n然后会出现:\n\t```\n\n\t# Path to your oh-my-zsh installation.\n\texport ZSH=/Users/ctt/.oh-my-zsh\n\n\t# Set name of the theme to load.\n\t# Look in ~/.oh-my-zsh/themes/\n\t# Optionally, if you set this to \"random\", it'll load a random theme each\n\t# time that oh-my-zsh is loaded.\n\tZSH_THEME=\"robbyrussell\"\n\n\t# Uncomment the following line to use case-sensitive completion.\n\t# CASE_SENSITIVE=\"true\"\n\n\t# Uncomment the following line to use hyphen-insensitive completion. Case\n\t# sensitive completion must be off. _ and - will be interchangeable.\n\t# HYPHEN_INSENSITIVE=\"true\"\n\n\t# Uncomment the following line to disable bi-weekly auto-update checks.\n\t# DISABLE_AUTO_UPDATE=\"true\"\n\n\t# Uncomment the following line to change how often to auto-update (in days).\n\t# export UPDATE_ZSH_DAYS=13\n\n\t# Uncomment the following line to disable colors in ls.\n\t\"~/.zshrc\" 84L, 2798C\n\t```\n\n把`ZSH_THEME=\"robbyrussell\"`中的主题改成你想要的名字保存即可,但是必须是`.oh-my-zsh/themes`中有的。\n```\n\n\t➜ ~ cd .oh-my-zsh \n\t➜ .oh-my-zsh git:(master) ls\n\tMIT-LICENSE.txt custom oh-my-zsh.sh themes\n\tREADME.markdown lib plugins tools\n\tcache log templates\n\t➜ .oh-my-zsh git:(master) cd themes \n\t➜ themes git:(master) ls\n\t3den.zsh-theme kafeitu.zsh-theme\n\tSoliah.zsh-theme kardan.zsh-theme\n\tadben.zsh-theme kennethreitz.zsh-theme\n\taf-magic.zsh-theme kiwi.zsh-theme\n\tafowler.zsh-theme kolo.zsh-theme\n\tagnoster.zsh-theme kphoen.zsh-theme\n\talanpeabody.zsh-theme lambda.zsh-theme\n\tamuse.zsh-theme linuxonly.zsh-theme\n\tapple.zsh-theme lukerandall.zsh-theme\n\t...\n```\n\n## 最后\n愿大家玩的高兴。^_^\n\n","source":"_posts/2015-08-05-快把你的bash换掉吧.md","raw":"---\nlayout: post\ntitle: \"快把你的bash换掉吧\"\ndate: 2015-08-05\ncomments: true\ncategories: Mac工具\ntags: [Mac工具]\nkeywords: oh-my-zsh\npublish: true\ndescription: 快把你的bash换掉吧\n---\n对于经常使用Mac终端的人而言,需要牢记大量复杂的命令,而开源的`zsh`则帮助用户减少了大脑的负荷,增加了使用的便捷性,而且还有许多主题可以随意更换,用起来更加的爽了。所以,赶紧换掉那个陈旧的`bash`吧.\n<!-- more -->\n\n## 什么是shell?\n`shell`是Linux/Unix的一个外壳,你理解成衣服也行。它负责外界与内核的交互,接收用户或其他应用程序的命令,然后把这些命令转化成内核能理解的语言,传给内核,内核是真正干活的,干完之后再把结果返回用户或应用程序。所以,工具用着不爽,当然就要更换一个效率更高的,功能更强大的,而`zsh`更是被誉为`终端的终结者`。\n\n想知道自己的电脑支持几种`shell`,可以用下面这个命令:\n```\ncat /etc/shells\n```\n\n然后你会看见:\n```\n/bin/bash\n/bin/csh\n/bin/ksh\n/bin/sh\n/bin/tcsh\n/bin/zsh\n```\n\n这样的东西。好吧,科普到此结束了。\n## oh-my-zsh\n废话不多说,我们今天的主角就是`oh-my-zsh`,它是`zsh`的一种,拥有着强大的功能和丰富的主题。在[github](https://github.com/robbyrussell/oh-my-zsh)上超过两万多颗星星。[这是](http://ohmyz.sh)官方的介绍,有兴趣的可以去看一看。\n\n## 安装\n`oh-my-zsh`的安装很简单,但是前提是你的电脑应该有`git`,输入:\n```\ngit --version\n```\n\n查看`git`版本。\n\n最简单的安装方法,在终端中输入:\n```\nsh -c \"$(curl -fsSL https://raw.github.com/robbyrussell/oh-my-zsh/master/tools/install.sh)\"\n```\n\n其他安装方法不再赘述,详情见[oh-my-zsh](https://github.com/robbyrussell/oh-my-zsh)的`github`地址。\n\n## 卸载\n\n卸载之后,终端将使用默认的`shell`,一般是`bash`。\n```\nuninstall_oh_my_zsh\n```\n\n## 主题\n[这里](https://github.com/robbyrussell/oh-my-zsh/wiki/Themes)有上百种主题,总有一款你喜欢的。想要修改主题,需要修改`.zshrc`文件,这个文件是隐藏的,所以最好在终端中修改,在终端中输入:\n```\nvi ~/.zshrc\n```\n\n然后会出现:\n\t```\n\n\t# Path to your oh-my-zsh installation.\n\texport ZSH=/Users/ctt/.oh-my-zsh\n\n\t# Set name of the theme to load.\n\t# Look in ~/.oh-my-zsh/themes/\n\t# Optionally, if you set this to \"random\", it'll load a random theme each\n\t# time that oh-my-zsh is loaded.\n\tZSH_THEME=\"robbyrussell\"\n\n\t# Uncomment the following line to use case-sensitive completion.\n\t# CASE_SENSITIVE=\"true\"\n\n\t# Uncomment the following line to use hyphen-insensitive completion. Case\n\t# sensitive completion must be off. _ and - will be interchangeable.\n\t# HYPHEN_INSENSITIVE=\"true\"\n\n\t# Uncomment the following line to disable bi-weekly auto-update checks.\n\t# DISABLE_AUTO_UPDATE=\"true\"\n\n\t# Uncomment the following line to change how often to auto-update (in days).\n\t# export UPDATE_ZSH_DAYS=13\n\n\t# Uncomment the following line to disable colors in ls.\n\t\"~/.zshrc\" 84L, 2798C\n\t```\n\n把`ZSH_THEME=\"robbyrussell\"`中的主题改成你想要的名字保存即可,但是必须是`.oh-my-zsh/themes`中有的。\n```\n\n\t➜ ~ cd .oh-my-zsh \n\t➜ .oh-my-zsh git:(master) ls\n\tMIT-LICENSE.txt custom oh-my-zsh.sh themes\n\tREADME.markdown lib plugins tools\n\tcache log templates\n\t➜ .oh-my-zsh git:(master) cd themes \n\t➜ themes git:(master) ls\n\t3den.zsh-theme kafeitu.zsh-theme\n\tSoliah.zsh-theme kardan.zsh-theme\n\tadben.zsh-theme kennethreitz.zsh-theme\n\taf-magic.zsh-theme kiwi.zsh-theme\n\tafowler.zsh-theme kolo.zsh-theme\n\tagnoster.zsh-theme kphoen.zsh-theme\n\talanpeabody.zsh-theme lambda.zsh-theme\n\tamuse.zsh-theme linuxonly.zsh-theme\n\tapple.zsh-theme lukerandall.zsh-theme\n\t...\n```\n\n## 最后\n愿大家玩的高兴。^_^\n\n","slug":"2015-08-05-快把你的bash换掉吧","published":1,"updated":"2017-03-05T04:17:23.000Z","photos":[],"link":"","_id":"cj0l1ptak000b0er9n8jlc6y3","content":"<p>对于经常使用Mac终端的人而言,需要牢记大量复杂的命令,而开源的<code>zsh</code>则帮助用户减少了大脑的负荷,增加了使用的便捷性,而且还有许多主题可以随意更换,用起来更加的爽了。所以,赶紧换掉那个陈旧的<code>bash</code>吧.<br><a id=\"more\"></a></p>\n<h2 id=\"什么是shell?\"><a href=\"#什么是shell?\" class=\"headerlink\" title=\"什么是shell?\"></a>什么是shell?</h2><p><code>shell</code>是Linux/Unix的一个外壳,你理解成衣服也行。它负责外界与内核的交互,接收用户或其他应用程序的命令,然后把这些命令转化成内核能理解的语言,传给内核,内核是真正干活的,干完之后再把结果返回用户或应用程序。所以,工具用着不爽,当然就要更换一个效率更高的,功能更强大的,而<code>zsh</code>更是被誉为<code>终端的终结者</code>。</p>\n<p>想知道自己的电脑支持几种<code>shell</code>,可以用下面这个命令:<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div></pre></td><td class=\"code\"><pre><div class=\"line\">cat /etc/shells</div></pre></td></tr></table></figure></p>\n<p>然后你会看见:<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div></pre></td><td class=\"code\"><pre><div class=\"line\">/bin/bash</div><div class=\"line\">/bin/csh</div><div class=\"line\">/bin/ksh</div><div class=\"line\">/bin/sh</div><div class=\"line\">/bin/tcsh</div><div class=\"line\">/bin/zsh</div></pre></td></tr></table></figure></p>\n<p>这样的东西。好吧,科普到此结束了。</p>\n<h2 id=\"oh-my-zsh\"><a href=\"#oh-my-zsh\" class=\"headerlink\" title=\"oh-my-zsh\"></a>oh-my-zsh</h2><p>废话不多说,我们今天的主角就是<code>oh-my-zsh</code>,它是<code>zsh</code>的一种,拥有着强大的功能和丰富的主题。在<a href=\"https://github.com/robbyrussell/oh-my-zsh\" target=\"_blank\" rel=\"external\">github</a>上超过两万多颗星星。<a href=\"http://ohmyz.sh\" target=\"_blank\" rel=\"external\">这是</a>官方的介绍,有兴趣的可以去看一看。</p>\n<h2 id=\"安装\"><a href=\"#安装\" class=\"headerlink\" title=\"安装\"></a>安装</h2><p><code>oh-my-zsh</code>的安装很简单,但是前提是你的电脑应该有<code>git</code>,输入:<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div></pre></td><td class=\"code\"><pre><div class=\"line\">git --version</div></pre></td></tr></table></figure></p>\n<p>查看<code>git</code>版本。</p>\n<p>最简单的安装方法,在终端中输入:<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div></pre></td><td class=\"code\"><pre><div class=\"line\">sh -c "$(curl -fsSL https://raw.github.com/robbyrussell/oh-my-zsh/master/tools/install.sh)"</div></pre></td></tr></table></figure></p>\n<p>其他安装方法不再赘述,详情见<a href=\"https://github.com/robbyrussell/oh-my-zsh\" target=\"_blank\" rel=\"external\">oh-my-zsh</a>的<code>github</code>地址。</p>\n<h2 id=\"卸载\"><a href=\"#卸载\" class=\"headerlink\" title=\"卸载\"></a>卸载</h2><p>卸载之后,终端将使用默认的<code>shell</code>,一般是<code>bash</code>。<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div></pre></td><td class=\"code\"><pre><div class=\"line\">uninstall_oh_my_zsh</div></pre></td></tr></table></figure></p>\n<h2 id=\"主题\"><a href=\"#主题\" class=\"headerlink\" title=\"主题\"></a>主题</h2><p><a href=\"https://github.com/robbyrussell/oh-my-zsh/wiki/Themes\" target=\"_blank\" rel=\"external\">这里</a>有上百种主题,总有一款你喜欢的。想要修改主题,需要修改<code>.zshrc</code>文件,这个文件是隐藏的,所以最好在终端中修改,在终端中输入:<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div></pre></td><td class=\"code\"><pre><div class=\"line\">vi ~/.zshrc</div></pre></td></tr></table></figure></p>\n<p>然后会出现:<br> <figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div><div class=\"line\">13</div><div class=\"line\">14</div><div class=\"line\">15</div><div class=\"line\">16</div><div class=\"line\">17</div><div class=\"line\">18</div><div class=\"line\">19</div><div class=\"line\">20</div><div class=\"line\">21</div><div class=\"line\">22</div><div class=\"line\">23</div><div class=\"line\">24</div><div class=\"line\">25</div></pre></td><td class=\"code\"><pre><div class=\"line\"></div><div class=\"line\"># Path to your oh-my-zsh installation.</div><div class=\"line\">export ZSH=/Users/ctt/.oh-my-zsh</div><div class=\"line\"></div><div class=\"line\"># Set name of the theme to load.</div><div class=\"line\"># Look in ~/.oh-my-zsh/themes/</div><div class=\"line\"># Optionally, if you set this to "random", it'll load a random theme each</div><div class=\"line\"># time that oh-my-zsh is loaded.</div><div class=\"line\">ZSH_THEME="robbyrussell"</div><div class=\"line\"></div><div class=\"line\"># Uncomment the following line to use case-sensitive completion.</div><div class=\"line\"># CASE_SENSITIVE="true"</div><div class=\"line\"></div><div class=\"line\"># Uncomment the following line to use hyphen-insensitive completion. Case</div><div class=\"line\"># sensitive completion must be off. _ and - will be interchangeable.</div><div class=\"line\"># HYPHEN_INSENSITIVE="true"</div><div class=\"line\"></div><div class=\"line\"># Uncomment the following line to disable bi-weekly auto-update checks.</div><div class=\"line\"># DISABLE_AUTO_UPDATE="true"</div><div class=\"line\"></div><div class=\"line\"># Uncomment the following line to change how often to auto-update (in days).</div><div class=\"line\"># export UPDATE_ZSH_DAYS=13</div><div class=\"line\"></div><div class=\"line\"># Uncomment the following line to disable colors in ls.</div><div class=\"line\">"~/.zshrc" 84L, 2798C</div></pre></td></tr></table></figure></p>\n<p>把<code>ZSH_THEME="robbyrussell"</code>中的主题改成你想要的名字保存即可,但是必须是<code>.oh-my-zsh/themes</code>中有的。<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div><div class=\"line\">13</div><div class=\"line\">14</div><div class=\"line\">15</div><div class=\"line\">16</div><div class=\"line\">17</div><div class=\"line\">18</div></pre></td><td class=\"code\"><pre><div class=\"line\"></div><div class=\"line\">➜ ~ cd .oh-my-zsh </div><div class=\"line\">➜ .oh-my-zsh git:(master) ls</div><div class=\"line\">MIT-LICENSE.txt custom oh-my-zsh.sh themes</div><div class=\"line\">README.markdown lib plugins tools</div><div class=\"line\">cache log templates</div><div class=\"line\">➜ .oh-my-zsh git:(master) cd themes </div><div class=\"line\">➜ themes git:(master) ls</div><div class=\"line\">3den.zsh-theme kafeitu.zsh-theme</div><div class=\"line\">Soliah.zsh-theme kardan.zsh-theme</div><div class=\"line\">adben.zsh-theme kennethreitz.zsh-theme</div><div class=\"line\">af-magic.zsh-theme kiwi.zsh-theme</div><div class=\"line\">afowler.zsh-theme kolo.zsh-theme</div><div class=\"line\">agnoster.zsh-theme kphoen.zsh-theme</div><div class=\"line\">alanpeabody.zsh-theme lambda.zsh-theme</div><div class=\"line\">amuse.zsh-theme linuxonly.zsh-theme</div><div class=\"line\">apple.zsh-theme lukerandall.zsh-theme</div><div class=\"line\">...</div></pre></td></tr></table></figure></p>\n<h2 id=\"最后\"><a href=\"#最后\" class=\"headerlink\" title=\"最后\"></a>最后</h2><p>愿大家玩的高兴。^_^</p>\n","excerpt":"<p>对于经常使用Mac终端的人而言,需要牢记大量复杂的命令,而开源的<code>zsh</code>则帮助用户减少了大脑的负荷,增加了使用的便捷性,而且还有许多主题可以随意更换,用起来更加的爽了。所以,赶紧换掉那个陈旧的<code>bash</code>吧.<br>","more":"</p>\n<h2 id=\"什么是shell?\"><a href=\"#什么是shell?\" class=\"headerlink\" title=\"什么是shell?\"></a>什么是shell?</h2><p><code>shell</code>是Linux/Unix的一个外壳,你理解成衣服也行。它负责外界与内核的交互,接收用户或其他应用程序的命令,然后把这些命令转化成内核能理解的语言,传给内核,内核是真正干活的,干完之后再把结果返回用户或应用程序。所以,工具用着不爽,当然就要更换一个效率更高的,功能更强大的,而<code>zsh</code>更是被誉为<code>终端的终结者</code>。</p>\n<p>想知道自己的电脑支持几种<code>shell</code>,可以用下面这个命令:<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div></pre></td><td class=\"code\"><pre><div class=\"line\">cat /etc/shells</div></pre></td></tr></table></figure></p>\n<p>然后你会看见:<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div></pre></td><td class=\"code\"><pre><div class=\"line\">/bin/bash</div><div class=\"line\">/bin/csh</div><div class=\"line\">/bin/ksh</div><div class=\"line\">/bin/sh</div><div class=\"line\">/bin/tcsh</div><div class=\"line\">/bin/zsh</div></pre></td></tr></table></figure></p>\n<p>这样的东西。好吧,科普到此结束了。</p>\n<h2 id=\"oh-my-zsh\"><a href=\"#oh-my-zsh\" class=\"headerlink\" title=\"oh-my-zsh\"></a>oh-my-zsh</h2><p>废话不多说,我们今天的主角就是<code>oh-my-zsh</code>,它是<code>zsh</code>的一种,拥有着强大的功能和丰富的主题。在<a href=\"https://github.com/robbyrussell/oh-my-zsh\">github</a>上超过两万多颗星星。<a href=\"http://ohmyz.sh\">这是</a>官方的介绍,有兴趣的可以去看一看。</p>\n<h2 id=\"安装\"><a href=\"#安装\" class=\"headerlink\" title=\"安装\"></a>安装</h2><p><code>oh-my-zsh</code>的安装很简单,但是前提是你的电脑应该有<code>git</code>,输入:<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div></pre></td><td class=\"code\"><pre><div class=\"line\">git --version</div></pre></td></tr></table></figure></p>\n<p>查看<code>git</code>版本。</p>\n<p>最简单的安装方法,在终端中输入:<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div></pre></td><td class=\"code\"><pre><div class=\"line\">sh -c "$(curl -fsSL https://raw.github.com/robbyrussell/oh-my-zsh/master/tools/install.sh)"</div></pre></td></tr></table></figure></p>\n<p>其他安装方法不再赘述,详情见<a href=\"https://github.com/robbyrussell/oh-my-zsh\">oh-my-zsh</a>的<code>github</code>地址。</p>\n<h2 id=\"卸载\"><a href=\"#卸载\" class=\"headerlink\" title=\"卸载\"></a>卸载</h2><p>卸载之后,终端将使用默认的<code>shell</code>,一般是<code>bash</code>。<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div></pre></td><td class=\"code\"><pre><div class=\"line\">uninstall_oh_my_zsh</div></pre></td></tr></table></figure></p>\n<h2 id=\"主题\"><a href=\"#主题\" class=\"headerlink\" title=\"主题\"></a>主题</h2><p><a href=\"https://github.com/robbyrussell/oh-my-zsh/wiki/Themes\">这里</a>有上百种主题,总有一款你喜欢的。想要修改主题,需要修改<code>.zshrc</code>文件,这个文件是隐藏的,所以最好在终端中修改,在终端中输入:<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div></pre></td><td class=\"code\"><pre><div class=\"line\">vi ~/.zshrc</div></pre></td></tr></table></figure></p>\n<p>然后会出现:<br> <figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div><div class=\"line\">13</div><div class=\"line\">14</div><div class=\"line\">15</div><div class=\"line\">16</div><div class=\"line\">17</div><div class=\"line\">18</div><div class=\"line\">19</div><div class=\"line\">20</div><div class=\"line\">21</div><div class=\"line\">22</div><div class=\"line\">23</div><div class=\"line\">24</div><div class=\"line\">25</div></pre></td><td class=\"code\"><pre><div class=\"line\"></div><div class=\"line\"># Path to your oh-my-zsh installation.</div><div class=\"line\">export ZSH=/Users/ctt/.oh-my-zsh</div><div class=\"line\"></div><div class=\"line\"># Set name of the theme to load.</div><div class=\"line\"># Look in ~/.oh-my-zsh/themes/</div><div class=\"line\"># Optionally, if you set this to "random", it'll load a random theme each</div><div class=\"line\"># time that oh-my-zsh is loaded.</div><div class=\"line\">ZSH_THEME="robbyrussell"</div><div class=\"line\"></div><div class=\"line\"># Uncomment the following line to use case-sensitive completion.</div><div class=\"line\"># CASE_SENSITIVE="true"</div><div class=\"line\"></div><div class=\"line\"># Uncomment the following line to use hyphen-insensitive completion. Case</div><div class=\"line\"># sensitive completion must be off. _ and - will be interchangeable.</div><div class=\"line\"># HYPHEN_INSENSITIVE="true"</div><div class=\"line\"></div><div class=\"line\"># Uncomment the following line to disable bi-weekly auto-update checks.</div><div class=\"line\"># DISABLE_AUTO_UPDATE="true"</div><div class=\"line\"></div><div class=\"line\"># Uncomment the following line to change how often to auto-update (in days).</div><div class=\"line\"># export UPDATE_ZSH_DAYS=13</div><div class=\"line\"></div><div class=\"line\"># Uncomment the following line to disable colors in ls.</div><div class=\"line\">"~/.zshrc" 84L, 2798C</div></pre></td></tr></table></figure></p>\n<p>把<code>ZSH_THEME="robbyrussell"</code>中的主题改成你想要的名字保存即可,但是必须是<code>.oh-my-zsh/themes</code>中有的。<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div><div class=\"line\">13</div><div class=\"line\">14</div><div class=\"line\">15</div><div class=\"line\">16</div><div class=\"line\">17</div><div class=\"line\">18</div></pre></td><td class=\"code\"><pre><div class=\"line\"></div><div class=\"line\">➜ ~ cd .oh-my-zsh </div><div class=\"line\">➜ .oh-my-zsh git:(master) ls</div><div class=\"line\">MIT-LICENSE.txt custom oh-my-zsh.sh themes</div><div class=\"line\">README.markdown lib plugins tools</div><div class=\"line\">cache log templates</div><div class=\"line\">➜ .oh-my-zsh git:(master) cd themes </div><div class=\"line\">➜ themes git:(master) ls</div><div class=\"line\">3den.zsh-theme kafeitu.zsh-theme</div><div class=\"line\">Soliah.zsh-theme kardan.zsh-theme</div><div class=\"line\">adben.zsh-theme kennethreitz.zsh-theme</div><div class=\"line\">af-magic.zsh-theme kiwi.zsh-theme</div><div class=\"line\">afowler.zsh-theme kolo.zsh-theme</div><div class=\"line\">agnoster.zsh-theme kphoen.zsh-theme</div><div class=\"line\">alanpeabody.zsh-theme lambda.zsh-theme</div><div class=\"line\">amuse.zsh-theme linuxonly.zsh-theme</div><div class=\"line\">apple.zsh-theme lukerandall.zsh-theme</div><div class=\"line\">...</div></pre></td></tr></table></figure></p>\n<h2 id=\"最后\"><a href=\"#最后\" class=\"headerlink\" title=\"最后\"></a>最后</h2><p>愿大家玩的高兴。^_^</p>"},{"layout":"post","title":"使用SKPSMTPMessage发送邮件","date":"2015-08-11T16:00:00.000Z","comments":1,"keywords":"SMTP","publish":true,"description":"使用SKPSMTPMessage发送邮件","_content":"在iOS开发里,可以发送邮件的第三方框架几乎没有,而iOS自带的框架又有诸多的不便,所以今天就来研究一下唯一算是比较好用的`SKPSMTPMessage `。\n<!-- more -->\n\n## SMTP协议\n先来看一下什么是`SMTP`:\n\n`SMTP`(Simple Mail Transfer Protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式。`SMTP`协议属于TCP/IP协议簇,它帮助每台计算机在发送或中转信件时找到下一个目的地。通过`SMTP`协议所指定的服务器,就可以把E-mail寄到收信人的服务器上了,整个过程只要几分钟。`SMTP`服务器则是遵循`SMTP`协议的发送邮件服务器,用来发送或中转发出的电子邮件。\n\t\n简而言之`SMTP`就是邮件发送协议,而`SKPSMTPMessage`则是对协议的实现。\n## SKPSMTPMessage\n[SKPSMTPMessage](https://github.com/jetseven/skpsmtpmessage)是开源的邮件发送框架,由于框架比较老,所以没有使用`ARC`,但这丝毫不影响我们的使用。`SKPSMTPMessage`支持后台发送邮件,支持各种类型附件,功能还是相当强大的,我们可以随意定制UI,不受限制。\n### 如何使用\n\n* 首先是初始化以及邮件发送的基本设置\n\n```\n\tSKPSMTPMessage *testMsg = [[SKPSMTPMessage alloc] init];\n //发送者\n testMsg.fromEmail = @\"passion_wxm@163.com\";\n //发送给\n testMsg.toEmail = @\"413085129@qq.com\";\n //抄送联系人列表,如:@\"664742641@qq.com;1@qq.com;2@q.com;3@qq.com\"\n testMsg.ccEmail = @\"lanyuu@live.cn\";\n //密送联系人列表,如:@\"664742641@qq.com;1@qq.com;2@q.com;3@qq.com\"\n testMsg.bccEmail = @\"664742641@qq.com\";\n //发送有些的发送服务器地址\n testMsg.relayHost = @\"smtp.163.com\";\n //需要鉴权\n testMsg.requiresAuth = YES;\n //发送者的登录账号\n testMsg.login = @\"passion_wxm\";\n //发送者的登录密码\n testMsg.pass = @\"your_password\";\n //邮件主题\n testMsg.subject = [NSString stringWithCString:\"来自iphone socket的测试邮件\" encoding:NSUTF8StringEncoding ];\n testMsg.wantsSecure = YES; // smtp.gmail.com doesn't work without TLS!\n // Only do this for self-signed certs!\n // testMsg.validateSSLChain = NO;\n testMsg.delegate = self;\n```\n\n* 然后我们可以设置主题附件等,这里需要注意的是,由于邮件发送操作受网络影响,比较耗时,所以发送操作要放在异步线程内。\n\n```\n\t//正文\n NSDictionary *plainPart = [NSDictionary dictionaryWithObjectsAndKeys:@\"text/plain\",kSKPSMTPPartContentTypeKey,\n @\"This is a test message.\\r\\n支持中文。\",kSKPSMTPPartMessageKey,@\"8bit\",kSKPSMTPPartContentTransferEncodingKey,nil];\n \n //设置文本附件\n NSData *mailData = [NSData dataWithContentsOfFile:self.mailPath];\n NSDictionary *txtPart = [[NSDictionary alloc ]initWithObjectsAndKeys:@\"text/plain;\\r\\n\\tx-unix-mode=0644;\\r\\n\\tname=\\\"bug.txt\\\"\",kSKPSMTPPartContentTypeKey, @\"attachment;\\r\\n\\tfilename=\\\"bug.txt\\\"\", kSKPSMTPPartContentDispositionKey, [mailData encodeBase64ForData], kSKPSMTPPartMessageKey, @\"base64\", kSKPSMTPPartContentTransferEncodingKey,nil];\n \n //附件图片文件(联系人)\n NSString *vcfPath = [[NSBundle mainBundle] pathForResource:@\"video.jpg\" ofType:@\"\"];\n NSData *vcfData = [NSData dataWithContentsOfFile:vcfPath];\n NSDictionary *vcfPart = [[NSDictionary alloc ]initWithObjectsAndKeys:@\"text/directory;\\r\\n\\tx-unix-mode=0644;\\r\\n\\tname=\\\"video.jpg\\\"\",kSKPSMTPPartContentTypeKey,\n @\"attachment;\\r\\n\\tfilename=\\\"video.jpg\\\"\",kSKPSMTPPartContentDispositionKey,[vcfData encodeBase64ForData],kSKPSMTPPartMessageKey,@\"base64\",kSKPSMTPPartContentTransferEncodingKey,nil];\n //附件音频文件\n NSString *wavPath = [[NSBundle mainBundle] pathForResource:@\"push\" ofType:@\"wav\"];\n NSData *wavData = [NSData dataWithContentsOfFile:wavPath];\n NSDictionary *wavPart = [[NSDictionary alloc ]initWithObjectsAndKeys:@\"text/directory;\\r\\n\\tx-unix-mode=0644;\\r\\n\\tname=\\\"push.wav\\\"\",kSKPSMTPPartContentTypeKey,\n @\"attachment;\\r\\n\\tfilename=\\\"push.wav\\\"\",kSKPSMTPPartContentDispositionKey,[wavData encodeBase64ForData],kSKPSMTPPartMessageKey,@\"base64\",kSKPSMTPPartContentTransferEncodingKey,nil];\n testMsg.parts = [NSArray arrayWithObjects:plainPart,txtPart,vcfPart,wavPart, nil];\n //发送\n dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{\n [mailMsg send];\n });\n```\n* 最后就是一些代理方法了\n\n```\n- (void)messageSent:(SKPSMTPMessage *)message\n{ \n //发送成功\n NSLog(@\"delegate - message sent\");\n}\n\n- (void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error\n{ \n //发送失败 \n NSLog(@\"delegate - error(%d): %@\", [error code], [error localizedDescription]);\n}\n```\n\n### 我遇到的坑\n* 使用上面的写法会出现一个严重的问题,那就是发送等待过程中,APP会crash掉,起初我以为是发送数据量太大,后来发现其实不是这么回事,最后我在`stackoverflow`上面找到了[答案](http://stackoverflow.com/questions/16397120/app-crashes-after-sending-mail-using-smtp),原因是在发送过程中,`SKPSMTPMessage`实例被释放掉,所以导致crash,最好的做法是将`SKPSMTPMessage`实例声明为强引用的属性,这样就没有问题了。\n\n## 最后\n愿大家玩的高兴。^_^\n\n","source":"_posts/2015-08-12-使用SKPSMTPMessage发送邮件.md","raw":"---\nlayout: post\ntitle: \"使用SKPSMTPMessage发送邮件\"\ndate: 2015-08-12\ncomments: true\ncategories: iOS\ntags: [iOS]\nkeywords: SMTP\npublish: true\ndescription: 使用SKPSMTPMessage发送邮件\n---\n在iOS开发里,可以发送邮件的第三方框架几乎没有,而iOS自带的框架又有诸多的不便,所以今天就来研究一下唯一算是比较好用的`SKPSMTPMessage `。\n<!-- more -->\n\n## SMTP协议\n先来看一下什么是`SMTP`:\n\n`SMTP`(Simple Mail Transfer Protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式。`SMTP`协议属于TCP/IP协议簇,它帮助每台计算机在发送或中转信件时找到下一个目的地。通过`SMTP`协议所指定的服务器,就可以把E-mail寄到收信人的服务器上了,整个过程只要几分钟。`SMTP`服务器则是遵循`SMTP`协议的发送邮件服务器,用来发送或中转发出的电子邮件。\n\t\n简而言之`SMTP`就是邮件发送协议,而`SKPSMTPMessage`则是对协议的实现。\n## SKPSMTPMessage\n[SKPSMTPMessage](https://github.com/jetseven/skpsmtpmessage)是开源的邮件发送框架,由于框架比较老,所以没有使用`ARC`,但这丝毫不影响我们的使用。`SKPSMTPMessage`支持后台发送邮件,支持各种类型附件,功能还是相当强大的,我们可以随意定制UI,不受限制。\n### 如何使用\n\n* 首先是初始化以及邮件发送的基本设置\n\n```\n\tSKPSMTPMessage *testMsg = [[SKPSMTPMessage alloc] init];\n //发送者\n testMsg.fromEmail = @\"passion_wxm@163.com\";\n //发送给\n testMsg.toEmail = @\"413085129@qq.com\";\n //抄送联系人列表,如:@\"664742641@qq.com;1@qq.com;2@q.com;3@qq.com\"\n testMsg.ccEmail = @\"lanyuu@live.cn\";\n //密送联系人列表,如:@\"664742641@qq.com;1@qq.com;2@q.com;3@qq.com\"\n testMsg.bccEmail = @\"664742641@qq.com\";\n //发送有些的发送服务器地址\n testMsg.relayHost = @\"smtp.163.com\";\n //需要鉴权\n testMsg.requiresAuth = YES;\n //发送者的登录账号\n testMsg.login = @\"passion_wxm\";\n //发送者的登录密码\n testMsg.pass = @\"your_password\";\n //邮件主题\n testMsg.subject = [NSString stringWithCString:\"来自iphone socket的测试邮件\" encoding:NSUTF8StringEncoding ];\n testMsg.wantsSecure = YES; // smtp.gmail.com doesn't work without TLS!\n // Only do this for self-signed certs!\n // testMsg.validateSSLChain = NO;\n testMsg.delegate = self;\n```\n\n* 然后我们可以设置主题附件等,这里需要注意的是,由于邮件发送操作受网络影响,比较耗时,所以发送操作要放在异步线程内。\n\n```\n\t//正文\n NSDictionary *plainPart = [NSDictionary dictionaryWithObjectsAndKeys:@\"text/plain\",kSKPSMTPPartContentTypeKey,\n @\"This is a test message.\\r\\n支持中文。\",kSKPSMTPPartMessageKey,@\"8bit\",kSKPSMTPPartContentTransferEncodingKey,nil];\n \n //设置文本附件\n NSData *mailData = [NSData dataWithContentsOfFile:self.mailPath];\n NSDictionary *txtPart = [[NSDictionary alloc ]initWithObjectsAndKeys:@\"text/plain;\\r\\n\\tx-unix-mode=0644;\\r\\n\\tname=\\\"bug.txt\\\"\",kSKPSMTPPartContentTypeKey, @\"attachment;\\r\\n\\tfilename=\\\"bug.txt\\\"\", kSKPSMTPPartContentDispositionKey, [mailData encodeBase64ForData], kSKPSMTPPartMessageKey, @\"base64\", kSKPSMTPPartContentTransferEncodingKey,nil];\n \n //附件图片文件(联系人)\n NSString *vcfPath = [[NSBundle mainBundle] pathForResource:@\"video.jpg\" ofType:@\"\"];\n NSData *vcfData = [NSData dataWithContentsOfFile:vcfPath];\n NSDictionary *vcfPart = [[NSDictionary alloc ]initWithObjectsAndKeys:@\"text/directory;\\r\\n\\tx-unix-mode=0644;\\r\\n\\tname=\\\"video.jpg\\\"\",kSKPSMTPPartContentTypeKey,\n @\"attachment;\\r\\n\\tfilename=\\\"video.jpg\\\"\",kSKPSMTPPartContentDispositionKey,[vcfData encodeBase64ForData],kSKPSMTPPartMessageKey,@\"base64\",kSKPSMTPPartContentTransferEncodingKey,nil];\n //附件音频文件\n NSString *wavPath = [[NSBundle mainBundle] pathForResource:@\"push\" ofType:@\"wav\"];\n NSData *wavData = [NSData dataWithContentsOfFile:wavPath];\n NSDictionary *wavPart = [[NSDictionary alloc ]initWithObjectsAndKeys:@\"text/directory;\\r\\n\\tx-unix-mode=0644;\\r\\n\\tname=\\\"push.wav\\\"\",kSKPSMTPPartContentTypeKey,\n @\"attachment;\\r\\n\\tfilename=\\\"push.wav\\\"\",kSKPSMTPPartContentDispositionKey,[wavData encodeBase64ForData],kSKPSMTPPartMessageKey,@\"base64\",kSKPSMTPPartContentTransferEncodingKey,nil];\n testMsg.parts = [NSArray arrayWithObjects:plainPart,txtPart,vcfPart,wavPart, nil];\n //发送\n dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{\n [mailMsg send];\n });\n```\n* 最后就是一些代理方法了\n\n```\n- (void)messageSent:(SKPSMTPMessage *)message\n{ \n //发送成功\n NSLog(@\"delegate - message sent\");\n}\n\n- (void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error\n{ \n //发送失败 \n NSLog(@\"delegate - error(%d): %@\", [error code], [error localizedDescription]);\n}\n```\n\n### 我遇到的坑\n* 使用上面的写法会出现一个严重的问题,那就是发送等待过程中,APP会crash掉,起初我以为是发送数据量太大,后来发现其实不是这么回事,最后我在`stackoverflow`上面找到了[答案](http://stackoverflow.com/questions/16397120/app-crashes-after-sending-mail-using-smtp),原因是在发送过程中,`SKPSMTPMessage`实例被释放掉,所以导致crash,最好的做法是将`SKPSMTPMessage`实例声明为强引用的属性,这样就没有问题了。\n\n## 最后\n愿大家玩的高兴。^_^\n\n","slug":"2015-08-12-使用SKPSMTPMessage发送邮件","published":1,"updated":"2017-03-05T04:17:01.000Z","photos":[],"link":"","_id":"cj0l1ptaq000d0er9i23sim55","content":"<p>在iOS开发里,可以发送邮件的第三方框架几乎没有,而iOS自带的框架又有诸多的不便,所以今天就来研究一下唯一算是比较好用的<code>SKPSMTPMessage</code>。<br><a id=\"more\"></a></p>\n<h2 id=\"SMTP协议\"><a href=\"#SMTP协议\" class=\"headerlink\" title=\"SMTP协议\"></a>SMTP协议</h2><p>先来看一下什么是<code>SMTP</code>:</p>\n<p><code>SMTP</code>(Simple Mail Transfer Protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式。<code>SMTP</code>协议属于TCP/IP协议簇,它帮助每台计算机在发送或中转信件时找到下一个目的地。通过<code>SMTP</code>协议所指定的服务器,就可以把E-mail寄到收信人的服务器上了,整个过程只要几分钟。<code>SMTP</code>服务器则是遵循<code>SMTP</code>协议的发送邮件服务器,用来发送或中转发出的电子邮件。</p>\n<p>简而言之<code>SMTP</code>就是邮件发送协议,而<code>SKPSMTPMessage</code>则是对协议的实现。</p>\n<h2 id=\"SKPSMTPMessage\"><a href=\"#SKPSMTPMessage\" class=\"headerlink\" title=\"SKPSMTPMessage\"></a>SKPSMTPMessage</h2><p><a href=\"https://github.com/jetseven/skpsmtpmessage\" target=\"_blank\" rel=\"external\">SKPSMTPMessage</a>是开源的邮件发送框架,由于框架比较老,所以没有使用<code>ARC</code>,但这丝毫不影响我们的使用。<code>SKPSMTPMessage</code>支持后台发送邮件,支持各种类型附件,功能还是相当强大的,我们可以随意定制UI,不受限制。</p>\n<h3 id=\"如何使用\"><a href=\"#如何使用\" class=\"headerlink\" title=\"如何使用\"></a>如何使用</h3><ul>\n<li>首先是初始化以及邮件发送的基本设置</li>\n</ul>\n<figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div><div class=\"line\">13</div><div class=\"line\">14</div><div class=\"line\">15</div><div class=\"line\">16</div><div class=\"line\">17</div><div class=\"line\">18</div><div class=\"line\">19</div><div class=\"line\">20</div><div class=\"line\">21</div><div class=\"line\">22</div><div class=\"line\">23</div></pre></td><td class=\"code\"><pre><div class=\"line\">SKPSMTPMessage *testMsg = [[SKPSMTPMessage alloc] init];</div><div class=\"line\"> //发送者</div><div class=\"line\"> testMsg.fromEmail = @"passion_wxm@163.com";</div><div class=\"line\"> //发送给</div><div class=\"line\"> testMsg.toEmail = @"413085129@qq.com";</div><div class=\"line\"> //抄送联系人列表,如:@"664742641@qq.com;1@qq.com;2@q.com;3@qq.com"</div><div class=\"line\"> testMsg.ccEmail = @"lanyuu@live.cn";</div><div class=\"line\"> //密送联系人列表,如:@"664742641@qq.com;1@qq.com;2@q.com;3@qq.com"</div><div class=\"line\"> testMsg.bccEmail = @"664742641@qq.com";</div><div class=\"line\"> //发送有些的发送服务器地址</div><div class=\"line\"> testMsg.relayHost = @"smtp.163.com";</div><div class=\"line\"> //需要鉴权</div><div class=\"line\"> testMsg.requiresAuth = YES;</div><div class=\"line\"> //发送者的登录账号</div><div class=\"line\"> testMsg.login = @"passion_wxm";</div><div class=\"line\"> //发送者的登录密码</div><div class=\"line\"> testMsg.pass = @"your_password";</div><div class=\"line\"> //邮件主题</div><div class=\"line\"> testMsg.subject = [NSString stringWithCString:"来自iphone socket的测试邮件" encoding:NSUTF8StringEncoding ];</div><div class=\"line\"> testMsg.wantsSecure = YES; // smtp.gmail.com doesn't work without TLS!</div><div class=\"line\"> // Only do this for self-signed certs!</div><div class=\"line\"> // testMsg.validateSSLChain = NO;</div><div class=\"line\"> testMsg.delegate = self;</div></pre></td></tr></table></figure>\n<ul>\n<li>然后我们可以设置主题附件等,这里需要注意的是,由于邮件发送操作受网络影响,比较耗时,所以发送操作要放在异步线程内。</li>\n</ul>\n<figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div><div class=\"line\">13</div><div class=\"line\">14</div><div class=\"line\">15</div><div class=\"line\">16</div><div class=\"line\">17</div><div class=\"line\">18</div><div class=\"line\">19</div><div class=\"line\">20</div><div class=\"line\">21</div><div class=\"line\">22</div><div class=\"line\">23</div></pre></td><td class=\"code\"><pre><div class=\"line\">//正文</div><div class=\"line\"> NSDictionary *plainPart = [NSDictionary dictionaryWithObjectsAndKeys:@"text/plain",kSKPSMTPPartContentTypeKey,</div><div class=\"line\"> @"This is a test message.\\r\\n支持中文。",kSKPSMTPPartMessageKey,@"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];</div><div class=\"line\"> </div><div class=\"line\"> //设置文本附件</div><div class=\"line\"> NSData *mailData = [NSData dataWithContentsOfFile:self.mailPath];</div><div class=\"line\"> NSDictionary *txtPart = [[NSDictionary alloc ]initWithObjectsAndKeys:@"text/plain;\\r\\n\\tx-unix-mode=0644;\\r\\n\\tname=\\"bug.txt\\"",kSKPSMTPPartContentTypeKey, @"attachment;\\r\\n\\tfilename=\\"bug.txt\\"", kSKPSMTPPartContentDispositionKey, [mailData encodeBase64ForData], kSKPSMTPPartMessageKey, @"base64", kSKPSMTPPartContentTransferEncodingKey,nil];</div><div class=\"line\"> </div><div class=\"line\"> //附件图片文件(联系人)</div><div class=\"line\"> NSString *vcfPath = [[NSBundle mainBundle] pathForResource:@"video.jpg" ofType:@""];</div><div class=\"line\"> NSData *vcfData = [NSData dataWithContentsOfFile:vcfPath];</div><div class=\"line\"> NSDictionary *vcfPart = [[NSDictionary alloc ]initWithObjectsAndKeys:@"text/directory;\\r\\n\\tx-unix-mode=0644;\\r\\n\\tname=\\"video.jpg\\"",kSKPSMTPPartContentTypeKey,</div><div class=\"line\"> @"attachment;\\r\\n\\tfilename=\\"video.jpg\\"",kSKPSMTPPartContentDispositionKey,[vcfData encodeBase64ForData],kSKPSMTPPartMessageKey,@"base64",kSKPSMTPPartContentTransferEncodingKey,nil];</div><div class=\"line\"> //附件音频文件</div><div class=\"line\"> NSString *wavPath = [[NSBundle mainBundle] pathForResource:@"push" ofType:@"wav"];</div><div class=\"line\"> NSData *wavData = [NSData dataWithContentsOfFile:wavPath];</div><div class=\"line\"> NSDictionary *wavPart = [[NSDictionary alloc ]initWithObjectsAndKeys:@"text/directory;\\r\\n\\tx-unix-mode=0644;\\r\\n\\tname=\\"push.wav\\"",kSKPSMTPPartContentTypeKey,</div><div class=\"line\"> @"attachment;\\r\\n\\tfilename=\\"push.wav\\"",kSKPSMTPPartContentDispositionKey,[wavData encodeBase64ForData],kSKPSMTPPartMessageKey,@"base64",kSKPSMTPPartContentTransferEncodingKey,nil];</div><div class=\"line\"> testMsg.parts = [NSArray arrayWithObjects:plainPart,txtPart,vcfPart,wavPart, nil];</div><div class=\"line\"> //发送</div><div class=\"line\"> dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{</div><div class=\"line\"> [mailMsg send];</div><div class=\"line\"> });</div></pre></td></tr></table></figure>\n<ul>\n<li>最后就是一些代理方法了</li>\n</ul>\n<figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div></pre></td><td class=\"code\"><pre><div class=\"line\">- (void)messageSent:(SKPSMTPMessage *)message</div><div class=\"line\">{ </div><div class=\"line\"> //发送成功</div><div class=\"line\"> NSLog(@"delegate - message sent");</div><div class=\"line\">}</div><div class=\"line\"></div><div class=\"line\">- (void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error</div><div class=\"line\">{ </div><div class=\"line\"> //发送失败 </div><div class=\"line\"> NSLog(@"delegate - error(%d): %@", [error code], [error localizedDescription]);</div><div class=\"line\">}</div></pre></td></tr></table></figure>\n<h3 id=\"我遇到的坑\"><a href=\"#我遇到的坑\" class=\"headerlink\" title=\"我遇到的坑\"></a>我遇到的坑</h3><ul>\n<li>使用上面的写法会出现一个严重的问题,那就是发送等待过程中,APP会crash掉,起初我以为是发送数据量太大,后来发现其实不是这么回事,最后我在<code>stackoverflow</code>上面找到了<a href=\"http://stackoverflow.com/questions/16397120/app-crashes-after-sending-mail-using-smtp\" target=\"_blank\" rel=\"external\">答案</a>,原因是在发送过程中,<code>SKPSMTPMessage</code>实例被释放掉,所以导致crash,最好的做法是将<code>SKPSMTPMessage</code>实例声明为强引用的属性,这样就没有问题了。</li>\n</ul>\n<h2 id=\"最后\"><a href=\"#最后\" class=\"headerlink\" title=\"最后\"></a>最后</h2><p>愿大家玩的高兴。^_^</p>\n","excerpt":"<p>在iOS开发里,可以发送邮件的第三方框架几乎没有,而iOS自带的框架又有诸多的不便,所以今天就来研究一下唯一算是比较好用的<code>SKPSMTPMessage</code>。<br>","more":"</p>\n<h2 id=\"SMTP协议\"><a href=\"#SMTP协议\" class=\"headerlink\" title=\"SMTP协议\"></a>SMTP协议</h2><p>先来看一下什么是<code>SMTP</code>:</p>\n<p><code>SMTP</code>(Simple Mail Transfer Protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式。<code>SMTP</code>协议属于TCP/IP协议簇,它帮助每台计算机在发送或中转信件时找到下一个目的地。通过<code>SMTP</code>协议所指定的服务器,就可以把E-mail寄到收信人的服务器上了,整个过程只要几分钟。<code>SMTP</code>服务器则是遵循<code>SMTP</code>协议的发送邮件服务器,用来发送或中转发出的电子邮件。</p>\n<p>简而言之<code>SMTP</code>就是邮件发送协议,而<code>SKPSMTPMessage</code>则是对协议的实现。</p>\n<h2 id=\"SKPSMTPMessage\"><a href=\"#SKPSMTPMessage\" class=\"headerlink\" title=\"SKPSMTPMessage\"></a>SKPSMTPMessage</h2><p><a href=\"https://github.com/jetseven/skpsmtpmessage\">SKPSMTPMessage</a>是开源的邮件发送框架,由于框架比较老,所以没有使用<code>ARC</code>,但这丝毫不影响我们的使用。<code>SKPSMTPMessage</code>支持后台发送邮件,支持各种类型附件,功能还是相当强大的,我们可以随意定制UI,不受限制。</p>\n<h3 id=\"如何使用\"><a href=\"#如何使用\" class=\"headerlink\" title=\"如何使用\"></a>如何使用</h3><ul>\n<li>首先是初始化以及邮件发送的基本设置</li>\n</ul>\n<figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div><div class=\"line\">13</div><div class=\"line\">14</div><div class=\"line\">15</div><div class=\"line\">16</div><div class=\"line\">17</div><div class=\"line\">18</div><div class=\"line\">19</div><div class=\"line\">20</div><div class=\"line\">21</div><div class=\"line\">22</div><div class=\"line\">23</div></pre></td><td class=\"code\"><pre><div class=\"line\">SKPSMTPMessage *testMsg = [[SKPSMTPMessage alloc] init];</div><div class=\"line\"> //发送者</div><div class=\"line\"> testMsg.fromEmail = @"passion_wxm@163.com";</div><div class=\"line\"> //发送给</div><div class=\"line\"> testMsg.toEmail = @"413085129@qq.com";</div><div class=\"line\"> //抄送联系人列表,如:@"664742641@qq.com;1@qq.com;2@q.com;3@qq.com"</div><div class=\"line\"> testMsg.ccEmail = @"lanyuu@live.cn";</div><div class=\"line\"> //密送联系人列表,如:@"664742641@qq.com;1@qq.com;2@q.com;3@qq.com"</div><div class=\"line\"> testMsg.bccEmail = @"664742641@qq.com";</div><div class=\"line\"> //发送有些的发送服务器地址</div><div class=\"line\"> testMsg.relayHost = @"smtp.163.com";</div><div class=\"line\"> //需要鉴权</div><div class=\"line\"> testMsg.requiresAuth = YES;</div><div class=\"line\"> //发送者的登录账号</div><div class=\"line\"> testMsg.login = @"passion_wxm";</div><div class=\"line\"> //发送者的登录密码</div><div class=\"line\"> testMsg.pass = @"your_password";</div><div class=\"line\"> //邮件主题</div><div class=\"line\"> testMsg.subject = [NSString stringWithCString:"来自iphone socket的测试邮件" encoding:NSUTF8StringEncoding ];</div><div class=\"line\"> testMsg.wantsSecure = YES; // smtp.gmail.com doesn't work without TLS!</div><div class=\"line\"> // Only do this for self-signed certs!</div><div class=\"line\"> // testMsg.validateSSLChain = NO;</div><div class=\"line\"> testMsg.delegate = self;</div></pre></td></tr></table></figure>\n<ul>\n<li>然后我们可以设置主题附件等,这里需要注意的是,由于邮件发送操作受网络影响,比较耗时,所以发送操作要放在异步线程内。</li>\n</ul>\n<figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div><div class=\"line\">13</div><div class=\"line\">14</div><div class=\"line\">15</div><div class=\"line\">16</div><div class=\"line\">17</div><div class=\"line\">18</div><div class=\"line\">19</div><div class=\"line\">20</div><div class=\"line\">21</div><div class=\"line\">22</div><div class=\"line\">23</div></pre></td><td class=\"code\"><pre><div class=\"line\">//正文</div><div class=\"line\"> NSDictionary *plainPart = [NSDictionary dictionaryWithObjectsAndKeys:@"text/plain",kSKPSMTPPartContentTypeKey,</div><div class=\"line\"> @"This is a test message.\\r\\n支持中文。",kSKPSMTPPartMessageKey,@"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];</div><div class=\"line\"> </div><div class=\"line\"> //设置文本附件</div><div class=\"line\"> NSData *mailData = [NSData dataWithContentsOfFile:self.mailPath];</div><div class=\"line\"> NSDictionary *txtPart = [[NSDictionary alloc ]initWithObjectsAndKeys:@"text/plain;\\r\\n\\tx-unix-mode=0644;\\r\\n\\tname=\\"bug.txt\\"",kSKPSMTPPartContentTypeKey, @"attachment;\\r\\n\\tfilename=\\"bug.txt\\"", kSKPSMTPPartContentDispositionKey, [mailData encodeBase64ForData], kSKPSMTPPartMessageKey, @"base64", kSKPSMTPPartContentTransferEncodingKey,nil];</div><div class=\"line\"> </div><div class=\"line\"> //附件图片文件(联系人)</div><div class=\"line\"> NSString *vcfPath = [[NSBundle mainBundle] pathForResource:@"video.jpg" ofType:@""];</div><div class=\"line\"> NSData *vcfData = [NSData dataWithContentsOfFile:vcfPath];</div><div class=\"line\"> NSDictionary *vcfPart = [[NSDictionary alloc ]initWithObjectsAndKeys:@"text/directory;\\r\\n\\tx-unix-mode=0644;\\r\\n\\tname=\\"video.jpg\\"",kSKPSMTPPartContentTypeKey,</div><div class=\"line\"> @"attachment;\\r\\n\\tfilename=\\"video.jpg\\"",kSKPSMTPPartContentDispositionKey,[vcfData encodeBase64ForData],kSKPSMTPPartMessageKey,@"base64",kSKPSMTPPartContentTransferEncodingKey,nil];</div><div class=\"line\"> //附件音频文件</div><div class=\"line\"> NSString *wavPath = [[NSBundle mainBundle] pathForResource:@"push" ofType:@"wav"];</div><div class=\"line\"> NSData *wavData = [NSData dataWithContentsOfFile:wavPath];</div><div class=\"line\"> NSDictionary *wavPart = [[NSDictionary alloc ]initWithObjectsAndKeys:@"text/directory;\\r\\n\\tx-unix-mode=0644;\\r\\n\\tname=\\"push.wav\\"",kSKPSMTPPartContentTypeKey,</div><div class=\"line\"> @"attachment;\\r\\n\\tfilename=\\"push.wav\\"",kSKPSMTPPartContentDispositionKey,[wavData encodeBase64ForData],kSKPSMTPPartMessageKey,@"base64",kSKPSMTPPartContentTransferEncodingKey,nil];</div><div class=\"line\"> testMsg.parts = [NSArray arrayWithObjects:plainPart,txtPart,vcfPart,wavPart, nil];</div><div class=\"line\"> //发送</div><div class=\"line\"> dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{</div><div class=\"line\"> [mailMsg send];</div><div class=\"line\"> });</div></pre></td></tr></table></figure>\n<ul>\n<li>最后就是一些代理方法了</li>\n</ul>\n<figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div></pre></td><td class=\"code\"><pre><div class=\"line\">- (void)messageSent:(SKPSMTPMessage *)message</div><div class=\"line\">{ </div><div class=\"line\"> //发送成功</div><div class=\"line\"> NSLog(@"delegate - message sent");</div><div class=\"line\">}</div><div class=\"line\"></div><div class=\"line\">- (void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error</div><div class=\"line\">{ </div><div class=\"line\"> //发送失败 </div><div class=\"line\"> NSLog(@"delegate - error(%d): %@", [error code], [error localizedDescription]);</div><div class=\"line\">}</div></pre></td></tr></table></figure>\n<h3 id=\"我遇到的坑\"><a href=\"#我遇到的坑\" class=\"headerlink\" title=\"我遇到的坑\"></a>我遇到的坑</h3><ul>\n<li>使用上面的写法会出现一个严重的问题,那就是发送等待过程中,APP会crash掉,起初我以为是发送数据量太大,后来发现其实不是这么回事,最后我在<code>stackoverflow</code>上面找到了<a href=\"http://stackoverflow.com/questions/16397120/app-crashes-after-sending-mail-using-smtp\">答案</a>,原因是在发送过程中,<code>SKPSMTPMessage</code>实例被释放掉,所以导致crash,最好的做法是将<code>SKPSMTPMessage</code>实例声明为强引用的属性,这样就没有问题了。</li>\n</ul>\n<h2 id=\"最后\"><a href=\"#最后\" class=\"headerlink\" title=\"最后\"></a>最后</h2><p>愿大家玩的高兴。^_^</p>"},{"layout":"post","title":"UITableView的分割线","date":"2015-08-25T16:00:00.000Z","comments":1,"keywords":"Cell的分割线","publish":true,"description":"UITableView的分割线","_content":"在iOS7与iOS8中的UITableView的分割线的一些设置问题。\n<!-- more -->\n\n## 首先\n在iOS中UITableView的分割线默认是左边距离边距15像素,但是有时我们需要它左对齐。\n这是正常的分割线:\n\n\n\n我们的需求:\n\n\n## Do It\n\n### 在iOS7\n\n在iOS7上,我们有多种方式来解决这个问题。\n\n* 使用代码的方式\n\t\n\t```\n\tself.tableView.separatorInset = UIEdgeInsetsZero;\n\t```\n\t\n* 如果使用了xib或者是SB\n\n\n\n* 或者直接把分割线样式设置为`UITableViewCellSeparatorStyleNone`,然后自己在`cell`的底部添加一个高度为`1`的`UIView`\n\n### 在iOS8\n不幸的是在iOS8上,上述的两种方法都不行,为什么呢?其实是`layoutMargins`这个属性在作怪,这是iOS8新添加的一个属性,下面是官方的介绍:\n\n\n\n那么,我们就需要使用下面这段代码了:\n```\n-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath\n{\n \n if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {\n \t[tableView setSeparatorInset:UIEdgeInsetsZero];\n }\n \n if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {\n \t [tableView setLayoutMargins:UIEdgeInsetsZero];\n \t}\n \n if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {\n \t[cell setLayoutMargins:UIEdgeInsetsZero];\n \t}\n}\n```\n\n`layoutMargins`在子控件与父控件布局中起了决定性的作用。\n\n但是这一段代码会在每个cell绘制时候频繁调用,这也就意味着性能的下降,所以还有一种方法来实现:\n\n self.tableView.separatorInset = UIEdgeInsetsZero;\n self.tableView.layoutMargins = UIEdgeInsetsZero;\n## 最后\n愿大家玩的高兴。^_^\n\n","source":"_posts/2015-08-26-UITableView的分割线.md","raw":"---\nlayout: post\ntitle: \"UITableView的分割线\"\ndate: 2015-08-26\ncomments: true\ncategories: iOS\ntags: [iOS]\nkeywords: Cell的分割线\npublish: true\ndescription: UITableView的分割线\n---\n在iOS7与iOS8中的UITableView的分割线的一些设置问题。\n<!-- more -->\n\n## 首先\n在iOS中UITableView的分割线默认是左边距离边距15像素,但是有时我们需要它左对齐。\n这是正常的分割线:\n\n\n\n我们的需求:\n\n\n## Do It\n\n### 在iOS7\n\n在iOS7上,我们有多种方式来解决这个问题。\n\n* 使用代码的方式\n\t\n\t```\n\tself.tableView.separatorInset = UIEdgeInsetsZero;\n\t```\n\t\n* 如果使用了xib或者是SB\n\n\n\n* 或者直接把分割线样式设置为`UITableViewCellSeparatorStyleNone`,然后自己在`cell`的底部添加一个高度为`1`的`UIView`\n\n### 在iOS8\n不幸的是在iOS8上,上述的两种方法都不行,为什么呢?其实是`layoutMargins`这个属性在作怪,这是iOS8新添加的一个属性,下面是官方的介绍:\n\n\n\n那么,我们就需要使用下面这段代码了:\n```\n-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath\n{\n \n if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {\n \t[tableView setSeparatorInset:UIEdgeInsetsZero];\n }\n \n if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {\n \t [tableView setLayoutMargins:UIEdgeInsetsZero];\n \t}\n \n if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {\n \t[cell setLayoutMargins:UIEdgeInsetsZero];\n \t}\n}\n```\n\n`layoutMargins`在子控件与父控件布局中起了决定性的作用。\n\n但是这一段代码会在每个cell绘制时候频繁调用,这也就意味着性能的下降,所以还有一种方法来实现:\n\n self.tableView.separatorInset = UIEdgeInsetsZero;\n self.tableView.layoutMargins = UIEdgeInsetsZero;\n## 最后\n愿大家玩的高兴。^_^\n\n","slug":"2015-08-26-UITableView的分割线","published":1,"updated":"2017-03-05T04:16:44.000Z","photos":[],"link":"","_id":"cj0l1ptau000h0er988xdu1g0","content":"<p>在iOS7与iOS8中的UITableView的分割线的一些设置问题。<br><a id=\"more\"></a></p>\n<h2 id=\"首先\"><a href=\"#首先\" class=\"headerlink\" title=\"首先\"></a>首先</h2><p>在iOS中UITableView的分割线默认是左边距离边距15像素,但是有时我们需要它左对齐。<br>这是正常的分割线:</p>\n<p><img src=\"http://img17.poco.cn/mypoco/myphoto/20150826/20/17832875620150826201621072.png?375x689_130\" alt=\"正常\"></p>\n<p>我们的需求:</p>\n<p><img src=\"http://img17.poco.cn/mypoco/myphoto/20150826/20/17832875620150826201715025.png?375x689_130\" alt=\"需求\"></p>\n<h2 id=\"Do-It\"><a href=\"#Do-It\" class=\"headerlink\" title=\"Do It\"></a>Do It</h2><h3 id=\"在iOS7\"><a href=\"#在iOS7\" class=\"headerlink\" title=\"在iOS7\"></a>在iOS7</h3><p>在iOS7上,我们有多种方式来解决这个问题。</p>\n<ul>\n<li><p>使用代码的方式</p>\n <figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div></pre></td><td class=\"code\"><pre><div class=\"line\">self.tableView.separatorInset = UIEdgeInsetsZero;</div></pre></td></tr></table></figure>\n</li>\n</ul>\n<ul>\n<li>如果使用了xib或者是SB</li>\n</ul>\n<p><img src=\"http://img17.poco.cn/mypoco/myphoto/20150826/20/17832875620150826202654013.png?239x59_130\" alt=\"xib-sb\"></p>\n<ul>\n<li>或者直接把分割线样式设置为<code>UITableViewCellSeparatorStyleNone</code>,然后自己在<code>cell</code>的底部添加一个高度为<code>1</code>的<code>UIView</code></li>\n</ul>\n<h3 id=\"在iOS8\"><a href=\"#在iOS8\" class=\"headerlink\" title=\"在iOS8\"></a>在iOS8</h3><p>不幸的是在iOS8上,上述的两种方法都不行,为什么呢?其实是<code>layoutMargins</code>这个属性在作怪,这是iOS8新添加的一个属性,下面是官方的介绍:</p>\n<p><img src=\"http://img17.poco.cn/mypoco/myphoto/20150826/20/17832875620150826203706040.png?710x429_130\" alt=\"layoutMargins\"></p>\n<p>那么,我们就需要使用下面这段代码了:<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div><div class=\"line\">13</div><div class=\"line\">14</div><div class=\"line\">15</div></pre></td><td class=\"code\"><pre><div class=\"line\">-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath</div><div class=\"line\">{</div><div class=\"line\"> </div><div class=\"line\"> if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {</div><div class=\"line\"> \t[tableView setSeparatorInset:UIEdgeInsetsZero];</div><div class=\"line\"> }</div><div class=\"line\"> </div><div class=\"line\"> if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {</div><div class=\"line\"> \t [tableView setLayoutMargins:UIEdgeInsetsZero];</div><div class=\"line\"> \t}</div><div class=\"line\"> </div><div class=\"line\"> if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {</div><div class=\"line\"> \t[cell setLayoutMargins:UIEdgeInsetsZero];</div><div class=\"line\"> \t}</div><div class=\"line\">}</div></pre></td></tr></table></figure></p>\n<p><code>layoutMargins</code>在子控件与父控件布局中起了决定性的作用。</p>\n<p>但是这一段代码会在每个cell绘制时候频繁调用,这也就意味着性能的下降,所以还有一种方法来实现:</p>\n<pre><code>self.tableView.separatorInset = UIEdgeInsetsZero;\nself.tableView.layoutMargins = UIEdgeInsetsZero;\n</code></pre><h2 id=\"最后\"><a href=\"#最后\" class=\"headerlink\" title=\"最后\"></a>最后</h2><p>愿大家玩的高兴。^_^</p>\n","excerpt":"<p>在iOS7与iOS8中的UITableView的分割线的一些设置问题。<br>","more":"</p>\n<h2 id=\"首先\"><a href=\"#首先\" class=\"headerlink\" title=\"首先\"></a>首先</h2><p>在iOS中UITableView的分割线默认是左边距离边距15像素,但是有时我们需要它左对齐。<br>这是正常的分割线:</p>\n<p><img src=\"http://img17.poco.cn/mypoco/myphoto/20150826/20/17832875620150826201621072.png?375x689_130\" alt=\"正常\"></p>\n<p>我们的需求:</p>\n<p><img src=\"http://img17.poco.cn/mypoco/myphoto/20150826/20/17832875620150826201715025.png?375x689_130\" alt=\"需求\"></p>\n<h2 id=\"Do-It\"><a href=\"#Do-It\" class=\"headerlink\" title=\"Do It\"></a>Do It</h2><h3 id=\"在iOS7\"><a href=\"#在iOS7\" class=\"headerlink\" title=\"在iOS7\"></a>在iOS7</h3><p>在iOS7上,我们有多种方式来解决这个问题。</p>\n<ul>\n<li><p>使用代码的方式</p>\n <figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div></pre></td><td class=\"code\"><pre><div class=\"line\">self.tableView.separatorInset = UIEdgeInsetsZero;</div></pre></td></tr></table></figure>\n</li>\n</ul>\n<ul>\n<li>如果使用了xib或者是SB</li>\n</ul>\n<p><img src=\"http://img17.poco.cn/mypoco/myphoto/20150826/20/17832875620150826202654013.png?239x59_130\" alt=\"xib-sb\"></p>\n<ul>\n<li>或者直接把分割线样式设置为<code>UITableViewCellSeparatorStyleNone</code>,然后自己在<code>cell</code>的底部添加一个高度为<code>1</code>的<code>UIView</code></li>\n</ul>\n<h3 id=\"在iOS8\"><a href=\"#在iOS8\" class=\"headerlink\" title=\"在iOS8\"></a>在iOS8</h3><p>不幸的是在iOS8上,上述的两种方法都不行,为什么呢?其实是<code>layoutMargins</code>这个属性在作怪,这是iOS8新添加的一个属性,下面是官方的介绍:</p>\n<p><img src=\"http://img17.poco.cn/mypoco/myphoto/20150826/20/17832875620150826203706040.png?710x429_130\" alt=\"layoutMargins\"></p>\n<p>那么,我们就需要使用下面这段代码了:<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div><div class=\"line\">13</div><div class=\"line\">14</div><div class=\"line\">15</div></pre></td><td class=\"code\"><pre><div class=\"line\">-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath</div><div class=\"line\">{</div><div class=\"line\"> </div><div class=\"line\"> if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {</div><div class=\"line\"> \t[tableView setSeparatorInset:UIEdgeInsetsZero];</div><div class=\"line\"> }</div><div class=\"line\"> </div><div class=\"line\"> if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {</div><div class=\"line\"> \t [tableView setLayoutMargins:UIEdgeInsetsZero];</div><div class=\"line\"> \t}</div><div class=\"line\"> </div><div class=\"line\"> if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {</div><div class=\"line\"> \t[cell setLayoutMargins:UIEdgeInsetsZero];</div><div class=\"line\"> \t}</div><div class=\"line\">}</div></pre></td></tr></table></figure></p>\n<p><code>layoutMargins</code>在子控件与父控件布局中起了决定性的作用。</p>\n<p>但是这一段代码会在每个cell绘制时候频繁调用,这也就意味着性能的下降,所以还有一种方法来实现:</p>\n<pre><code>self.tableView.separatorInset = UIEdgeInsetsZero;\nself.tableView.layoutMargins = UIEdgeInsetsZero;\n</code></pre><h2 id=\"最后\"><a href=\"#最后\" class=\"headerlink\" title=\"最后\"></a>最后</h2><p>愿大家玩的高兴。^_^</p>"},{"layout":"post","title":"快速了解JavaScript中的函数","date":"2017-01-22T16:00:00.000Z","comments":1,"keywords":"快速了解JavaScript中的函数","publish":true,"description":"快速了解JavaScript中的函数","_content":"最近在学习前端知识,顺手把一些东西记录下来,加深记忆,忘记的时候翻阅一下,温故而知新。\n<!-- more -->\n\n## 快速了解JavaScript中的函数\n### 1.普通函数\n\n#### 1.1 普通函数示例\n```\nfunction sayHello() {\n\tconsole.log(\"hello\");\n}\nconsole.log(\"------------------------------------------------\");\n```\n\n#### 1.2 同名函数覆盖,\nJS中没有函数重载,定义相同的函数名,不同参数的函数。 调用时,后面的函数会覆盖前面的函数。\n\n```\nfunction add(value1) {\n\treturn value1 + 1;\n}\n\t\nfunction add(value1, value2) {\n\treturn value1 + 2;\n}\nconsole.log(add(2)); //4\nconsole.log(\"------------------------------------------------\");\n```\n\n#### 1.3 arguments对象 \n 传入参数大于定义参数时,arguments对象存放了函数调用时的所有参数\n```\nfunction showNames(name) {\n\tconsole.log(name);\n\tfor (var i = 0; i < arguments.length; i++) {\n\t\tconsole.log(arguments[i]);\n\t} \n}\nshowNames(\"🍎\", \"🍐\", \"🍑\"); //🍎🍎🍐🍑\nconsole.log(\"------------------------------------------------\");\n```\n\n#### 1.4 “undefined”\n若函数没有指明返回值,默认返回的是“undefined”\n```\nfunction showUndefined() {\n\t\n}\nconsole.log(showUndefined());\nconsole.log(\"------------------------------------------------\");\n```\n\n### 2.匿名函数\n#### 2.1 变量匿名函数 \n可以把函数赋值给变量,事件。\n```\nvar add = function (num1, num2) {\n\tconsole.log(num1 + num2);\n}\n\t\nadd(1, 1);\nconsole.log(\"------------------------------------------------\");\n```\n\n#### 2.2 无名称匿名函数 \n即在函数声明时,在后面紧跟参数。JS解析语法时立即执行该函数。\n```\n(function(arg) {\n\tconsole.log(\"无名称匿名函数\" + arg);\n})(33);\nconsole.log(\"------------------------------------------------\");\n```\n适用场景,只需执行一次的。如浏览器加载完,只需要执行一次且后面不执行的功能。\n\n### 3.闭包函数\n * 函数A内部声明了个函数B,函数B引用了函数B之外的变量,并且函数A的返回值是函数B的引用,那么函数B就是闭包函数。\n\n#### 3.1 全局引用与局部引用\n```\nfunction funA() {\n\tvar i = 0;\n\tfunction funB() { // 闭包函数funB\n\t\ti++;\n\t\tconsole.log(i);\n\t}\n\treturn funB();\n}\n// allShowA是全局变量,引用了函数funA,重复运行allShowA(),输出1,2,3,4等累加值。\nvar allShowA = funA(); \n\n// 执行函数partShowA(),因为内部只声明了局部变量showA来引用函数funA,函数执行完由于作用域,showA变量就被释放了。\nfunction partShowA() {\n\tvar showA = funA();\n\tshowA();\n}\n// 闭包的关键就在于作用域:全局变量占有的资源只有当页面变换或浏览器关闭后才会释放。var allShowA = funA()时,相当于allShowA引用了funB(),从而使funB()里的资源不被GC回收,因此funA()里的资源也不会。\nconsole.log(\"------------------------------------------------\");\n```\n\n#### 3.2 有参数的闭包函数\n```\n function funA(arg1, arg2) {\n \tvar i = 0;\n \tfunction funB(num) {\n \t\ti = i + num;\n \t\tconsole.log(i);\n \t}\n \treturn funB;\n }\n\t\n var allShowA = funA(3, 4);\n allShowA(1); // 1\n allShowA(2); // 3\n allShowA(3); // 6\n\t\n function partShowA(arg) {\n\tvar showA = funA(3, 4);\n\tshowA(arg);\n}\npartShowA(1); // 1\npartShowA(2); // 2\npartShowA(3); // 3\nconsole.log(\"------------------------------------------------\");\n```\n#### 3.3 函数内变量共享\n```\nfunction funA1() {\n\tvar i = 0;\n\tfunction funB() {\n\t\ti++;\n\t\tconsole.log(i);\n\t}\n\tallShowC = function(){\n\t\ti++;\n\t\tconsole.log(i);\n\t}\n\treturn funB();\n}\nvar allShow1 = funA1();\nvar allShow2 = funA1();\nconsole.log(\"------------------------------------------------\");\n```\n\n#### 参考\n[JavaScript function函数种类](http://www.cnblogs.com/polk6/p/3284839.html)\n\n\n","source":"_posts/2017-01-23-快速了解JavaScript中的函数.md","raw":"---\nlayout: post\ntitle: \"快速了解JavaScript中的函数\"\ndate: 2017-01-23\ncomments: true\ncategories: JavaScript\ntags: [随笔]\nkeywords: 快速了解JavaScript中的函数\npublish: true\ndescription: 快速了解JavaScript中的函数\n---\n最近在学习前端知识,顺手把一些东西记录下来,加深记忆,忘记的时候翻阅一下,温故而知新。\n<!-- more -->\n\n## 快速了解JavaScript中的函数\n### 1.普通函数\n\n#### 1.1 普通函数示例\n```\nfunction sayHello() {\n\tconsole.log(\"hello\");\n}\nconsole.log(\"------------------------------------------------\");\n```\n\n#### 1.2 同名函数覆盖,\nJS中没有函数重载,定义相同的函数名,不同参数的函数。 调用时,后面的函数会覆盖前面的函数。\n\n```\nfunction add(value1) {\n\treturn value1 + 1;\n}\n\t\nfunction add(value1, value2) {\n\treturn value1 + 2;\n}\nconsole.log(add(2)); //4\nconsole.log(\"------------------------------------------------\");\n```\n\n#### 1.3 arguments对象 \n 传入参数大于定义参数时,arguments对象存放了函数调用时的所有参数\n```\nfunction showNames(name) {\n\tconsole.log(name);\n\tfor (var i = 0; i < arguments.length; i++) {\n\t\tconsole.log(arguments[i]);\n\t} \n}\nshowNames(\"🍎\", \"🍐\", \"🍑\"); //🍎🍎🍐🍑\nconsole.log(\"------------------------------------------------\");\n```\n\n#### 1.4 “undefined”\n若函数没有指明返回值,默认返回的是“undefined”\n```\nfunction showUndefined() {\n\t\n}\nconsole.log(showUndefined());\nconsole.log(\"------------------------------------------------\");\n```\n\n### 2.匿名函数\n#### 2.1 变量匿名函数 \n可以把函数赋值给变量,事件。\n```\nvar add = function (num1, num2) {\n\tconsole.log(num1 + num2);\n}\n\t\nadd(1, 1);\nconsole.log(\"------------------------------------------------\");\n```\n\n#### 2.2 无名称匿名函数 \n即在函数声明时,在后面紧跟参数。JS解析语法时立即执行该函数。\n```\n(function(arg) {\n\tconsole.log(\"无名称匿名函数\" + arg);\n})(33);\nconsole.log(\"------------------------------------------------\");\n```\n适用场景,只需执行一次的。如浏览器加载完,只需要执行一次且后面不执行的功能。\n\n### 3.闭包函数\n * 函数A内部声明了个函数B,函数B引用了函数B之外的变量,并且函数A的返回值是函数B的引用,那么函数B就是闭包函数。\n\n#### 3.1 全局引用与局部引用\n```\nfunction funA() {\n\tvar i = 0;\n\tfunction funB() { // 闭包函数funB\n\t\ti++;\n\t\tconsole.log(i);\n\t}\n\treturn funB();\n}\n// allShowA是全局变量,引用了函数funA,重复运行allShowA(),输出1,2,3,4等累加值。\nvar allShowA = funA(); \n\n// 执行函数partShowA(),因为内部只声明了局部变量showA来引用函数funA,函数执行完由于作用域,showA变量就被释放了。\nfunction partShowA() {\n\tvar showA = funA();\n\tshowA();\n}\n// 闭包的关键就在于作用域:全局变量占有的资源只有当页面变换或浏览器关闭后才会释放。var allShowA = funA()时,相当于allShowA引用了funB(),从而使funB()里的资源不被GC回收,因此funA()里的资源也不会。\nconsole.log(\"------------------------------------------------\");\n```\n\n#### 3.2 有参数的闭包函数\n```\n function funA(arg1, arg2) {\n \tvar i = 0;\n \tfunction funB(num) {\n \t\ti = i + num;\n \t\tconsole.log(i);\n \t}\n \treturn funB;\n }\n\t\n var allShowA = funA(3, 4);\n allShowA(1); // 1\n allShowA(2); // 3\n allShowA(3); // 6\n\t\n function partShowA(arg) {\n\tvar showA = funA(3, 4);\n\tshowA(arg);\n}\npartShowA(1); // 1\npartShowA(2); // 2\npartShowA(3); // 3\nconsole.log(\"------------------------------------------------\");\n```\n#### 3.3 函数内变量共享\n```\nfunction funA1() {\n\tvar i = 0;\n\tfunction funB() {\n\t\ti++;\n\t\tconsole.log(i);\n\t}\n\tallShowC = function(){\n\t\ti++;\n\t\tconsole.log(i);\n\t}\n\treturn funB();\n}\nvar allShow1 = funA1();\nvar allShow2 = funA1();\nconsole.log(\"------------------------------------------------\");\n```\n\n#### 参考\n[JavaScript function函数种类](http://www.cnblogs.com/polk6/p/3284839.html)\n\n\n","slug":"2017-01-23-快速了解JavaScript中的函数","published":1,"updated":"2017-03-05T04:16:10.000Z","photos":[],"link":"","_id":"cj0l1ptax000k0er90j4wkuer","content":"<p>最近在学习前端知识,顺手把一些东西记录下来,加深记忆,忘记的时候翻阅一下,温故而知新。<br><a id=\"more\"></a></p>\n<h2 id=\"快速了解JavaScript中的函数\"><a href=\"#快速了解JavaScript中的函数\" class=\"headerlink\" title=\"快速了解JavaScript中的函数\"></a>快速了解JavaScript中的函数</h2><h3 id=\"1-普通函数\"><a href=\"#1-普通函数\" class=\"headerlink\" title=\"1.普通函数\"></a>1.普通函数</h3><h4 id=\"1-1-普通函数示例\"><a href=\"#1-1-普通函数示例\" class=\"headerlink\" title=\"1.1 普通函数示例\"></a>1.1 普通函数示例</h4><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div></pre></td><td class=\"code\"><pre><div class=\"line\">function sayHello() {</div><div class=\"line\">\tconsole.log("hello");</div><div class=\"line\">}</div><div class=\"line\">console.log("------------------------------------------------");</div></pre></td></tr></table></figure>\n<h4 id=\"1-2-同名函数覆盖\"><a href=\"#1-2-同名函数覆盖\" class=\"headerlink\" title=\"1.2 同名函数覆盖,\"></a>1.2 同名函数覆盖,</h4><p>JS中没有函数重载,定义相同的函数名,不同参数的函数。 调用时,后面的函数会覆盖前面的函数。</p>\n<figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div></pre></td><td class=\"code\"><pre><div class=\"line\">function add(value1) {</div><div class=\"line\">\treturn value1 + 1;</div><div class=\"line\">}</div><div class=\"line\">\t</div><div class=\"line\">function add(value1, value2) {</div><div class=\"line\">\treturn value1 + 2;</div><div class=\"line\">}</div><div class=\"line\">console.log(add(2)); //4</div><div class=\"line\">console.log("------------------------------------------------");</div></pre></td></tr></table></figure>\n<h4 id=\"1-3-arguments对象\"><a href=\"#1-3-arguments对象\" class=\"headerlink\" title=\"1.3 arguments对象\"></a>1.3 arguments对象</h4><p> 传入参数大于定义参数时,arguments对象存放了函数调用时的所有参数<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div></pre></td><td class=\"code\"><pre><div class=\"line\">function showNames(name) {</div><div class=\"line\">\tconsole.log(name);</div><div class=\"line\">\tfor (var i = 0; i < arguments.length; i++) {</div><div class=\"line\">\t\tconsole.log(arguments[i]);</div><div class=\"line\">\t} </div><div class=\"line\">}</div><div class=\"line\">showNames("🍎", "🍐", "🍑"); //🍎🍎🍐🍑</div><div class=\"line\">console.log("------------------------------------------------");</div></pre></td></tr></table></figure></p>\n<h4 id=\"1-4-“undefined”\"><a href=\"#1-4-“undefined”\" class=\"headerlink\" title=\"1.4 “undefined”\"></a>1.4 “undefined”</h4><p>若函数没有指明返回值,默认返回的是“undefined”<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div></pre></td><td class=\"code\"><pre><div class=\"line\">function showUndefined() {</div><div class=\"line\">\t</div><div class=\"line\">}</div><div class=\"line\">console.log(showUndefined());</div><div class=\"line\">console.log("------------------------------------------------");</div></pre></td></tr></table></figure></p>\n<h3 id=\"2-匿名函数\"><a href=\"#2-匿名函数\" class=\"headerlink\" title=\"2.匿名函数\"></a>2.匿名函数</h3><h4 id=\"2-1-变量匿名函数\"><a href=\"#2-1-变量匿名函数\" class=\"headerlink\" title=\"2.1 变量匿名函数\"></a>2.1 变量匿名函数</h4><p>可以把函数赋值给变量,事件。<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div></pre></td><td class=\"code\"><pre><div class=\"line\">var add = function (num1, num2) {</div><div class=\"line\">\tconsole.log(num1 + num2);</div><div class=\"line\">}</div><div class=\"line\">\t</div><div class=\"line\">add(1, 1);</div><div class=\"line\">console.log("------------------------------------------------");</div></pre></td></tr></table></figure></p>\n<h4 id=\"2-2-无名称匿名函数\"><a href=\"#2-2-无名称匿名函数\" class=\"headerlink\" title=\"2.2 无名称匿名函数\"></a>2.2 无名称匿名函数</h4><p>即在函数声明时,在后面紧跟参数。JS解析语法时立即执行该函数。<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div></pre></td><td class=\"code\"><pre><div class=\"line\">(function(arg) {</div><div class=\"line\">\tconsole.log("无名称匿名函数" + arg);</div><div class=\"line\">})(33);</div><div class=\"line\">console.log("------------------------------------------------");</div></pre></td></tr></table></figure></p>\n<p>适用场景,只需执行一次的。如浏览器加载完,只需要执行一次且后面不执行的功能。</p>\n<h3 id=\"3-闭包函数\"><a href=\"#3-闭包函数\" class=\"headerlink\" title=\"3.闭包函数\"></a>3.闭包函数</h3><ul>\n<li>函数A内部声明了个函数B,函数B引用了函数B之外的变量,并且函数A的返回值是函数B的引用,那么函数B就是闭包函数。</li>\n</ul>\n<h4 id=\"3-1-全局引用与局部引用\"><a href=\"#3-1-全局引用与局部引用\" class=\"headerlink\" title=\"3.1 全局引用与局部引用\"></a>3.1 全局引用与局部引用</h4><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div><div class=\"line\">13</div><div class=\"line\">14</div><div class=\"line\">15</div><div class=\"line\">16</div><div class=\"line\">17</div><div class=\"line\">18</div></pre></td><td class=\"code\"><pre><div class=\"line\">function funA() {</div><div class=\"line\">\tvar i = 0;</div><div class=\"line\">\tfunction funB() { // 闭包函数funB</div><div class=\"line\">\t\ti++;</div><div class=\"line\">\t\tconsole.log(i);</div><div class=\"line\">\t}</div><div class=\"line\">\treturn funB();</div><div class=\"line\">}</div><div class=\"line\">// allShowA是全局变量,引用了函数funA,重复运行allShowA(),输出1,2,3,4等累加值。</div><div class=\"line\">var allShowA = funA(); </div><div class=\"line\"></div><div class=\"line\">// 执行函数partShowA(),因为内部只声明了局部变量showA来引用函数funA,函数执行完由于作用域,showA变量就被释放了。</div><div class=\"line\">function partShowA() {</div><div class=\"line\">\tvar showA = funA();</div><div class=\"line\">\tshowA();</div><div class=\"line\">}</div><div class=\"line\">// 闭包的关键就在于作用域:全局变量占有的资源只有当页面变换或浏览器关闭后才会释放。var allShowA = funA()时,相当于allShowA引用了funB(),从而使funB()里的资源不被GC回收,因此funA()里的资源也不会。</div><div class=\"line\">console.log("------------------------------------------------");</div></pre></td></tr></table></figure>\n<h4 id=\"3-2-有参数的闭包函数\"><a href=\"#3-2-有参数的闭包函数\" class=\"headerlink\" title=\"3.2 有参数的闭包函数\"></a>3.2 有参数的闭包函数</h4><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div><div class=\"line\">13</div><div class=\"line\">14</div><div class=\"line\">15</div><div class=\"line\">16</div><div class=\"line\">17</div><div class=\"line\">18</div><div class=\"line\">19</div><div class=\"line\">20</div><div class=\"line\">21</div><div class=\"line\">22</div></pre></td><td class=\"code\"><pre><div class=\"line\"> function funA(arg1, arg2) {</div><div class=\"line\"> \tvar i = 0;</div><div class=\"line\"> \tfunction funB(num) {</div><div class=\"line\"> \t\ti = i + num;</div><div class=\"line\"> \t\tconsole.log(i);</div><div class=\"line\"> \t}</div><div class=\"line\"> \treturn funB;</div><div class=\"line\"> }</div><div class=\"line\">\t</div><div class=\"line\"> var allShowA = funA(3, 4);</div><div class=\"line\"> allShowA(1); // 1</div><div class=\"line\"> allShowA(2); // 3</div><div class=\"line\"> allShowA(3); // 6</div><div class=\"line\">\t</div><div class=\"line\"> function partShowA(arg) {</div><div class=\"line\">\tvar showA = funA(3, 4);</div><div class=\"line\">\tshowA(arg);</div><div class=\"line\">}</div><div class=\"line\">partShowA(1); // 1</div><div class=\"line\">partShowA(2); // 2</div><div class=\"line\">partShowA(3); // 3</div><div class=\"line\">console.log("------------------------------------------------");</div></pre></td></tr></table></figure>\n<h4 id=\"3-3-函数内变量共享\"><a href=\"#3-3-函数内变量共享\" class=\"headerlink\" title=\"3.3 函数内变量共享\"></a>3.3 函数内变量共享</h4><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div><div class=\"line\">13</div><div class=\"line\">14</div><div class=\"line\">15</div></pre></td><td class=\"code\"><pre><div class=\"line\">function funA1() {</div><div class=\"line\">\tvar i = 0;</div><div class=\"line\">\tfunction funB() {</div><div class=\"line\">\t\ti++;</div><div class=\"line\">\t\tconsole.log(i);</div><div class=\"line\">\t}</div><div class=\"line\">\tallShowC = function(){</div><div class=\"line\">\t\ti++;</div><div class=\"line\">\t\tconsole.log(i);</div><div class=\"line\">\t}</div><div class=\"line\">\treturn funB();</div><div class=\"line\">}</div><div class=\"line\">var allShow1 = funA1();</div><div class=\"line\">var allShow2 = funA1();</div><div class=\"line\">console.log("------------------------------------------------");</div></pre></td></tr></table></figure>\n<h4 id=\"参考\"><a href=\"#参考\" class=\"headerlink\" title=\"参考\"></a>参考</h4><p><a href=\"http://www.cnblogs.com/polk6/p/3284839.html\" target=\"_blank\" rel=\"external\">JavaScript function函数种类</a></p>\n","excerpt":"<p>最近在学习前端知识,顺手把一些东西记录下来,加深记忆,忘记的时候翻阅一下,温故而知新。<br>","more":"</p>\n<h2 id=\"快速了解JavaScript中的函数\"><a href=\"#快速了解JavaScript中的函数\" class=\"headerlink\" title=\"快速了解JavaScript中的函数\"></a>快速了解JavaScript中的函数</h2><h3 id=\"1-普通函数\"><a href=\"#1-普通函数\" class=\"headerlink\" title=\"1.普通函数\"></a>1.普通函数</h3><h4 id=\"1-1-普通函数示例\"><a href=\"#1-1-普通函数示例\" class=\"headerlink\" title=\"1.1 普通函数示例\"></a>1.1 普通函数示例</h4><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div></pre></td><td class=\"code\"><pre><div class=\"line\">function sayHello() {</div><div class=\"line\">\tconsole.log("hello");</div><div class=\"line\">}</div><div class=\"line\">console.log("------------------------------------------------");</div></pre></td></tr></table></figure>\n<h4 id=\"1-2-同名函数覆盖\"><a href=\"#1-2-同名函数覆盖\" class=\"headerlink\" title=\"1.2 同名函数覆盖,\"></a>1.2 同名函数覆盖,</h4><p>JS中没有函数重载,定义相同的函数名,不同参数的函数。 调用时,后面的函数会覆盖前面的函数。</p>\n<figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div></pre></td><td class=\"code\"><pre><div class=\"line\">function add(value1) {</div><div class=\"line\">\treturn value1 + 1;</div><div class=\"line\">}</div><div class=\"line\">\t</div><div class=\"line\">function add(value1, value2) {</div><div class=\"line\">\treturn value1 + 2;</div><div class=\"line\">}</div><div class=\"line\">console.log(add(2)); //4</div><div class=\"line\">console.log("------------------------------------------------");</div></pre></td></tr></table></figure>\n<h4 id=\"1-3-arguments对象\"><a href=\"#1-3-arguments对象\" class=\"headerlink\" title=\"1.3 arguments对象\"></a>1.3 arguments对象</h4><p> 传入参数大于定义参数时,arguments对象存放了函数调用时的所有参数<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div></pre></td><td class=\"code\"><pre><div class=\"line\">function showNames(name) {</div><div class=\"line\">\tconsole.log(name);</div><div class=\"line\">\tfor (var i = 0; i < arguments.length; i++) {</div><div class=\"line\">\t\tconsole.log(arguments[i]);</div><div class=\"line\">\t} </div><div class=\"line\">}</div><div class=\"line\">showNames("🍎", "🍐", "🍑"); //🍎🍎🍐🍑</div><div class=\"line\">console.log("------------------------------------------------");</div></pre></td></tr></table></figure></p>\n<h4 id=\"1-4-“undefined”\"><a href=\"#1-4-“undefined”\" class=\"headerlink\" title=\"1.4 “undefined”\"></a>1.4 “undefined”</h4><p>若函数没有指明返回值,默认返回的是“undefined”<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div></pre></td><td class=\"code\"><pre><div class=\"line\">function showUndefined() {</div><div class=\"line\">\t</div><div class=\"line\">}</div><div class=\"line\">console.log(showUndefined());</div><div class=\"line\">console.log("------------------------------------------------");</div></pre></td></tr></table></figure></p>\n<h3 id=\"2-匿名函数\"><a href=\"#2-匿名函数\" class=\"headerlink\" title=\"2.匿名函数\"></a>2.匿名函数</h3><h4 id=\"2-1-变量匿名函数\"><a href=\"#2-1-变量匿名函数\" class=\"headerlink\" title=\"2.1 变量匿名函数\"></a>2.1 变量匿名函数</h4><p>可以把函数赋值给变量,事件。<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div></pre></td><td class=\"code\"><pre><div class=\"line\">var add = function (num1, num2) {</div><div class=\"line\">\tconsole.log(num1 + num2);</div><div class=\"line\">}</div><div class=\"line\">\t</div><div class=\"line\">add(1, 1);</div><div class=\"line\">console.log("------------------------------------------------");</div></pre></td></tr></table></figure></p>\n<h4 id=\"2-2-无名称匿名函数\"><a href=\"#2-2-无名称匿名函数\" class=\"headerlink\" title=\"2.2 无名称匿名函数\"></a>2.2 无名称匿名函数</h4><p>即在函数声明时,在后面紧跟参数。JS解析语法时立即执行该函数。<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div></pre></td><td class=\"code\"><pre><div class=\"line\">(function(arg) {</div><div class=\"line\">\tconsole.log("无名称匿名函数" + arg);</div><div class=\"line\">})(33);</div><div class=\"line\">console.log("------------------------------------------------");</div></pre></td></tr></table></figure></p>\n<p>适用场景,只需执行一次的。如浏览器加载完,只需要执行一次且后面不执行的功能。</p>\n<h3 id=\"3-闭包函数\"><a href=\"#3-闭包函数\" class=\"headerlink\" title=\"3.闭包函数\"></a>3.闭包函数</h3><ul>\n<li>函数A内部声明了个函数B,函数B引用了函数B之外的变量,并且函数A的返回值是函数B的引用,那么函数B就是闭包函数。</li>\n</ul>\n<h4 id=\"3-1-全局引用与局部引用\"><a href=\"#3-1-全局引用与局部引用\" class=\"headerlink\" title=\"3.1 全局引用与局部引用\"></a>3.1 全局引用与局部引用</h4><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div><div class=\"line\">13</div><div class=\"line\">14</div><div class=\"line\">15</div><div class=\"line\">16</div><div class=\"line\">17</div><div class=\"line\">18</div></pre></td><td class=\"code\"><pre><div class=\"line\">function funA() {</div><div class=\"line\">\tvar i = 0;</div><div class=\"line\">\tfunction funB() { // 闭包函数funB</div><div class=\"line\">\t\ti++;</div><div class=\"line\">\t\tconsole.log(i);</div><div class=\"line\">\t}</div><div class=\"line\">\treturn funB();</div><div class=\"line\">}</div><div class=\"line\">// allShowA是全局变量,引用了函数funA,重复运行allShowA(),输出1,2,3,4等累加值。</div><div class=\"line\">var allShowA = funA(); </div><div class=\"line\"></div><div class=\"line\">// 执行函数partShowA(),因为内部只声明了局部变量showA来引用函数funA,函数执行完由于作用域,showA变量就被释放了。</div><div class=\"line\">function partShowA() {</div><div class=\"line\">\tvar showA = funA();</div><div class=\"line\">\tshowA();</div><div class=\"line\">}</div><div class=\"line\">// 闭包的关键就在于作用域:全局变量占有的资源只有当页面变换或浏览器关闭后才会释放。var allShowA = funA()时,相当于allShowA引用了funB(),从而使funB()里的资源不被GC回收,因此funA()里的资源也不会。</div><div class=\"line\">console.log("------------------------------------------------");</div></pre></td></tr></table></figure>\n<h4 id=\"3-2-有参数的闭包函数\"><a href=\"#3-2-有参数的闭包函数\" class=\"headerlink\" title=\"3.2 有参数的闭包函数\"></a>3.2 有参数的闭包函数</h4><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div><div class=\"line\">13</div><div class=\"line\">14</div><div class=\"line\">15</div><div class=\"line\">16</div><div class=\"line\">17</div><div class=\"line\">18</div><div class=\"line\">19</div><div class=\"line\">20</div><div class=\"line\">21</div><div class=\"line\">22</div></pre></td><td class=\"code\"><pre><div class=\"line\"> function funA(arg1, arg2) {</div><div class=\"line\"> \tvar i = 0;</div><div class=\"line\"> \tfunction funB(num) {</div><div class=\"line\"> \t\ti = i + num;</div><div class=\"line\"> \t\tconsole.log(i);</div><div class=\"line\"> \t}</div><div class=\"line\"> \treturn funB;</div><div class=\"line\"> }</div><div class=\"line\">\t</div><div class=\"line\"> var allShowA = funA(3, 4);</div><div class=\"line\"> allShowA(1); // 1</div><div class=\"line\"> allShowA(2); // 3</div><div class=\"line\"> allShowA(3); // 6</div><div class=\"line\">\t</div><div class=\"line\"> function partShowA(arg) {</div><div class=\"line\">\tvar showA = funA(3, 4);</div><div class=\"line\">\tshowA(arg);</div><div class=\"line\">}</div><div class=\"line\">partShowA(1); // 1</div><div class=\"line\">partShowA(2); // 2</div><div class=\"line\">partShowA(3); // 3</div><div class=\"line\">console.log("------------------------------------------------");</div></pre></td></tr></table></figure>\n<h4 id=\"3-3-函数内变量共享\"><a href=\"#3-3-函数内变量共享\" class=\"headerlink\" title=\"3.3 函数内变量共享\"></a>3.3 函数内变量共享</h4><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div><div class=\"line\">13</div><div class=\"line\">14</div><div class=\"line\">15</div></pre></td><td class=\"code\"><pre><div class=\"line\">function funA1() {</div><div class=\"line\">\tvar i = 0;</div><div class=\"line\">\tfunction funB() {</div><div class=\"line\">\t\ti++;</div><div class=\"line\">\t\tconsole.log(i);</div><div class=\"line\">\t}</div><div class=\"line\">\tallShowC = function(){</div><div class=\"line\">\t\ti++;</div><div class=\"line\">\t\tconsole.log(i);</div><div class=\"line\">\t}</div><div class=\"line\">\treturn funB();</div><div class=\"line\">}</div><div class=\"line\">var allShow1 = funA1();</div><div class=\"line\">var allShow2 = funA1();</div><div class=\"line\">console.log("------------------------------------------------");</div></pre></td></tr></table></figure>\n<h4 id=\"参考\"><a href=\"#参考\" class=\"headerlink\" title=\"参考\"></a>参考</h4><p><a href=\"http://www.cnblogs.com/polk6/p/3284839.html\">JavaScript function函数种类</a></p>"},{"layout":"post","title":"iOS中英文混合排序","date":"2017-02-27T16:00:00.000Z","comments":1,"keywords":"iOS中英文混合排序","publish":true,"description":"iOS中英文混合排序","_content":"\n听起来中英文排序貌似很简单,直接使用数组或者字符串相对应的方法不就行了嘛,但是我真正去做的时候确实发现了一些问题。\n<!-- more -->\n\n## 牛刀小试\n首先我想到的是用这种方法,直接看代码吧。\n\n```\nNSArray *array = @[@\"俺家\", @\"阿尔卑斯\", @\"上海\", @\"AJ\", @\"北京\"];\nNSArray *sortArray = [array sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {\n return [obj1 compare:obj2 options:NSCaseInsensitiveSearch];\n }];\n```\n然后运行结果并没有达到预期的目的。\n\n```\n结果:\nAJ\n上海\n俺家\n北京\n阿尔卑斯\n```\n## 发现问题\n为什么会这样呢?后来查资料发现,汉字如果使用这种方式的排序,并不是按照首字母进行排序的,也就是说这个方法用来排列纯字母的是没问题的,汉字是不行的。看了compare方法的介绍,我发现了一条重要的信息。\n\n_When working with text that’s presented to the user, use the localizedStandardCompare: instead, or use the compare:options:range:locale: method, passing the user’s locale._\n\n这段话大概意思是如果用户设置了手机的语言,则需要使用`localizedStandardCompare`,好吧,那就换种办法试一试。\n\n## 渐入佳境\n\n```\nNSArray *array = @[@\"俺家\", @\"阿尔卑斯\", @\"上海\", @\"AJ\", @\"北京\"];\nNSArray *sortArray = [array sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {\n return [obj1 localizedCompare:obj2];\n}];\nfor (NSString *str in sortArray) {\n NSLog(@\"%@\\n\", str);\n}\n\n结果:\n阿尔卑斯\n俺家\n北京\n上海\nAJ\n```\n虽然这次排序依然是不正确的,但是可以看到其中的汉字已经正确了,说明这个方法并不能兼容汉字和字母的排序。那么就只能通过取汉字拼音的首字母去比较了,这样才能和其他字母进行比较。后来我找到了这种解决办法。\n\n## 守得云开见月明\n\n```\nNSInteger sortObjects(id obj1, id obj2,void *context)\n{\n NSMutableString * str1 = [[NSMutableString alloc] initWithString:obj1];\n if (CFStringTransform((__bridge CFMutableStringRef)str1, 0, kCFStringTransformMandarinLatin, NO)) {\n }\n \n NSMutableString * str2 = [[NSMutableString alloc] initWithString:obj2];\n if (CFStringTransform((__bridge CFMutableStringRef)str2, 0, kCFStringTransformMandarinLatin, NO)) {\n }\n return [str1 localizedCompare:str2];\n}\n\nNSArray *array = @[@\"俺家\", @\"阿尔卑斯\", @\"上海\", @\"AJ\", @\"北京\"];\nNSArray *sortArray = [array sortedArrayUsingFunction:sortObjects context:NULL];\nfor (NSString *str in sortArray) {\n NSLog(@\"%@\\n\", str);\n}\n\n结果:\n阿尔卑斯\nAJ\n俺家\n北京\n上海\n```\n这次终于是正确了,上面的sortObjects函数是将汉字转成拼音,字母不做任何处理,这样再运用第二种方法的比较就可以了。\n\n","source":"_posts/2017-02-28-iOS中英文混合排序.md","raw":"---\nlayout: post\ntitle: \"iOS中英文混合排序\"\ndate: 2017-02-28\ncomments: true\ncategories: iOS\ntags: [iOS]\nkeywords: iOS中英文混合排序\npublish: true\ndescription: iOS中英文混合排序\n---\n\n听起来中英文排序貌似很简单,直接使用数组或者字符串相对应的方法不就行了嘛,但是我真正去做的时候确实发现了一些问题。\n<!-- more -->\n\n## 牛刀小试\n首先我想到的是用这种方法,直接看代码吧。\n\n```\nNSArray *array = @[@\"俺家\", @\"阿尔卑斯\", @\"上海\", @\"AJ\", @\"北京\"];\nNSArray *sortArray = [array sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {\n return [obj1 compare:obj2 options:NSCaseInsensitiveSearch];\n }];\n```\n然后运行结果并没有达到预期的目的。\n\n```\n结果:\nAJ\n上海\n俺家\n北京\n阿尔卑斯\n```\n## 发现问题\n为什么会这样呢?后来查资料发现,汉字如果使用这种方式的排序,并不是按照首字母进行排序的,也就是说这个方法用来排列纯字母的是没问题的,汉字是不行的。看了compare方法的介绍,我发现了一条重要的信息。\n\n_When working with text that’s presented to the user, use the localizedStandardCompare: instead, or use the compare:options:range:locale: method, passing the user’s locale._\n\n这段话大概意思是如果用户设置了手机的语言,则需要使用`localizedStandardCompare`,好吧,那就换种办法试一试。\n\n## 渐入佳境\n\n```\nNSArray *array = @[@\"俺家\", @\"阿尔卑斯\", @\"上海\", @\"AJ\", @\"北京\"];\nNSArray *sortArray = [array sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {\n return [obj1 localizedCompare:obj2];\n}];\nfor (NSString *str in sortArray) {\n NSLog(@\"%@\\n\", str);\n}\n\n结果:\n阿尔卑斯\n俺家\n北京\n上海\nAJ\n```\n虽然这次排序依然是不正确的,但是可以看到其中的汉字已经正确了,说明这个方法并不能兼容汉字和字母的排序。那么就只能通过取汉字拼音的首字母去比较了,这样才能和其他字母进行比较。后来我找到了这种解决办法。\n\n## 守得云开见月明\n\n```\nNSInteger sortObjects(id obj1, id obj2,void *context)\n{\n NSMutableString * str1 = [[NSMutableString alloc] initWithString:obj1];\n if (CFStringTransform((__bridge CFMutableStringRef)str1, 0, kCFStringTransformMandarinLatin, NO)) {\n }\n \n NSMutableString * str2 = [[NSMutableString alloc] initWithString:obj2];\n if (CFStringTransform((__bridge CFMutableStringRef)str2, 0, kCFStringTransformMandarinLatin, NO)) {\n }\n return [str1 localizedCompare:str2];\n}\n\nNSArray *array = @[@\"俺家\", @\"阿尔卑斯\", @\"上海\", @\"AJ\", @\"北京\"];\nNSArray *sortArray = [array sortedArrayUsingFunction:sortObjects context:NULL];\nfor (NSString *str in sortArray) {\n NSLog(@\"%@\\n\", str);\n}\n\n结果:\n阿尔卑斯\nAJ\n俺家\n北京\n上海\n```\n这次终于是正确了,上面的sortObjects函数是将汉字转成拼音,字母不做任何处理,这样再运用第二种方法的比较就可以了。\n\n","slug":"2017-02-28-iOS中英文混合排序","published":1,"updated":"2017-03-05T04:15:51.000Z","photos":[],"link":"","_id":"cj0l1ptb1000p0er9bhskkf18","content":"<p>听起来中英文排序貌似很简单,直接使用数组或者字符串相对应的方法不就行了嘛,但是我真正去做的时候确实发现了一些问题。<br><a id=\"more\"></a></p>\n<h2 id=\"牛刀小试\"><a href=\"#牛刀小试\" class=\"headerlink\" title=\"牛刀小试\"></a>牛刀小试</h2><p>首先我想到的是用这种方法,直接看代码吧。</p>\n<figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div></pre></td><td class=\"code\"><pre><div class=\"line\">NSArray *array = @[@"俺家", @"阿尔卑斯", @"上海", @"AJ", @"北京"];</div><div class=\"line\">NSArray *sortArray = [array sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {</div><div class=\"line\"> return [obj1 compare:obj2 options:NSCaseInsensitiveSearch];</div><div class=\"line\"> }];</div></pre></td></tr></table></figure>\n<p>然后运行结果并没有达到预期的目的。</p>\n<figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div></pre></td><td class=\"code\"><pre><div class=\"line\">结果:</div><div class=\"line\">AJ</div><div class=\"line\">上海</div><div class=\"line\">俺家</div><div class=\"line\">北京</div><div class=\"line\">阿尔卑斯</div></pre></td></tr></table></figure>\n<h2 id=\"发现问题\"><a href=\"#发现问题\" class=\"headerlink\" title=\"发现问题\"></a>发现问题</h2><p>为什么会这样呢?后来查资料发现,汉字如果使用这种方式的排序,并不是按照首字母进行排序的,也就是说这个方法用来排列纯字母的是没问题的,汉字是不行的。看了compare方法的介绍,我发现了一条重要的信息。</p>\n<p><em>When working with text that’s presented to the user, use the localizedStandardCompare: instead, or use the compare:options:range:locale: method, passing the user’s locale.</em></p>\n<p>这段话大概意思是如果用户设置了手机的语言,则需要使用<code>localizedStandardCompare</code>,好吧,那就换种办法试一试。</p>\n<h2 id=\"渐入佳境\"><a href=\"#渐入佳境\" class=\"headerlink\" title=\"渐入佳境\"></a>渐入佳境</h2><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div><div class=\"line\">13</div><div class=\"line\">14</div></pre></td><td class=\"code\"><pre><div class=\"line\">NSArray *array = @[@"俺家", @"阿尔卑斯", @"上海", @"AJ", @"北京"];</div><div class=\"line\">NSArray *sortArray = [array sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {</div><div class=\"line\"> return [obj1 localizedCompare:obj2];</div><div class=\"line\">}];</div><div class=\"line\">for (NSString *str in sortArray) {</div><div class=\"line\"> NSLog(@"%@\\n", str);</div><div class=\"line\">}</div><div class=\"line\"></div><div class=\"line\">结果:</div><div class=\"line\">阿尔卑斯</div><div class=\"line\">俺家</div><div class=\"line\">北京</div><div class=\"line\">上海</div><div class=\"line\">AJ</div></pre></td></tr></table></figure>\n<p>虽然这次排序依然是不正确的,但是可以看到其中的汉字已经正确了,说明这个方法并不能兼容汉字和字母的排序。那么就只能通过取汉字拼音的首字母去比较了,这样才能和其他字母进行比较。后来我找到了这种解决办法。</p>\n<h2 id=\"守得云开见月明\"><a href=\"#守得云开见月明\" class=\"headerlink\" title=\"守得云开见月明\"></a>守得云开见月明</h2><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div><div class=\"line\">13</div><div class=\"line\">14</div><div class=\"line\">15</div><div class=\"line\">16</div><div class=\"line\">17</div><div class=\"line\">18</div><div class=\"line\">19</div><div class=\"line\">20</div><div class=\"line\">21</div><div class=\"line\">22</div><div class=\"line\">23</div><div class=\"line\">24</div></pre></td><td class=\"code\"><pre><div class=\"line\">NSInteger sortObjects(id obj1, id obj2,void *context)</div><div class=\"line\">{</div><div class=\"line\"> NSMutableString * str1 = [[NSMutableString alloc] initWithString:obj1];</div><div class=\"line\"> if (CFStringTransform((__bridge CFMutableStringRef)str1, 0, kCFStringTransformMandarinLatin, NO)) {</div><div class=\"line\"> }</div><div class=\"line\"> </div><div class=\"line\"> NSMutableString * str2 = [[NSMutableString alloc] initWithString:obj2];</div><div class=\"line\"> if (CFStringTransform((__bridge CFMutableStringRef)str2, 0, kCFStringTransformMandarinLatin, NO)) {</div><div class=\"line\"> }</div><div class=\"line\"> return [str1 localizedCompare:str2];</div><div class=\"line\">}</div><div class=\"line\"></div><div class=\"line\">NSArray *array = @[@"俺家", @"阿尔卑斯", @"上海", @"AJ", @"北京"];</div><div class=\"line\">NSArray *sortArray = [array sortedArrayUsingFunction:sortObjects context:NULL];</div><div class=\"line\">for (NSString *str in sortArray) {</div><div class=\"line\"> NSLog(@"%@\\n", str);</div><div class=\"line\">}</div><div class=\"line\"></div><div class=\"line\">结果:</div><div class=\"line\">阿尔卑斯</div><div class=\"line\">AJ</div><div class=\"line\">俺家</div><div class=\"line\">北京</div><div class=\"line\">上海</div></pre></td></tr></table></figure>\n<p>这次终于是正确了,上面的sortObjects函数是将汉字转成拼音,字母不做任何处理,这样再运用第二种方法的比较就可以了。</p>\n","excerpt":"<p>听起来中英文排序貌似很简单,直接使用数组或者字符串相对应的方法不就行了嘛,但是我真正去做的时候确实发现了一些问题。<br>","more":"</p>\n<h2 id=\"牛刀小试\"><a href=\"#牛刀小试\" class=\"headerlink\" title=\"牛刀小试\"></a>牛刀小试</h2><p>首先我想到的是用这种方法,直接看代码吧。</p>\n<figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div></pre></td><td class=\"code\"><pre><div class=\"line\">NSArray *array = @[@"俺家", @"阿尔卑斯", @"上海", @"AJ", @"北京"];</div><div class=\"line\">NSArray *sortArray = [array sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {</div><div class=\"line\"> return [obj1 compare:obj2 options:NSCaseInsensitiveSearch];</div><div class=\"line\"> }];</div></pre></td></tr></table></figure>\n<p>然后运行结果并没有达到预期的目的。</p>\n<figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div></pre></td><td class=\"code\"><pre><div class=\"line\">结果:</div><div class=\"line\">AJ</div><div class=\"line\">上海</div><div class=\"line\">俺家</div><div class=\"line\">北京</div><div class=\"line\">阿尔卑斯</div></pre></td></tr></table></figure>\n<h2 id=\"发现问题\"><a href=\"#发现问题\" class=\"headerlink\" title=\"发现问题\"></a>发现问题</h2><p>为什么会这样呢?后来查资料发现,汉字如果使用这种方式的排序,并不是按照首字母进行排序的,也就是说这个方法用来排列纯字母的是没问题的,汉字是不行的。看了compare方法的介绍,我发现了一条重要的信息。</p>\n<p><em>When working with text that’s presented to the user, use the localizedStandardCompare: instead, or use the compare:options:range:locale: method, passing the user’s locale.</em></p>\n<p>这段话大概意思是如果用户设置了手机的语言,则需要使用<code>localizedStandardCompare</code>,好吧,那就换种办法试一试。</p>\n<h2 id=\"渐入佳境\"><a href=\"#渐入佳境\" class=\"headerlink\" title=\"渐入佳境\"></a>渐入佳境</h2><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div><div class=\"line\">13</div><div class=\"line\">14</div></pre></td><td class=\"code\"><pre><div class=\"line\">NSArray *array = @[@"俺家", @"阿尔卑斯", @"上海", @"AJ", @"北京"];</div><div class=\"line\">NSArray *sortArray = [array sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {</div><div class=\"line\"> return [obj1 localizedCompare:obj2];</div><div class=\"line\">}];</div><div class=\"line\">for (NSString *str in sortArray) {</div><div class=\"line\"> NSLog(@"%@\\n", str);</div><div class=\"line\">}</div><div class=\"line\"></div><div class=\"line\">结果:</div><div class=\"line\">阿尔卑斯</div><div class=\"line\">俺家</div><div class=\"line\">北京</div><div class=\"line\">上海</div><div class=\"line\">AJ</div></pre></td></tr></table></figure>\n<p>虽然这次排序依然是不正确的,但是可以看到其中的汉字已经正确了,说明这个方法并不能兼容汉字和字母的排序。那么就只能通过取汉字拼音的首字母去比较了,这样才能和其他字母进行比较。后来我找到了这种解决办法。</p>\n<h2 id=\"守得云开见月明\"><a href=\"#守得云开见月明\" class=\"headerlink\" title=\"守得云开见月明\"></a>守得云开见月明</h2><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div><div class=\"line\">13</div><div class=\"line\">14</div><div class=\"line\">15</div><div class=\"line\">16</div><div class=\"line\">17</div><div class=\"line\">18</div><div class=\"line\">19</div><div class=\"line\">20</div><div class=\"line\">21</div><div class=\"line\">22</div><div class=\"line\">23</div><div class=\"line\">24</div></pre></td><td class=\"code\"><pre><div class=\"line\">NSInteger sortObjects(id obj1, id obj2,void *context)</div><div class=\"line\">{</div><div class=\"line\"> NSMutableString * str1 = [[NSMutableString alloc] initWithString:obj1];</div><div class=\"line\"> if (CFStringTransform((__bridge CFMutableStringRef)str1, 0, kCFStringTransformMandarinLatin, NO)) {</div><div class=\"line\"> }</div><div class=\"line\"> </div><div class=\"line\"> NSMutableString * str2 = [[NSMutableString alloc] initWithString:obj2];</div><div class=\"line\"> if (CFStringTransform((__bridge CFMutableStringRef)str2, 0, kCFStringTransformMandarinLatin, NO)) {</div><div class=\"line\"> }</div><div class=\"line\"> return [str1 localizedCompare:str2];</div><div class=\"line\">}</div><div class=\"line\"></div><div class=\"line\">NSArray *array = @[@"俺家", @"阿尔卑斯", @"上海", @"AJ", @"北京"];</div><div class=\"line\">NSArray *sortArray = [array sortedArrayUsingFunction:sortObjects context:NULL];</div><div class=\"line\">for (NSString *str in sortArray) {</div><div class=\"line\"> NSLog(@"%@\\n", str);</div><div class=\"line\">}</div><div class=\"line\"></div><div class=\"line\">结果:</div><div class=\"line\">阿尔卑斯</div><div class=\"line\">AJ</div><div class=\"line\">俺家</div><div class=\"line\">北京</div><div class=\"line\">上海</div></pre></td></tr></table></figure>\n<p>这次终于是正确了,上面的sortObjects函数是将汉字转成拼音,字母不做任何处理,这样再运用第二种方法的比较就可以了。</p>"},{"layout":"post","title":"iOS开发神器Reveal使用指南","date":"2017-03-03T16:00:00.000Z","comments":1,"keywords":"iOS开发神器Reveal使用指南","publish":true,"description":"iOS开发神器Reveal使用指南","_content":">作为一名iOS开发者,想必Reveal大家都是知道的。它提供的视图层次浏览功能,给开发过程中定位错误带来了极大的便利,甚至可以通过越狱设备逆向别人的APP,浏览其他APP的视图结构。自从前阵子升级到Xcode8.x之后,Reveal1.6.3就再也用不了了,起初以为是系统兼容性问题,后来等到了Reveal2这个蛋疼的问题依然没解决,最近总算是成功的解决了这个问题,现在Reveal7已经出来了,不得不说,这个版本号真的是醉了,跟坐火箭一样。Reveal的官网在[这里](https://revealapp.com/),由于Reveal版本号更新太快,不同版本之间的接入操作会有一些差异,如果使用中遇到麻烦,一定要找对应版本的解决办法,这里就以Reveal4为例介绍一下使用步骤。\n\n\n\n<!-- more -->\n## 安装\n\nReveal可以免费试用14天,如果你不差钱可以买[正版](https://revealapp.com/buy/)支持一下,也就是一年59刀。当然了,如果你不打算这样做,可以去下载[破解版](http://xclient.info/s/reveal.html)。\n## 接入自己项目\nReveal可以接入自己的项目,也可以通过逆向查看其它APP,这里主要介绍Reveal如何连接模拟器及真机。\nReveal接入项目有三种方法:\n\n```\n1.通过CocoaPods导入SDK接入\n2.通过Xcode断点接入\n3.通过导入framework接入\n```\n这里的第一种和最后一种都不太合适,对项目造成了侵入,所以我毫不犹豫选择了第二种,只需要添加一个断点,并简单配置一下就可以。\n\n### 通过断点连接\n首先,打开Xcode,添加一个断点,如下:\n\n\n然后编辑断点,配置成如下图所示:\n\n\n\n`Debugger Command`下面一栏需要填上\n\n```\n expr (Class)NSClassFromString(@\"IBARevealLoader\") == nil ? (void *)dlopen(\"/Applications/Reveal.app/Contents/SharedSupport/iOS-Libraries/RevealServer.framework/RevealServer\", 0x2) : ((void*)0)\n```\n这里需要注意如果你使用的是Reveal4,你可以使用这一段代码,如果是其他版本会不一样。\n使用模拟器运行项目,打开Reveal,如果看到这种情况,那就成功一大步。\n\n\n\n如果你很不幸,没有看到这个图标,也不要灰心,点击下面这个,会有官方提供的解决办法。\n\n\n\n这里需要注意的是,不同的Reveal版本,点击后跳转的官方网页内容并不一样,连接方法稍有区别,仔细看官方的说明即可。\n\n\n\n\n如果你遇到了这个问题,说明你本机的hosts文件被更改了,可以使用[SwitchHosts](https://github.com/oldj/SwitchHosts/downloads)更改一下,如图。\n\n\n具体配置:\n\n```\n127.0.0.1 localhost\n255.255.255.255 broadcasthost\n::1 localhost \n```\n具体的内容可以看一下[这个博客](http://www.cnblogs.com/fengtengfei/p/5100005.html)。上面说的这些可以连接模拟器,至于真机,Reveal4暂时没有发现使用断点连接的办法,Reveal7则可以,需要在项目中增加一段脚本。可以仔细阅读官网的[Load the Reveal Server via an Xcode Breakpoint](http://support.revealapp.com/kb/getting-started/load-the-reveal-server-via-an-xcode-breakpoint),这篇文章是关于Reveal7的,跟上面所述会有些不同。\n## 其他\n由于之前用Reveal试用版30天,最后导致破解版无法使用,一打开APP就弹出激活框,折腾了好久,用Clean my mac删除也不行,后来无意间我发现在`/Users/Shared/Reveal`这里居然有个`Reveal`文件夹,打开一看,卧槽,这里放的就是激活许可相关的那个文件,心里一万只可爱的小动物飞过😭,小婊砸,二话不说,直接把这个文件干掉,从此又可以愉快的使用破解版啦😝。\n\n## 最后\n最后,特别想吐槽一下Reveal,虽然好用,但是配置起来很闹心,各种踩坑,如果你遇到什么坑,一定要告诉我哦,祝大家踩坑愉快!\n\n","source":"_posts/2017-03-04-iOS开发神器Reveal使用指南.md","raw":"---\nlayout: post\ntitle: \"iOS开发神器Reveal使用指南\"\ndate: 2017-03-04\ncomments: true\ncategories: Mac工具\ntags: [Mac工具]\nkeywords: iOS开发神器Reveal使用指南\npublish: true\ndescription: iOS开发神器Reveal使用指南\n---\n>作为一名iOS开发者,想必Reveal大家都是知道的。它提供的视图层次浏览功能,给开发过程中定位错误带来了极大的便利,甚至可以通过越狱设备逆向别人的APP,浏览其他APP的视图结构。自从前阵子升级到Xcode8.x之后,Reveal1.6.3就再也用不了了,起初以为是系统兼容性问题,后来等到了Reveal2这个蛋疼的问题依然没解决,最近总算是成功的解决了这个问题,现在Reveal7已经出来了,不得不说,这个版本号真的是醉了,跟坐火箭一样。Reveal的官网在[这里](https://revealapp.com/),由于Reveal版本号更新太快,不同版本之间的接入操作会有一些差异,如果使用中遇到麻烦,一定要找对应版本的解决办法,这里就以Reveal4为例介绍一下使用步骤。\n\n\n\n<!-- more -->\n## 安装\n\nReveal可以免费试用14天,如果你不差钱可以买[正版](https://revealapp.com/buy/)支持一下,也就是一年59刀。当然了,如果你不打算这样做,可以去下载[破解版](http://xclient.info/s/reveal.html)。\n## 接入自己项目\nReveal可以接入自己的项目,也可以通过逆向查看其它APP,这里主要介绍Reveal如何连接模拟器及真机。\nReveal接入项目有三种方法:\n\n```\n1.通过CocoaPods导入SDK接入\n2.通过Xcode断点接入\n3.通过导入framework接入\n```\n这里的第一种和最后一种都不太合适,对项目造成了侵入,所以我毫不犹豫选择了第二种,只需要添加一个断点,并简单配置一下就可以。\n\n### 通过断点连接\n首先,打开Xcode,添加一个断点,如下:\n\n\n然后编辑断点,配置成如下图所示:\n\n\n\n`Debugger Command`下面一栏需要填上\n\n```\n expr (Class)NSClassFromString(@\"IBARevealLoader\") == nil ? (void *)dlopen(\"/Applications/Reveal.app/Contents/SharedSupport/iOS-Libraries/RevealServer.framework/RevealServer\", 0x2) : ((void*)0)\n```\n这里需要注意如果你使用的是Reveal4,你可以使用这一段代码,如果是其他版本会不一样。\n使用模拟器运行项目,打开Reveal,如果看到这种情况,那就成功一大步。\n\n\n\n如果你很不幸,没有看到这个图标,也不要灰心,点击下面这个,会有官方提供的解决办法。\n\n\n\n这里需要注意的是,不同的Reveal版本,点击后跳转的官方网页内容并不一样,连接方法稍有区别,仔细看官方的说明即可。\n\n\n\n\n如果你遇到了这个问题,说明你本机的hosts文件被更改了,可以使用[SwitchHosts](https://github.com/oldj/SwitchHosts/downloads)更改一下,如图。\n\n\n具体配置:\n\n```\n127.0.0.1 localhost\n255.255.255.255 broadcasthost\n::1 localhost \n```\n具体的内容可以看一下[这个博客](http://www.cnblogs.com/fengtengfei/p/5100005.html)。上面说的这些可以连接模拟器,至于真机,Reveal4暂时没有发现使用断点连接的办法,Reveal7则可以,需要在项目中增加一段脚本。可以仔细阅读官网的[Load the Reveal Server via an Xcode Breakpoint](http://support.revealapp.com/kb/getting-started/load-the-reveal-server-via-an-xcode-breakpoint),这篇文章是关于Reveal7的,跟上面所述会有些不同。\n## 其他\n由于之前用Reveal试用版30天,最后导致破解版无法使用,一打开APP就弹出激活框,折腾了好久,用Clean my mac删除也不行,后来无意间我发现在`/Users/Shared/Reveal`这里居然有个`Reveal`文件夹,打开一看,卧槽,这里放的就是激活许可相关的那个文件,心里一万只可爱的小动物飞过😭,小婊砸,二话不说,直接把这个文件干掉,从此又可以愉快的使用破解版啦😝。\n\n## 最后\n最后,特别想吐槽一下Reveal,虽然好用,但是配置起来很闹心,各种踩坑,如果你遇到什么坑,一定要告诉我哦,祝大家踩坑愉快!\n\n","slug":"2017-03-04-iOS开发神器Reveal使用指南","published":1,"updated":"2017-03-22T14:11:14.000Z","_id":"cj0l1ptb3000s0er9g8s2e4o3","photos":[],"link":"","content":"<blockquote>\n<p>作为一名iOS开发者,想必Reveal大家都是知道的。它提供的视图层次浏览功能,给开发过程中定位错误带来了极大的便利,甚至可以通过越狱设备逆向别人的APP,浏览其他APP的视图结构。自从前阵子升级到Xcode8.x之后,Reveal1.6.3就再也用不了了,起初以为是系统兼容性问题,后来等到了Reveal2这个蛋疼的问题依然没解决,最近总算是成功的解决了这个问题,现在Reveal7已经出来了,不得不说,这个版本号真的是醉了,跟坐火箭一样。Reveal的官网在<a href=\"https://revealapp.com/\" target=\"_blank\" rel=\"external\">这里</a>,由于Reveal版本号更新太快,不同版本之间的接入操作会有一些差异,如果使用中遇到麻烦,一定要找对应版本的解决办法,这里就以Reveal4为例介绍一下使用步骤。</p>\n</blockquote>\n<p><img src=\"http://om6homgqk.bkt.clouddn.com/WX20170304-180852@2x.png\" alt=\"Reveal\"></p>\n<a id=\"more\"></a>\n<h2 id=\"安装\"><a href=\"#安装\" class=\"headerlink\" title=\"安装\"></a>安装</h2><p>Reveal可以免费试用14天,如果你不差钱可以买<a href=\"https://revealapp.com/buy/\" target=\"_blank\" rel=\"external\">正版</a>支持一下,也就是一年59刀。当然了,如果你不打算这样做,可以去下载<a href=\"http://xclient.info/s/reveal.html\" target=\"_blank\" rel=\"external\">破解版</a>。</p>\n<h2 id=\"接入自己项目\"><a href=\"#接入自己项目\" class=\"headerlink\" title=\"接入自己项目\"></a>接入自己项目</h2><p>Reveal可以接入自己的项目,也可以通过逆向查看其它APP,这里主要介绍Reveal如何连接模拟器及真机。<br>Reveal接入项目有三种方法:</p>\n<figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div></pre></td><td class=\"code\"><pre><div class=\"line\">1.通过CocoaPods导入SDK接入</div><div class=\"line\">2.通过Xcode断点接入</div><div class=\"line\">3.通过导入framework接入</div></pre></td></tr></table></figure>\n<p>这里的第一种和最后一种都不太合适,对项目造成了侵入,所以我毫不犹豫选择了第二种,只需要添加一个断点,并简单配置一下就可以。</p>\n<h3 id=\"通过断点连接\"><a href=\"#通过断点连接\" class=\"headerlink\" title=\"通过断点连接\"></a>通过断点连接</h3><p>首先,打开Xcode,添加一个断点,如下:</p>\n<p><img src=\"http://om6homgqk.bkt.clouddn.com/断点.png\" alt=\"添加断点\"><br>然后编辑断点,配置成如下图所示:</p>\n<p><img src=\"http://om6homgqk.bkt.clouddn.com/编辑断点.png\" alt=\"编辑断点\"></p>\n<p><code>Debugger Command</code>下面一栏需要填上</p>\n<figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div></pre></td><td class=\"code\"><pre><div class=\"line\">expr (Class)NSClassFromString(@"IBARevealLoader") == nil ? (void *)dlopen("/Applications/Reveal.app/Contents/SharedSupport/iOS-Libraries/RevealServer.framework/RevealServer", 0x2) : ((void*)0)</div></pre></td></tr></table></figure>\n<p>这里需要注意如果你使用的是Reveal4,你可以使用这一段代码,如果是其他版本会不一样。<br>使用模拟器运行项目,打开Reveal,如果看到这种情况,那就成功一大步。</p>\n<p><img src=\"http://om6homgqk.bkt.clouddn.com/success.png\" alt=\"关联成功图标\"></p>\n<p>如果你很不幸,没有看到这个图标,也不要灰心,点击下面这个,会有官方提供的解决办法。</p>\n<p><img src=\"http://om6homgqk.bkt.clouddn.com/点击去官网.png\" alt=\"官方解决问题\"></p>\n<p>这里需要注意的是,不同的Reveal版本,点击后跳转的官方网页内容并不一样,连接方法稍有区别,仔细看官方的说明即可。<br><img src=\"http://om6homgqk.bkt.clouddn.com/reveal解决问题指导.png\" alt=\"官方解决问题指导\"></p>\n<p><img src=\"http://om6homgqk.bkt.clouddn.com/最后一个错误.png\" alt=\"Hosts问题\"></p>\n<p>如果你遇到了这个问题,说明你本机的hosts文件被更改了,可以使用<a href=\"https://github.com/oldj/SwitchHosts/downloads\" target=\"_blank\" rel=\"external\">SwitchHosts</a>更改一下,如图。</p>\n<p><img src=\"http://om6homgqk.bkt.clouddn.com/hosts.png\" alt=\"更改Hosts\"><br>具体配置:</p>\n<figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div></pre></td><td class=\"code\"><pre><div class=\"line\">127.0.0.1 localhost</div><div class=\"line\">255.255.255.255 broadcasthost</div><div class=\"line\">::1 localhost</div></pre></td></tr></table></figure>\n<p>具体的内容可以看一下<a href=\"http://www.cnblogs.com/fengtengfei/p/5100005.html\" target=\"_blank\" rel=\"external\">这个博客</a>。上面说的这些可以连接模拟器,至于真机,Reveal4暂时没有发现使用断点连接的办法,Reveal7则可以,需要在项目中增加一段脚本。可以仔细阅读官网的<a href=\"http://support.revealapp.com/kb/getting-started/load-the-reveal-server-via-an-xcode-breakpoint\" target=\"_blank\" rel=\"external\">Load the Reveal Server via an Xcode Breakpoint</a>,这篇文章是关于Reveal7的,跟上面所述会有些不同。</p>\n<h2 id=\"其他\"><a href=\"#其他\" class=\"headerlink\" title=\"其他\"></a>其他</h2><p>由于之前用Reveal试用版30天,最后导致破解版无法使用,一打开APP就弹出激活框,折腾了好久,用Clean my mac删除也不行,后来无意间我发现在<code>/Users/Shared/Reveal</code>这里居然有个<code>Reveal</code>文件夹,打开一看,卧槽,这里放的就是激活许可相关的那个文件,心里一万只可爱的小动物飞过😭,小婊砸,二话不说,直接把这个文件干掉,从此又可以愉快的使用破解版啦😝。</p>\n<h2 id=\"最后\"><a href=\"#最后\" class=\"headerlink\" title=\"最后\"></a>最后</h2><p>最后,特别想吐槽一下Reveal,虽然好用,但是配置起来很闹心,各种踩坑,如果你遇到什么坑,一定要告诉我哦,祝大家踩坑愉快!</p>\n","excerpt":"<blockquote>\n<p>作为一名iOS开发者,想必Reveal大家都是知道的。它提供的视图层次浏览功能,给开发过程中定位错误带来了极大的便利,甚至可以通过越狱设备逆向别人的APP,浏览其他APP的视图结构。自从前阵子升级到Xcode8.x之后,Reveal1.6.3就再也用不了了,起初以为是系统兼容性问题,后来等到了Reveal2这个蛋疼的问题依然没解决,最近总算是成功的解决了这个问题,现在Reveal7已经出来了,不得不说,这个版本号真的是醉了,跟坐火箭一样。Reveal的官网在<a href=\"https://revealapp.com/\">这里</a>,由于Reveal版本号更新太快,不同版本之间的接入操作会有一些差异,如果使用中遇到麻烦,一定要找对应版本的解决办法,这里就以Reveal4为例介绍一下使用步骤。</p>\n</blockquote>\n<p><img src=\"http://om6homgqk.bkt.clouddn.com/WX20170304-180852@2x.png\" alt=\"Reveal\"></p>","more":"<h2 id=\"安装\"><a href=\"#安装\" class=\"headerlink\" title=\"安装\"></a>安装</h2><p>Reveal可以免费试用14天,如果你不差钱可以买<a href=\"https://revealapp.com/buy/\">正版</a>支持一下,也就是一年59刀。当然了,如果你不打算这样做,可以去下载<a href=\"http://xclient.info/s/reveal.html\">破解版</a>。</p>\n<h2 id=\"接入自己项目\"><a href=\"#接入自己项目\" class=\"headerlink\" title=\"接入自己项目\"></a>接入自己项目</h2><p>Reveal可以接入自己的项目,也可以通过逆向查看其它APP,这里主要介绍Reveal如何连接模拟器及真机。<br>Reveal接入项目有三种方法:</p>\n<figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div></pre></td><td class=\"code\"><pre><div class=\"line\">1.通过CocoaPods导入SDK接入</div><div class=\"line\">2.通过Xcode断点接入</div><div class=\"line\">3.通过导入framework接入</div></pre></td></tr></table></figure>\n<p>这里的第一种和最后一种都不太合适,对项目造成了侵入,所以我毫不犹豫选择了第二种,只需要添加一个断点,并简单配置一下就可以。</p>\n<h3 id=\"通过断点连接\"><a href=\"#通过断点连接\" class=\"headerlink\" title=\"通过断点连接\"></a>通过断点连接</h3><p>首先,打开Xcode,添加一个断点,如下:</p>\n<p><img src=\"http://om6homgqk.bkt.clouddn.com/断点.png\" alt=\"添加断点\"><br>然后编辑断点,配置成如下图所示:</p>\n<p><img src=\"http://om6homgqk.bkt.clouddn.com/编辑断点.png\" alt=\"编辑断点\"></p>\n<p><code>Debugger Command</code>下面一栏需要填上</p>\n<figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div></pre></td><td class=\"code\"><pre><div class=\"line\">expr (Class)NSClassFromString(@"IBARevealLoader") == nil ? (void *)dlopen("/Applications/Reveal.app/Contents/SharedSupport/iOS-Libraries/RevealServer.framework/RevealServer", 0x2) : ((void*)0)</div></pre></td></tr></table></figure>\n<p>这里需要注意如果你使用的是Reveal4,你可以使用这一段代码,如果是其他版本会不一样。<br>使用模拟器运行项目,打开Reveal,如果看到这种情况,那就成功一大步。</p>\n<p><img src=\"http://om6homgqk.bkt.clouddn.com/success.png\" alt=\"关联成功图标\"></p>\n<p>如果你很不幸,没有看到这个图标,也不要灰心,点击下面这个,会有官方提供的解决办法。</p>\n<p><img src=\"http://om6homgqk.bkt.clouddn.com/点击去官网.png\" alt=\"官方解决问题\"></p>\n<p>这里需要注意的是,不同的Reveal版本,点击后跳转的官方网页内容并不一样,连接方法稍有区别,仔细看官方的说明即可。<br><img src=\"http://om6homgqk.bkt.clouddn.com/reveal解决问题指导.png\" alt=\"官方解决问题指导\"></p>\n<p><img src=\"http://om6homgqk.bkt.clouddn.com/最后一个错误.png\" alt=\"Hosts问题\"></p>\n<p>如果你遇到了这个问题,说明你本机的hosts文件被更改了,可以使用<a href=\"https://github.com/oldj/SwitchHosts/downloads\">SwitchHosts</a>更改一下,如图。</p>\n<p><img src=\"http://om6homgqk.bkt.clouddn.com/hosts.png\" alt=\"更改Hosts\"><br>具体配置:</p>\n<figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div></pre></td><td class=\"code\"><pre><div class=\"line\">127.0.0.1 localhost</div><div class=\"line\">255.255.255.255 broadcasthost</div><div class=\"line\">::1 localhost</div></pre></td></tr></table></figure>\n<p>具体的内容可以看一下<a href=\"http://www.cnblogs.com/fengtengfei/p/5100005.html\">这个博客</a>。上面说的这些可以连接模拟器,至于真机,Reveal4暂时没有发现使用断点连接的办法,Reveal7则可以,需要在项目中增加一段脚本。可以仔细阅读官网的<a href=\"http://support.revealapp.com/kb/getting-started/load-the-reveal-server-via-an-xcode-breakpoint\">Load the Reveal Server via an Xcode Breakpoint</a>,这篇文章是关于Reveal7的,跟上面所述会有些不同。</p>\n<h2 id=\"其他\"><a href=\"#其他\" class=\"headerlink\" title=\"其他\"></a>其他</h2><p>由于之前用Reveal试用版30天,最后导致破解版无法使用,一打开APP就弹出激活框,折腾了好久,用Clean my mac删除也不行,后来无意间我发现在<code>/Users/Shared/Reveal</code>这里居然有个<code>Reveal</code>文件夹,打开一看,卧槽,这里放的就是激活许可相关的那个文件,心里一万只可爱的小动物飞过😭,小婊砸,二话不说,直接把这个文件干掉,从此又可以愉快的使用破解版啦😝。</p>\n<h2 id=\"最后\"><a href=\"#最后\" class=\"headerlink\" title=\"最后\"></a>最后</h2><p>最后,特别想吐槽一下Reveal,虽然好用,但是配置起来很闹心,各种踩坑,如果你遇到什么坑,一定要告诉我哦,祝大家踩坑愉快!</p>"},{"layout":"post","title":"《Effective Objective-C 2.0:编写高质量iOS与OS X代码的52个有效方法》笔记","date":"2017-01-21T16:00:00.000Z","comments":1,"keywords":"编写高质量iOS与OS X代码的52个有效方法","publish":true,"description":"编写高质量iOS与OS X代码的52个有效方法","_content":"写出优雅高效的代码是每个程序员的最高追求,最近静下心里细细的品味一下一些提高代码质量的技巧,与君共勉之。\n<!-- more -->\n\n## 熟悉Objective-C\n\n### 了解Objective-C语言的起源\n\n1、区别于C++, Java等面向对象的语言,Objective-C在 运行中是“消息转发”而非“函数调用”,运行时所执行的代码由运行环境决定,而非编译器决定。\n2、NSString *someString = @\"The string\"; someString指针变量被分配在“栈帧”中,@“The string”对象则被分配在“堆空间”中,分配在堆中的内存必须直接管理,而分配在栈上用于保存变量的内存则会在其“栈帧”自动弹出时清理。在Objective-C中,内存管理指的是堆上的这部分内存。\n\n### 在类的头文件中尽量少引用其他头文件\n\n1、不要为了省事,直接在头文件中引用其他类的头文件,将头文件引入的时间尽量延后,可以用\"@class\"来声明类,减少编译器的负担。\n2、如果两个类互相引入对方的头文件会造成“循环引用”,无法正常编译。经测试:只互相引用头文件可正常编译,但是如果在类里面使用对方头文件变量时,就无法编译通过。\n3、某个类如果要实现某个协议,尽量把协议的声明写在“类扩展”,即\".m\"文件的\"@interface xxx<XXXDelegate> @end\",如果实在不行,那就最好吧协议单独放在一个头文件中,然后将其引入。\n\t\n### 多用字面量语法,少用与之等价的方法\n\n好处:\n1、书写简洁,便于阅读。\n2、使用字面量数组时可以更快的抛出异常,更加安全。\n局限性:\n1、自定义创建子类的实例,需要采取“非字面量语法”。\n### 多用类型常量,少用#define预处理指令\n\n<del>#define ANIMATION_DURATION 0.3</del>\n\n```\nstatic const NSTimeInterval kAnimationDuration = 0.3\n```\n\n1、如果不打算公开变量,可在.m文件中,同时使用static和const来定义常量,如果试图修改该变量编译器就会报错。这种变量只在编译单元内可见,由于不在”全局符号表“中所以无需增加前缀。\n2、如果打算公开某个常量,则需要这样来实现\n```\n// EOCAnimatedView.h\nextern const NSTimerInterval EOCAnimatedViewAnimationDuration;\n// EOCAnimatedView.m\nconst NSTimerInterval EOCAnimatedViewAnimationDuration = 0.3;\n```\n\t\n在头文件中声明,在实现文件中定义,由于在”全局符号表“中,为避免名称冲突,最好用与之相关的类名作为前缀。这样定义常量是不可被更改的,而使用#define预处理指令定义的常量很可能遭到别人的无意更改,这是非常危险的事情。\n\t\n### 多用类型常量,少用#define预处理指令\n1、使用NS_ENUM与NS_OPTIONS宏来定义枚举类型并指明其数据结构。\n2、应该用枚举来表示状态机的状态,状态码等值。\n3、如果枚举的多个选项可以同时组合,将这些项定义为2的幂,以便可以通过按位或操作将其组合起来。\n例如:AnimationEasyIn | AnimationLeft\n```\ntypedef NS_ENUM(NSUInteger, AnimationBehavior) {\nAnimationEasyIn = 1 << 0,\nAnimationLeft = 1 << 1\n};\n```\n4、处理枚举类型的switch语句中不要实现default分支,这样的话有新枚举加入,编译器就会提示开发者,switch语句中并未处理所有的枚举。\n## 对象、消息、运行期\n### 理解“属性”这一概念\n1、尽量不要直接定义实例变量,推荐使用属性\"@proproty\"来合成存取方法。使用点语法调用来访问变量。\n2、在设置属性所对应的实例变量时,一定要遵循该属性所声明的语义。\n即:\n```\n@property (nonatomic, copy)NSString *name;\n\t\n- (void)setName:(NSString *)name\n{\n _name = [name copy];\n}\n疑问:\n- (void)setName:(NSString *)name\n{\n // _name = [name copy];\n _name = name;\n}\n```\n经过测试,使用_name = name,和上面的效果是一样的,内存地址发生了变化。\n### 在对象内部尽量直接访问实例变量\n强烈建议在读取实例变量时候采用直接访问的形式,而在设置实例变量的时候通过属性来做。\n\n理由:\n1、直接访问属性,而不经过存取方法,直接访问那块内存,速度当然比较快,但是可以忽略不计。\n2、直接访问属性就绕过了如“strong”、“copy”,等“管理语义”,如果在ARC下直接访问一个声明为copy的对象,并不会拷贝改属性,只会保留新值并释放旧值。\n3、直接访问实例变量,不会触发“KVO”,\n合理的方案:\n在对象内部读取数据时,直接通过实例变量来读,在写入数据时,通过属性来写。\n注意:\n1、在初始化方法和dealloc方法中,应该直接访问实例变量,防止子类覆盖设置方法。\n2、懒加载中,通过获取方法来访问属性,否则实例变量永远不会被初始化。\n```\n- (Person *)person {\n\tif (!_person) {\n\t\t_person = [Person alloc] init];\n\t}\n\treturn _person;\n}\n```\n\n### 理解“对象等同性”这一概念\n1、重写isEqual和hash方法,判断对象的等同性。\n2、利用标识符,类似于数据库的主键,来判断对象的等同性。\n3、容器中放入可变对象时,慎重改变其哈希码,如:NSMutableSet中加入NSMutableArray。\n4、不盲目地检查每条属性,按照具体需求来制定检测对象。\n5、相同的对象必须具有相同的哈希码,但是哈希码相同的对象未必相同。\n6、编写hash方法时,应该使用计算速度快而且哈希码碰撞几率低的算法。\n\n[哈希介绍](https://zh.wikipedia.org/wiki/%E5%93%88%E5%B8%8C%E8%A1%A8)\n[Equality](http://nshipster.cn/equality/)\n\n### 以“类族模式”隐藏实现细节\n1、使用类方法创建实例,如:+ (UIButton *)buttonWithType:\n2、从类族的公共抽象基类中继承子类时要当心,子类应当覆写父类中指明需要覆写的方法\n### 在既有类中使用关联对象存放自定义数据\n“关联对象\"(Associated Object),可以在外部给类添加属性,常用在Category中添加。\n### 理解objc_msgSend的作用\n1、“静态绑定”编译器在编译阶段就能生成调用函数指令,“动态绑定”运行期才可以生成函数调用指令。\n2、objc_msgSend函数会在接收者所属类中的“方法列表”中寻找符合的方法,如果找到就执行实现代码,如果找不到,就沿着继承体系,向上继续寻找,如果最终还是找不到,就执行“消息转发操作”,此处可进行手动拦截。\n3、尾调用优化对于递归具有重要意义,大大减少调用栈的调用记录,防止栈溢出。\n\t\n[尾调用优化](http://www.ruanyifeng.com/blog/2015/04/tail-call.html)\n### 理解消息转发机制\n1、运行时系统没有找到消息的接收者,会发起消息转发,给接收者最后一次机会,所有的细节封装在NSInvocation对象中,在此可以进行拦截处理。\n2、对象无法收到解读的消息后,首先调用其所属类的类方法:\n第一步:\n+ (BOOL)resolveInstanceMethod:(SEL)selector 此处可以使用class_addMethod()添加新方法。\n第二步:为消息寻找一个备用的接收者,但无法操作这一步的消息。\n- (id)forwardingTargetForSelector:(SEL)selector \n第三步:若发现某调用操作不应该由本类处理,则需要调用超类的同名方法,这样,继承体系的每个子类都有机会处理此调用请求,直至NSObject,如果最后调用了NSObject的方法,会抛出异常,表明消息未得到处理。\n- (void)forwardingInvocation:(NSInvocation *)invocation\n\n### 用“方法调配技术”测试“黑盒方法”\n在运行期,通过runtime向类中添加或者交换方法实现。\n### 理解“类对象”的用意\n1、如果类型无法在编译器确定,那么就应该使用类型信息查询方法来探知。isMemberOfClass:判断对象是否为某个类的实例,isKindOfClass:判断对象是否为某个类或者其子类的实例。\n2、尽量使用类型信息确定对象类型,不要直接比较类对象,因为某些对象可能实现了消息转发功能。\n如:\t\n<del>if([object class] == [Person class]){\n}<del>\n```\nif([object isMemberOfClass:[Person class]] {\n}\n```\n\n## 接口与API设计\n### 用前缀避免命名空间冲突\n1、选择与你公司,应用程序或者与之相关的名称作为类名前缀,并在所有代码中统一所有前缀。\n2、在Category中给变量,方法添加前缀。\n3、若自己所开发的程序中用到了第三方库,则应为其中的名称加上前缀。\n4、所选的前缀应为三个字母(苹果规定的)。\n### 提供全能的初始化方法\n1、在类中提供一个全能的初始化方法,供其他初始化方法调用。\n2、若全能初始化方法与超类的不同,则需要覆写超类中对应的方法。\n3、如果超类的初始化方法不适用于子类,那么应该覆写这个超类方法,并在其中抛出异常。\n```\n-(id)initWithWidth:(float)width andHeight:(float)height\n{\n @throw [NSException exceptionWithName:...];\n}\n```\n\n### 实现description方法\n1、实现description方法返回一串有意义的字符串,来描述该对象,使用NSLog()打印对象时调用。\n2、实现debugDescription方法返回一串有意义的字符串,来描述该对象,在开发者断点调试通过LLDB命令po对象时调用。\n### 尽量使用不可变对象\n1、尽量把对外部公布出去的属性设置为只读(readonly)\n2、如果想修改封装在对象内部的数据,但是又不想别人在外部修改,这时需要在.m文件中重新把属性声明为readwrite,但是这样会产生“竞态条件”,需要将对象的所有数据进行同步,参见41条。\n3、通过KVC仍可以修改只读属性的值,这时不符合API规范的。\n4、不要把可变的集合对象作为属性公开,而是提供相应的方法修改集合对象。\n### 使用清晰而协调的命名方式\n1、尽量使用长方法名,清晰的说明方法的意思,但是也要尽量言简意赅,可参考UIKit命名规范。\n\n<del>-(id)initWithSize:(float)width :(float)height<del>\n```\n-(id)initWithWidth:(float)width andHeight:(float)height\n```\n\n### 为私有方法名加前缀\n1、给私有方法的名称加上前缀,便于跟公共方法区分。\n2、不能用单一下划线做前缀,这是苹果私有API的前缀,会冲突。\n### 理解Objective-C错误模型\n1、“-fojc-arc-exception”编译标识可以在执行异常代码时不抛出异常\n2、异常用于处理致命问题,无需考虑恢复问题,应用程序直接退出,非致命问题使用NSError对象。\n3、通过“输出参数”方式把NSError对象回传给调用者\n``` \nNSError *error = nil;\nBOOL ret = [object doSomething:&error];\nif (ret) {\n // There was an error\n}\n- (Bool)doSomething:(NSError **)error {\n if (// there was an error) {\n if (error) {\n *error = [NSError errorWithDomain:...];\n }\n return NO;\n } else {\n return YES;\n }\n}\n```\n \n在error要指向一个新的对象时(解引用),必须先保证error参数不是nil,因为空指针解引用会导致“段错误”,并使应用程序崩溃。调用者在不关心具体错误时,会给error参数传入nil,因此必须判断这种情况。\n### 理解NSCopying协议\n1、想让自定义对象具有拷贝功能,需要实现NSCopying协议。 \n2、对象拷贝分为深拷贝和浅拷贝,一般情况下尽量执行浅拷贝。\n3、如果对象需要深拷贝,可以考虑增加一个专门执行深拷贝的方法。\n4、如果自定义对象分为可变和不可变版本,需要同时实现NSCopying和NSMutableCopying协议。\n\n## 协议与分类\n### 通过委托与数据源协议进行对象间通信\n1、委托模式为对象提供一套接口,通过接口可将相关事件告知其他对象。\n2、将委托对象应该支持的接口定义成协议,在协议中将可能需要处理的事件定义为方法。\n3、当使用委托模式传递数据时,该模式也叫“数据源协议”,如UITableViewDataSource\n4、使用“位域”(含有位段的结构体),将委托对象是否响应相关协议的信息缓存其中。\n```\nstruct {\n unsigned int didReceiveData : 1;\n unsigned int didFailWithError : 1;\n unsigned int didUpdateProgressTo : 1;\n} _delegateFlags;\n \n- (void)setDelegate:(id<...>)delegate {\n _delegateFlags.didReceiveData = [delegate respondsToSelector:@selctor(...)];\n}\n \nif (_delegateFlags.didReceiveData) {\n [_delegate ....];\n}\n```\n\n### 将类的实现代码分散到便于管理的数个分类之中\n1、使用分类机制把类的实现代码划分成易于管理的小块。\n2、将应该私有的方法归入名叫Private的分类中,以隐藏实现细节。\n### 总是为第三方类的分类名称加前缀\n1、如果多个分类重载“主实现”的相关方法,以最后一个分类为主,即:分类在项目中编译的顺序。\n2、以命名空间来区分分类中所定义的方法,三个小写字母加下划线:abc_xxx\n### 请勿在分类中声明属性\n1、分类不可以定义属性,如果非要这么做,可以使用“关联对象”。\n2、把封装数据所用的全部属性都定义在主类中。\n3、可以定义存取方法但是尽量不要定义属性。\n### 使用“class-continuation分类”隐藏实现细节\n“class-continuation分类”也叫“类扩展”。\n1、通过“class-continuation分类”,向类中增加实例变量。\n2、私有方法声明在“class-continuation分类”中。\n3、私有的协议也可以声明在“class-continuation分类”中。\n### 通过协议提供匿名对象\n1、协议可以在某种程度上提供匿名类型,具体对象类型可以淡化为遵从某一协议的id类型,协议里规定了对象所应该实现的方法。\n2、使用匿名对象id<xxx>来隐藏类型名称。\n3、如果具体类型不重要,重要的是对象能够响应协议里的特定方法,那么可以用匿名对象来表示。也就是说,只暴露使用者关心的,隐藏其不需要关注的。\n## 内存管理\n### 理解引用计数器\n1、非ARC通过引用计数器增减来管理内存,对象创建好之后,引用计数器至少为1,若引用计数为正,对 象继续存活,当保留计数降为0时,对象就被销毁了。\n2、在对象生命周期中,其他对象通过引用来保留或者释放此对象,保留与释放操作分别会使引用计数递增和递减。\n3、不要操作“悬挂指针”(野指针),会引起崩溃,最好将其变为“空指针”。\n4、set方法 strong retain新值,release旧值,然后赋值。\n5、autoreleasepool能延长对象生命期,在下次运行循环或者更早一些release对象。\n6、使用“弱引用”可以防止循环引用。\n### 以ARC简化引用计数\n1、ARC会自动补上引用计数代码,但是并没有使用Objective-C的消息转发,而是直接通过C代码,性能会更好。\n2、ARC只管理Objective-C对象的内存,CoreFoundation对象不归ARC管理,开发者必须适时调用CFRetain/CFRelease。\n3、ARC对引用计数进行了特殊优化,如果发现对象在运行期进行多次保留和释放操作,会成对的移除这些操作,只保留有用操作,从而提高效率。\n4、ARC对存取方法进行了优化,不需要再去关注先保留新值,再释放旧值,直接赋值即可。\n5、ARC借助Objective-C++的特性清理对象,回收Objective-C对象调用多有C++对象的“析构函数\",如发现某个对象里面有C++对象,会生成.cxx_destruct的方法,并在该方法中生成清理内存所需代码。如果有非Objective-C对象(CoreFoundation对象或者malloc()分配的堆内存),不会调用父类的dealloc方法,会生成.cxx_destruct的方法,并在该方法中生成清理内存所需代码,在生成的代码中自动调用父类的dealloc方法。因此可以这样写:\n```\n-(void)dealloc {\n CFRelease(...);\n free(...);\n}\n```\n\n### 在dealloc方法中只释放引用并解除监听\n1、可以在dealloc方法中注销通知观察者等。\n2、比如文件,套接字,大块内存等开销较大或者系统内稀缺资源不可以在dealloc方法中释放,需要用完即释放。\n3、系统并不能保证每个创建的对象的dealloc方法都会调用,个别对象在应用程序终止时仍处于存活状态,由于应用程序终止,将内存返还给操作系统,所以实际上这些对象也算是销毁了。所以在系统回收之前我们可以手动清理这些对象,在UIApplicationDelegate/NSApplicationDelegate的委托方法中处理比较合适。\n4、不要再dealloc方法中随便调用别的方法,存取方法也不要调用,因为这样可能会触发观察者,还是使用下划线比较稳妥。\n### 编写”异常安全代码“时留意内存管理问题\n1、捕获异常时,一定要将try块内的对象清理干净。\n2、在默认情况下,ARC不生成安全处理异常所需的清理代码,开启”-fobjc-arc-exceptions“标识后,可生成这种代码,不过会导致应用程序变大,而且会降低运行效率。\n3、如果发现大量异常捕获操作时,考虑使用NSError错误传递来重构。\n### 以弱引用避免保留环\n1、某些引用设置为weak可以避免出现”保留环“(循环引用)。\n2、weak与unsafe_unretained的区别:\n相同:都是弱引用,用来表示”非拥有关系“。\n不同:weak 系统如果把属性回收,属性自动设置为nil;unsafe_unretained 系统如果把属性回收,属性仍然指向那个已经回收的实例,也就是”野指针“,继续操作属性会使程序崩溃,\n总的来说,weak更加安全一些,但是性能比unsafe_unretained低些。\n3、一般来说,如果不拥有某个对象就不要去保留它。这条规则对集合类对象例外,因为集合类对象并不直接拥有其内容,而是通过自己内部的元素来保留这个对象。使用weak尽量也不要去使用一个已经释放的弱引用对象,尽管不会崩溃,但是这依然是一个bug。\n### 以”自动释放池块“降低内存峰值\n1、自动释放池排布在栈中,对象收到autorelease消息后,系统将其放入最顶端的池里。\n2、合理利用自动释放池可以降低内存峰值,如:在for循环内部使用自动释放池包裹代码。\n3、@autoreleasepool这种写法可以创建更轻便的自动释放池。\n### 用”僵尸对象“调试内存管理问题\n1、系统再回收对象时,可以不将其真的回收,而是把它转化成僵尸对象,通过环境变量NSZombieEnabled可以开启此功能。\n2、系统会修改对象的isa指针,另其指向特殊的僵尸类,从而使该对象变为僵尸对象,僵尸类能够响应所有的选择子,响应方式为:打印一条包含信息内容及接收者的消息,然后终止程序。\n### 不要使用retainCount\n1、在ARC中retainCount方法已经被废弃,因为它只能返回特定时间点的引用计数器,而未考虑系统稍后会吧自动释放池清空的情况。或者是retainCount永远不返回0,因为系统可能会优化对象的释放行为,在引用计数是1的时候就回收对象,引用计数可能永远不会是0,所以引用计数是不准确的,就算能够正常返回时凭运气。\n2、单例对象的引用计数是不会改变的,其保留和释放都是空操作,retainCount已经被废弃了,任何对象的retainCount都是不确定的,所以retainCount绝对不要用。\n## 块与大中枢派发\n### 理解“块”这一概念\n1、默认情况,block所捕获的变量不能被修改,声明变量时加上__block就可以修改。但是类的实例变量不需要加__block即可被修改。\n2、使用block小心因捕获了self而造成循环引用的情况。如果访问了类的实例变量,self也会被捕获。\n3、block可以分配在栈或者堆上,也可以是全局的。分配在栈上的block可以拷贝到堆上,这样的话,就和标准的Objective-C对象一样,具备引用计数了。\n4、全局的block无法捕获任何状态(变量),运行时也无需状态参与,所使用的内存区域在编译时就确定了。\n```\nvoid (^block)() = ^{\n NSLog(\"This is a block!\");\n};\n```\n\n### 为常用的块类型创建typedef\n1、以typedef重新定义block类型,可令块block变量用起来更加简单,可读性更好。\n2、定义新类型时遵循现有命名习惯,不要发生命名冲突。\n3、不妨为同一个block定义多个类型别名,如果要重构的代码使用了block类型的某个别名,那么只需修改相应typedef中的签名即可,无需改动其他typedef。\n### 用handler块降低代码分散程度\n1、使用block来取代delegate可以使代码更加紧凑,便于阅读。\n2、在网络请求的API设计中,尽量用一个handlerl来处理数据及错误,更加灵活。\n推荐:\n```\n[fetcher startWithCompletionHander:^(NSData *data, NSError *error){\n if (error) {\n // failed\n } else {\n // success\n }\n}];\n```\n \n不推荐:\n```\n[fetcher startWithCompletionHandler:^(NSData *data){\n // success\n} failureHandler:^(NSError *error){\n // failed\n}];\n```\n \n3、设计API是如果用到handler块,可以增加一个参数,使调用者可以通过此参数来决定应该把块安排在哪个队列执行。\n### 使用块引用其所属对象时不要出现保留环\n1、如果块所捕获的对象直接或者间接保留了块本身,那么就会造成保留环问题。\n2、一定要找一个适当的时机解除保留环,而不能把责任推给API的调用者。\n以下是两种会出现保留环的写法:\n```\n1、_fetcher捕获了block block捕获了_fetcher\n_fetcher = [[xxx alloc] init];// 属性\n[_fetcher startWithCompletionHander:^(NSData *data, NSError *error){\n NSLog(@\"%@\", fetcher.url);\n _fetchData = data;\n}];\n2、fetcher捕获了block block捕获了fetcher.url\nxxx *fetcher = [[xxx alloc] init];// 临时变量\n[fetcher startWithCompletionHander:^(NSData *data, NSError *error){\n NSLog(@\"%@\", fetcher.url);\n _fetchData = data;\n}];\n```\n\n解决方案:\n1、weakSelf和strongSelf。\n2、在block调用后置为nil。\n### 多用派发队列,少用同步锁\n1、使用锁可以用来实现同步机制,但会带来性能甚至死锁的问题。\n2、将同步与异步派发结合起来,可以实现与普通锁一样的同步行为,而这么做也不会阻塞执行异步派发的线程。\n3、使用同步队列及栅栏块(dispatch_barrier_xxx),可以令同步行为更加高效。\n### 多用GCD,少用performSelector系列方法\n1、使用[object performSelector:@selector(selectorName)]方法可能会造成内存泄漏,ARC不会添加相关的释放操作,因此有可能会造成内存泄漏。\n2、可以使用GCD来代替。\n### 掌握GCD及操作队列的使用时机\n1、GCD并不是最优的办法,在某些情况下使用操作队列(NSOperation)可能会更好一些。\n2、NSOperation的优势:取消某个操作,制定操作的依赖关系,通过KVO监控NSOperation对象属性,指定操作优先级。\n3、GCD基于任务的队列,NSOperation基于操作的队列。\n### 通过Dispatch Group机制,根据系统资源状况来执行任务\n1、一系列任务可放在一个dispatch group中,开发者可以在这组任务执行完获得通知。\n2、通过dispatch group,可以并发执行多项任务,GCD会根据系统资源来调度执行任务。\n### 使用dispatch_once来执行只需运行一次的线程安全代码\n1、使用dispatch_once实现单例可以保证线程安全。\n2、标记声明为static或者global作用域中,这样可以保证执行dispatch_once函数时,传入的标记也是相同的。\n### 不要使用dispatch_get_current_queue\n1、dispatch_get_current_queue已经废弃,最好不要使用,可能会产生死锁问题。\n## 系统框架\n### 熟悉系统框架\n请记住:用纯C写成的框架与用Objective-C写成的一样重要,若想成为优秀的Objective-C开发者,应掌握C语言的核心概念。\n### 多用块枚举,少用for循环\n1、遍历集合有四种方式,最基本的办法是for循环,其次是NSEnumerator遍历法及快速遍历法,最新,最先进的方式是“块枚举法”,也就是block。\n2.“块枚举法”通过GCD并发执行遍历操作,效率较高,推荐使用。\n3、若提前知道待遍历的collection含有何种对象,则应修改块签名,指出对象的类型。\n### 对自定义其内存管理语义的collection使用无缝桥接\n1、__bridge本身意思是:ARC仍然具备这个Objective-C对象的所有权。__bridge_retained则与之相反,意味着ARC交出所有权,后面需要加上CFRelease()以释放对象。\n2、通过无缝桥接技术,可以在Foundation框架中的Objective-C对象与CoreFoundation框架中的C语言数据结构之间来回转换。\n2、在CoreFoundation层面创建collection时,可以指定许多回调函数,这些函数表示此collection应该如何处理元素,然后,可以运用无缝桥接技术,将其转换成具备特殊内存管理语义的Objective-C collection。\n### 构建缓存时选用NSCache而非NSDictionary\n1、NSCache胜过NSDictionary之处在于,当系统资源将要耗尽时,他可以自动删减缓存。NSCache并不会“拷贝”键,而是会”保留“它,而且是线程安全的。\n2、可以给NSCache对象设置上限,用以限制缓存中的对象总个数及“总成本”,而这些尺度则定义了缓存删减其中对象的时机。但是绝对不要把这些尺度当成可靠的“硬限制”,他们仅对NSCache起到指导作用。\n3、将NSPurgeableData与NSCache搭配使用,可实现自动清除数据的功能,也就是说当NSPurgeableData对象所占内存为系统所丢弃时,该对象自身也将从缓存中清除。\n4、如果缓存使用得当,那么应用程序的响应速度就能提高。只有那种“重新计算起来很费事的”数据,才值得放入缓存,比如那些需要从网络获取或者从磁盘中读取的数据。\n### 精简initialize与load的实现代码\n1、+ (void)load 当包含类或者分类的程序载入系统时,就会执行此方法,通常是指程序启动的时候,此时运行时是混乱的状态,如果使用了其他的类,其他的类并不一定是初始化好了的。\n2、load方法的实现尽量精简,它不遵循那套继承规则,很难确定执行顺序,且load方式执行时应用会阻塞,如果在该方法里面执行了大量的耗时操作,那么程序就会无响应,所以一般不要使用此方法。\n3、+(void)initialize 会在程序首次使用该类之前调用,且只调用一次。与load方法的区别:首先它是“惰性”调用,只有程序在用到该类才会调用。此时运行时是正常状态,且执行环境是线程安全的。\n4、在编写load方法与initialize要保证代码实现尽量简单,除了初始化全局属性外,最好也不要调用自己的其他的方法。如:无法再编译期设定的全局常量,可以放在initialize方法里面初始化。\n\n### 别忘了NSTimer会保留其目标对象\n1、NSTimer对象会保留其目标对象,直到计时器本身失效为止,调用invalidate方法可令计时器失效,另外,一次性的计时器在触发完任务之后也会失效。\n2、反复执行任务的计时器很容易引入保留环,如果计时器的目标对象又保留了计时器本身,那么肯定会导致保留环,这种保留环关系,可能是由于直接或者间接发生的。\n3、可以扩充NSTimer的功能,用block来打破保留环。\n // 把block作为userInfo的参数传入,一定要先拷贝到堆上,不然一会执行block时可能就被释放了。\n```\n+ (void)_yy_ExecBlock:(NSTimer *)timer {\n if ([timer userInfo]) {\n void (^block)(NSTimer *timer) = (void (^)(NSTimer *timer))[timer userInfo];\n block(timer);\n }\n}\n+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds \n block:(void (^)(NSTimer *timer))block \n repeats:(BOOL)repeats {\n \n return [NSTimer scheduledTimerWithTimeInterval:seconds \n target:self\n selector:@selector(_yy_ExecBlock:)\n userInfo:[block copy]\n repeats:repeats];\n}\n```\n\n \n\n \n\n\n \n\n\n\n\n","source":"_posts/2017-01-22-Effective Objective-C 2.0:编写高质量iOS与OS X代码的52个有效方法-.md","raw":"---\nlayout: post\ntitle: \"《Effective Objective-C 2.0:编写高质量iOS与OS X代码的52个有效方法》笔记\"\ndate: 2017-01-22\ncomments: true\ncategories: iOS\ntags: [读书笔记]\nkeywords: 编写高质量iOS与OS X代码的52个有效方法\npublish: true\ndescription: 编写高质量iOS与OS X代码的52个有效方法\n---\n写出优雅高效的代码是每个程序员的最高追求,最近静下心里细细的品味一下一些提高代码质量的技巧,与君共勉之。\n<!-- more -->\n\n## 熟悉Objective-C\n\n### 了解Objective-C语言的起源\n\n1、区别于C++, Java等面向对象的语言,Objective-C在 运行中是“消息转发”而非“函数调用”,运行时所执行的代码由运行环境决定,而非编译器决定。\n2、NSString *someString = @\"The string\"; someString指针变量被分配在“栈帧”中,@“The string”对象则被分配在“堆空间”中,分配在堆中的内存必须直接管理,而分配在栈上用于保存变量的内存则会在其“栈帧”自动弹出时清理。在Objective-C中,内存管理指的是堆上的这部分内存。\n\n### 在类的头文件中尽量少引用其他头文件\n\n1、不要为了省事,直接在头文件中引用其他类的头文件,将头文件引入的时间尽量延后,可以用\"@class\"来声明类,减少编译器的负担。\n2、如果两个类互相引入对方的头文件会造成“循环引用”,无法正常编译。经测试:只互相引用头文件可正常编译,但是如果在类里面使用对方头文件变量时,就无法编译通过。\n3、某个类如果要实现某个协议,尽量把协议的声明写在“类扩展”,即\".m\"文件的\"@interface xxx<XXXDelegate> @end\",如果实在不行,那就最好吧协议单独放在一个头文件中,然后将其引入。\n\t\n### 多用字面量语法,少用与之等价的方法\n\n好处:\n1、书写简洁,便于阅读。\n2、使用字面量数组时可以更快的抛出异常,更加安全。\n局限性:\n1、自定义创建子类的实例,需要采取“非字面量语法”。\n### 多用类型常量,少用#define预处理指令\n\n<del>#define ANIMATION_DURATION 0.3</del>\n\n```\nstatic const NSTimeInterval kAnimationDuration = 0.3\n```\n\n1、如果不打算公开变量,可在.m文件中,同时使用static和const来定义常量,如果试图修改该变量编译器就会报错。这种变量只在编译单元内可见,由于不在”全局符号表“中所以无需增加前缀。\n2、如果打算公开某个常量,则需要这样来实现\n```\n// EOCAnimatedView.h\nextern const NSTimerInterval EOCAnimatedViewAnimationDuration;\n// EOCAnimatedView.m\nconst NSTimerInterval EOCAnimatedViewAnimationDuration = 0.3;\n```\n\t\n在头文件中声明,在实现文件中定义,由于在”全局符号表“中,为避免名称冲突,最好用与之相关的类名作为前缀。这样定义常量是不可被更改的,而使用#define预处理指令定义的常量很可能遭到别人的无意更改,这是非常危险的事情。\n\t\n### 多用类型常量,少用#define预处理指令\n1、使用NS_ENUM与NS_OPTIONS宏来定义枚举类型并指明其数据结构。\n2、应该用枚举来表示状态机的状态,状态码等值。\n3、如果枚举的多个选项可以同时组合,将这些项定义为2的幂,以便可以通过按位或操作将其组合起来。\n例如:AnimationEasyIn | AnimationLeft\n```\ntypedef NS_ENUM(NSUInteger, AnimationBehavior) {\nAnimationEasyIn = 1 << 0,\nAnimationLeft = 1 << 1\n};\n```\n4、处理枚举类型的switch语句中不要实现default分支,这样的话有新枚举加入,编译器就会提示开发者,switch语句中并未处理所有的枚举。\n## 对象、消息、运行期\n### 理解“属性”这一概念\n1、尽量不要直接定义实例变量,推荐使用属性\"@proproty\"来合成存取方法。使用点语法调用来访问变量。\n2、在设置属性所对应的实例变量时,一定要遵循该属性所声明的语义。\n即:\n```\n@property (nonatomic, copy)NSString *name;\n\t\n- (void)setName:(NSString *)name\n{\n _name = [name copy];\n}\n疑问:\n- (void)setName:(NSString *)name\n{\n // _name = [name copy];\n _name = name;\n}\n```\n经过测试,使用_name = name,和上面的效果是一样的,内存地址发生了变化。\n### 在对象内部尽量直接访问实例变量\n强烈建议在读取实例变量时候采用直接访问的形式,而在设置实例变量的时候通过属性来做。\n\n理由:\n1、直接访问属性,而不经过存取方法,直接访问那块内存,速度当然比较快,但是可以忽略不计。\n2、直接访问属性就绕过了如“strong”、“copy”,等“管理语义”,如果在ARC下直接访问一个声明为copy的对象,并不会拷贝改属性,只会保留新值并释放旧值。\n3、直接访问实例变量,不会触发“KVO”,\n合理的方案:\n在对象内部读取数据时,直接通过实例变量来读,在写入数据时,通过属性来写。\n注意:\n1、在初始化方法和dealloc方法中,应该直接访问实例变量,防止子类覆盖设置方法。\n2、懒加载中,通过获取方法来访问属性,否则实例变量永远不会被初始化。\n```\n- (Person *)person {\n\tif (!_person) {\n\t\t_person = [Person alloc] init];\n\t}\n\treturn _person;\n}\n```\n\n### 理解“对象等同性”这一概念\n1、重写isEqual和hash方法,判断对象的等同性。\n2、利用标识符,类似于数据库的主键,来判断对象的等同性。\n3、容器中放入可变对象时,慎重改变其哈希码,如:NSMutableSet中加入NSMutableArray。\n4、不盲目地检查每条属性,按照具体需求来制定检测对象。\n5、相同的对象必须具有相同的哈希码,但是哈希码相同的对象未必相同。\n6、编写hash方法时,应该使用计算速度快而且哈希码碰撞几率低的算法。\n\n[哈希介绍](https://zh.wikipedia.org/wiki/%E5%93%88%E5%B8%8C%E8%A1%A8)\n[Equality](http://nshipster.cn/equality/)\n\n### 以“类族模式”隐藏实现细节\n1、使用类方法创建实例,如:+ (UIButton *)buttonWithType:\n2、从类族的公共抽象基类中继承子类时要当心,子类应当覆写父类中指明需要覆写的方法\n### 在既有类中使用关联对象存放自定义数据\n“关联对象\"(Associated Object),可以在外部给类添加属性,常用在Category中添加。\n### 理解objc_msgSend的作用\n1、“静态绑定”编译器在编译阶段就能生成调用函数指令,“动态绑定”运行期才可以生成函数调用指令。\n2、objc_msgSend函数会在接收者所属类中的“方法列表”中寻找符合的方法,如果找到就执行实现代码,如果找不到,就沿着继承体系,向上继续寻找,如果最终还是找不到,就执行“消息转发操作”,此处可进行手动拦截。\n3、尾调用优化对于递归具有重要意义,大大减少调用栈的调用记录,防止栈溢出。\n\t\n[尾调用优化](http://www.ruanyifeng.com/blog/2015/04/tail-call.html)\n### 理解消息转发机制\n1、运行时系统没有找到消息的接收者,会发起消息转发,给接收者最后一次机会,所有的细节封装在NSInvocation对象中,在此可以进行拦截处理。\n2、对象无法收到解读的消息后,首先调用其所属类的类方法:\n第一步:\n+ (BOOL)resolveInstanceMethod:(SEL)selector 此处可以使用class_addMethod()添加新方法。\n第二步:为消息寻找一个备用的接收者,但无法操作这一步的消息。\n- (id)forwardingTargetForSelector:(SEL)selector \n第三步:若发现某调用操作不应该由本类处理,则需要调用超类的同名方法,这样,继承体系的每个子类都有机会处理此调用请求,直至NSObject,如果最后调用了NSObject的方法,会抛出异常,表明消息未得到处理。\n- (void)forwardingInvocation:(NSInvocation *)invocation\n\n### 用“方法调配技术”测试“黑盒方法”\n在运行期,通过runtime向类中添加或者交换方法实现。\n### 理解“类对象”的用意\n1、如果类型无法在编译器确定,那么就应该使用类型信息查询方法来探知。isMemberOfClass:判断对象是否为某个类的实例,isKindOfClass:判断对象是否为某个类或者其子类的实例。\n2、尽量使用类型信息确定对象类型,不要直接比较类对象,因为某些对象可能实现了消息转发功能。\n如:\t\n<del>if([object class] == [Person class]){\n}<del>\n```\nif([object isMemberOfClass:[Person class]] {\n}\n```\n\n## 接口与API设计\n### 用前缀避免命名空间冲突\n1、选择与你公司,应用程序或者与之相关的名称作为类名前缀,并在所有代码中统一所有前缀。\n2、在Category中给变量,方法添加前缀。\n3、若自己所开发的程序中用到了第三方库,则应为其中的名称加上前缀。\n4、所选的前缀应为三个字母(苹果规定的)。\n### 提供全能的初始化方法\n1、在类中提供一个全能的初始化方法,供其他初始化方法调用。\n2、若全能初始化方法与超类的不同,则需要覆写超类中对应的方法。\n3、如果超类的初始化方法不适用于子类,那么应该覆写这个超类方法,并在其中抛出异常。\n```\n-(id)initWithWidth:(float)width andHeight:(float)height\n{\n @throw [NSException exceptionWithName:...];\n}\n```\n\n### 实现description方法\n1、实现description方法返回一串有意义的字符串,来描述该对象,使用NSLog()打印对象时调用。\n2、实现debugDescription方法返回一串有意义的字符串,来描述该对象,在开发者断点调试通过LLDB命令po对象时调用。\n### 尽量使用不可变对象\n1、尽量把对外部公布出去的属性设置为只读(readonly)\n2、如果想修改封装在对象内部的数据,但是又不想别人在外部修改,这时需要在.m文件中重新把属性声明为readwrite,但是这样会产生“竞态条件”,需要将对象的所有数据进行同步,参见41条。\n3、通过KVC仍可以修改只读属性的值,这时不符合API规范的。\n4、不要把可变的集合对象作为属性公开,而是提供相应的方法修改集合对象。\n### 使用清晰而协调的命名方式\n1、尽量使用长方法名,清晰的说明方法的意思,但是也要尽量言简意赅,可参考UIKit命名规范。\n\n<del>-(id)initWithSize:(float)width :(float)height<del>\n```\n-(id)initWithWidth:(float)width andHeight:(float)height\n```\n\n### 为私有方法名加前缀\n1、给私有方法的名称加上前缀,便于跟公共方法区分。\n2、不能用单一下划线做前缀,这是苹果私有API的前缀,会冲突。\n### 理解Objective-C错误模型\n1、“-fojc-arc-exception”编译标识可以在执行异常代码时不抛出异常\n2、异常用于处理致命问题,无需考虑恢复问题,应用程序直接退出,非致命问题使用NSError对象。\n3、通过“输出参数”方式把NSError对象回传给调用者\n``` \nNSError *error = nil;\nBOOL ret = [object doSomething:&error];\nif (ret) {\n // There was an error\n}\n- (Bool)doSomething:(NSError **)error {\n if (// there was an error) {\n if (error) {\n *error = [NSError errorWithDomain:...];\n }\n return NO;\n } else {\n return YES;\n }\n}\n```\n \n在error要指向一个新的对象时(解引用),必须先保证error参数不是nil,因为空指针解引用会导致“段错误”,并使应用程序崩溃。调用者在不关心具体错误时,会给error参数传入nil,因此必须判断这种情况。\n### 理解NSCopying协议\n1、想让自定义对象具有拷贝功能,需要实现NSCopying协议。 \n2、对象拷贝分为深拷贝和浅拷贝,一般情况下尽量执行浅拷贝。\n3、如果对象需要深拷贝,可以考虑增加一个专门执行深拷贝的方法。\n4、如果自定义对象分为可变和不可变版本,需要同时实现NSCopying和NSMutableCopying协议。\n\n## 协议与分类\n### 通过委托与数据源协议进行对象间通信\n1、委托模式为对象提供一套接口,通过接口可将相关事件告知其他对象。\n2、将委托对象应该支持的接口定义成协议,在协议中将可能需要处理的事件定义为方法。\n3、当使用委托模式传递数据时,该模式也叫“数据源协议”,如UITableViewDataSource\n4、使用“位域”(含有位段的结构体),将委托对象是否响应相关协议的信息缓存其中。\n```\nstruct {\n unsigned int didReceiveData : 1;\n unsigned int didFailWithError : 1;\n unsigned int didUpdateProgressTo : 1;\n} _delegateFlags;\n \n- (void)setDelegate:(id<...>)delegate {\n _delegateFlags.didReceiveData = [delegate respondsToSelector:@selctor(...)];\n}\n \nif (_delegateFlags.didReceiveData) {\n [_delegate ....];\n}\n```\n\n### 将类的实现代码分散到便于管理的数个分类之中\n1、使用分类机制把类的实现代码划分成易于管理的小块。\n2、将应该私有的方法归入名叫Private的分类中,以隐藏实现细节。\n### 总是为第三方类的分类名称加前缀\n1、如果多个分类重载“主实现”的相关方法,以最后一个分类为主,即:分类在项目中编译的顺序。\n2、以命名空间来区分分类中所定义的方法,三个小写字母加下划线:abc_xxx\n### 请勿在分类中声明属性\n1、分类不可以定义属性,如果非要这么做,可以使用“关联对象”。\n2、把封装数据所用的全部属性都定义在主类中。\n3、可以定义存取方法但是尽量不要定义属性。\n### 使用“class-continuation分类”隐藏实现细节\n“class-continuation分类”也叫“类扩展”。\n1、通过“class-continuation分类”,向类中增加实例变量。\n2、私有方法声明在“class-continuation分类”中。\n3、私有的协议也可以声明在“class-continuation分类”中。\n### 通过协议提供匿名对象\n1、协议可以在某种程度上提供匿名类型,具体对象类型可以淡化为遵从某一协议的id类型,协议里规定了对象所应该实现的方法。\n2、使用匿名对象id<xxx>来隐藏类型名称。\n3、如果具体类型不重要,重要的是对象能够响应协议里的特定方法,那么可以用匿名对象来表示。也就是说,只暴露使用者关心的,隐藏其不需要关注的。\n## 内存管理\n### 理解引用计数器\n1、非ARC通过引用计数器增减来管理内存,对象创建好之后,引用计数器至少为1,若引用计数为正,对 象继续存活,当保留计数降为0时,对象就被销毁了。\n2、在对象生命周期中,其他对象通过引用来保留或者释放此对象,保留与释放操作分别会使引用计数递增和递减。\n3、不要操作“悬挂指针”(野指针),会引起崩溃,最好将其变为“空指针”。\n4、set方法 strong retain新值,release旧值,然后赋值。\n5、autoreleasepool能延长对象生命期,在下次运行循环或者更早一些release对象。\n6、使用“弱引用”可以防止循环引用。\n### 以ARC简化引用计数\n1、ARC会自动补上引用计数代码,但是并没有使用Objective-C的消息转发,而是直接通过C代码,性能会更好。\n2、ARC只管理Objective-C对象的内存,CoreFoundation对象不归ARC管理,开发者必须适时调用CFRetain/CFRelease。\n3、ARC对引用计数进行了特殊优化,如果发现对象在运行期进行多次保留和释放操作,会成对的移除这些操作,只保留有用操作,从而提高效率。\n4、ARC对存取方法进行了优化,不需要再去关注先保留新值,再释放旧值,直接赋值即可。\n5、ARC借助Objective-C++的特性清理对象,回收Objective-C对象调用多有C++对象的“析构函数\",如发现某个对象里面有C++对象,会生成.cxx_destruct的方法,并在该方法中生成清理内存所需代码。如果有非Objective-C对象(CoreFoundation对象或者malloc()分配的堆内存),不会调用父类的dealloc方法,会生成.cxx_destruct的方法,并在该方法中生成清理内存所需代码,在生成的代码中自动调用父类的dealloc方法。因此可以这样写:\n```\n-(void)dealloc {\n CFRelease(...);\n free(...);\n}\n```\n\n### 在dealloc方法中只释放引用并解除监听\n1、可以在dealloc方法中注销通知观察者等。\n2、比如文件,套接字,大块内存等开销较大或者系统内稀缺资源不可以在dealloc方法中释放,需要用完即释放。\n3、系统并不能保证每个创建的对象的dealloc方法都会调用,个别对象在应用程序终止时仍处于存活状态,由于应用程序终止,将内存返还给操作系统,所以实际上这些对象也算是销毁了。所以在系统回收之前我们可以手动清理这些对象,在UIApplicationDelegate/NSApplicationDelegate的委托方法中处理比较合适。\n4、不要再dealloc方法中随便调用别的方法,存取方法也不要调用,因为这样可能会触发观察者,还是使用下划线比较稳妥。\n### 编写”异常安全代码“时留意内存管理问题\n1、捕获异常时,一定要将try块内的对象清理干净。\n2、在默认情况下,ARC不生成安全处理异常所需的清理代码,开启”-fobjc-arc-exceptions“标识后,可生成这种代码,不过会导致应用程序变大,而且会降低运行效率。\n3、如果发现大量异常捕获操作时,考虑使用NSError错误传递来重构。\n### 以弱引用避免保留环\n1、某些引用设置为weak可以避免出现”保留环“(循环引用)。\n2、weak与unsafe_unretained的区别:\n相同:都是弱引用,用来表示”非拥有关系“。\n不同:weak 系统如果把属性回收,属性自动设置为nil;unsafe_unretained 系统如果把属性回收,属性仍然指向那个已经回收的实例,也就是”野指针“,继续操作属性会使程序崩溃,\n总的来说,weak更加安全一些,但是性能比unsafe_unretained低些。\n3、一般来说,如果不拥有某个对象就不要去保留它。这条规则对集合类对象例外,因为集合类对象并不直接拥有其内容,而是通过自己内部的元素来保留这个对象。使用weak尽量也不要去使用一个已经释放的弱引用对象,尽管不会崩溃,但是这依然是一个bug。\n### 以”自动释放池块“降低内存峰值\n1、自动释放池排布在栈中,对象收到autorelease消息后,系统将其放入最顶端的池里。\n2、合理利用自动释放池可以降低内存峰值,如:在for循环内部使用自动释放池包裹代码。\n3、@autoreleasepool这种写法可以创建更轻便的自动释放池。\n### 用”僵尸对象“调试内存管理问题\n1、系统再回收对象时,可以不将其真的回收,而是把它转化成僵尸对象,通过环境变量NSZombieEnabled可以开启此功能。\n2、系统会修改对象的isa指针,另其指向特殊的僵尸类,从而使该对象变为僵尸对象,僵尸类能够响应所有的选择子,响应方式为:打印一条包含信息内容及接收者的消息,然后终止程序。\n### 不要使用retainCount\n1、在ARC中retainCount方法已经被废弃,因为它只能返回特定时间点的引用计数器,而未考虑系统稍后会吧自动释放池清空的情况。或者是retainCount永远不返回0,因为系统可能会优化对象的释放行为,在引用计数是1的时候就回收对象,引用计数可能永远不会是0,所以引用计数是不准确的,就算能够正常返回时凭运气。\n2、单例对象的引用计数是不会改变的,其保留和释放都是空操作,retainCount已经被废弃了,任何对象的retainCount都是不确定的,所以retainCount绝对不要用。\n## 块与大中枢派发\n### 理解“块”这一概念\n1、默认情况,block所捕获的变量不能被修改,声明变量时加上__block就可以修改。但是类的实例变量不需要加__block即可被修改。\n2、使用block小心因捕获了self而造成循环引用的情况。如果访问了类的实例变量,self也会被捕获。\n3、block可以分配在栈或者堆上,也可以是全局的。分配在栈上的block可以拷贝到堆上,这样的话,就和标准的Objective-C对象一样,具备引用计数了。\n4、全局的block无法捕获任何状态(变量),运行时也无需状态参与,所使用的内存区域在编译时就确定了。\n```\nvoid (^block)() = ^{\n NSLog(\"This is a block!\");\n};\n```\n\n### 为常用的块类型创建typedef\n1、以typedef重新定义block类型,可令块block变量用起来更加简单,可读性更好。\n2、定义新类型时遵循现有命名习惯,不要发生命名冲突。\n3、不妨为同一个block定义多个类型别名,如果要重构的代码使用了block类型的某个别名,那么只需修改相应typedef中的签名即可,无需改动其他typedef。\n### 用handler块降低代码分散程度\n1、使用block来取代delegate可以使代码更加紧凑,便于阅读。\n2、在网络请求的API设计中,尽量用一个handlerl来处理数据及错误,更加灵活。\n推荐:\n```\n[fetcher startWithCompletionHander:^(NSData *data, NSError *error){\n if (error) {\n // failed\n } else {\n // success\n }\n}];\n```\n \n不推荐:\n```\n[fetcher startWithCompletionHandler:^(NSData *data){\n // success\n} failureHandler:^(NSError *error){\n // failed\n}];\n```\n \n3、设计API是如果用到handler块,可以增加一个参数,使调用者可以通过此参数来决定应该把块安排在哪个队列执行。\n### 使用块引用其所属对象时不要出现保留环\n1、如果块所捕获的对象直接或者间接保留了块本身,那么就会造成保留环问题。\n2、一定要找一个适当的时机解除保留环,而不能把责任推给API的调用者。\n以下是两种会出现保留环的写法:\n```\n1、_fetcher捕获了block block捕获了_fetcher\n_fetcher = [[xxx alloc] init];// 属性\n[_fetcher startWithCompletionHander:^(NSData *data, NSError *error){\n NSLog(@\"%@\", fetcher.url);\n _fetchData = data;\n}];\n2、fetcher捕获了block block捕获了fetcher.url\nxxx *fetcher = [[xxx alloc] init];// 临时变量\n[fetcher startWithCompletionHander:^(NSData *data, NSError *error){\n NSLog(@\"%@\", fetcher.url);\n _fetchData = data;\n}];\n```\n\n解决方案:\n1、weakSelf和strongSelf。\n2、在block调用后置为nil。\n### 多用派发队列,少用同步锁\n1、使用锁可以用来实现同步机制,但会带来性能甚至死锁的问题。\n2、将同步与异步派发结合起来,可以实现与普通锁一样的同步行为,而这么做也不会阻塞执行异步派发的线程。\n3、使用同步队列及栅栏块(dispatch_barrier_xxx),可以令同步行为更加高效。\n### 多用GCD,少用performSelector系列方法\n1、使用[object performSelector:@selector(selectorName)]方法可能会造成内存泄漏,ARC不会添加相关的释放操作,因此有可能会造成内存泄漏。\n2、可以使用GCD来代替。\n### 掌握GCD及操作队列的使用时机\n1、GCD并不是最优的办法,在某些情况下使用操作队列(NSOperation)可能会更好一些。\n2、NSOperation的优势:取消某个操作,制定操作的依赖关系,通过KVO监控NSOperation对象属性,指定操作优先级。\n3、GCD基于任务的队列,NSOperation基于操作的队列。\n### 通过Dispatch Group机制,根据系统资源状况来执行任务\n1、一系列任务可放在一个dispatch group中,开发者可以在这组任务执行完获得通知。\n2、通过dispatch group,可以并发执行多项任务,GCD会根据系统资源来调度执行任务。\n### 使用dispatch_once来执行只需运行一次的线程安全代码\n1、使用dispatch_once实现单例可以保证线程安全。\n2、标记声明为static或者global作用域中,这样可以保证执行dispatch_once函数时,传入的标记也是相同的。\n### 不要使用dispatch_get_current_queue\n1、dispatch_get_current_queue已经废弃,最好不要使用,可能会产生死锁问题。\n## 系统框架\n### 熟悉系统框架\n请记住:用纯C写成的框架与用Objective-C写成的一样重要,若想成为优秀的Objective-C开发者,应掌握C语言的核心概念。\n### 多用块枚举,少用for循环\n1、遍历集合有四种方式,最基本的办法是for循环,其次是NSEnumerator遍历法及快速遍历法,最新,最先进的方式是“块枚举法”,也就是block。\n2.“块枚举法”通过GCD并发执行遍历操作,效率较高,推荐使用。\n3、若提前知道待遍历的collection含有何种对象,则应修改块签名,指出对象的类型。\n### 对自定义其内存管理语义的collection使用无缝桥接\n1、__bridge本身意思是:ARC仍然具备这个Objective-C对象的所有权。__bridge_retained则与之相反,意味着ARC交出所有权,后面需要加上CFRelease()以释放对象。\n2、通过无缝桥接技术,可以在Foundation框架中的Objective-C对象与CoreFoundation框架中的C语言数据结构之间来回转换。\n2、在CoreFoundation层面创建collection时,可以指定许多回调函数,这些函数表示此collection应该如何处理元素,然后,可以运用无缝桥接技术,将其转换成具备特殊内存管理语义的Objective-C collection。\n### 构建缓存时选用NSCache而非NSDictionary\n1、NSCache胜过NSDictionary之处在于,当系统资源将要耗尽时,他可以自动删减缓存。NSCache并不会“拷贝”键,而是会”保留“它,而且是线程安全的。\n2、可以给NSCache对象设置上限,用以限制缓存中的对象总个数及“总成本”,而这些尺度则定义了缓存删减其中对象的时机。但是绝对不要把这些尺度当成可靠的“硬限制”,他们仅对NSCache起到指导作用。\n3、将NSPurgeableData与NSCache搭配使用,可实现自动清除数据的功能,也就是说当NSPurgeableData对象所占内存为系统所丢弃时,该对象自身也将从缓存中清除。\n4、如果缓存使用得当,那么应用程序的响应速度就能提高。只有那种“重新计算起来很费事的”数据,才值得放入缓存,比如那些需要从网络获取或者从磁盘中读取的数据。\n### 精简initialize与load的实现代码\n1、+ (void)load 当包含类或者分类的程序载入系统时,就会执行此方法,通常是指程序启动的时候,此时运行时是混乱的状态,如果使用了其他的类,其他的类并不一定是初始化好了的。\n2、load方法的实现尽量精简,它不遵循那套继承规则,很难确定执行顺序,且load方式执行时应用会阻塞,如果在该方法里面执行了大量的耗时操作,那么程序就会无响应,所以一般不要使用此方法。\n3、+(void)initialize 会在程序首次使用该类之前调用,且只调用一次。与load方法的区别:首先它是“惰性”调用,只有程序在用到该类才会调用。此时运行时是正常状态,且执行环境是线程安全的。\n4、在编写load方法与initialize要保证代码实现尽量简单,除了初始化全局属性外,最好也不要调用自己的其他的方法。如:无法再编译期设定的全局常量,可以放在initialize方法里面初始化。\n\n### 别忘了NSTimer会保留其目标对象\n1、NSTimer对象会保留其目标对象,直到计时器本身失效为止,调用invalidate方法可令计时器失效,另外,一次性的计时器在触发完任务之后也会失效。\n2、反复执行任务的计时器很容易引入保留环,如果计时器的目标对象又保留了计时器本身,那么肯定会导致保留环,这种保留环关系,可能是由于直接或者间接发生的。\n3、可以扩充NSTimer的功能,用block来打破保留环。\n // 把block作为userInfo的参数传入,一定要先拷贝到堆上,不然一会执行block时可能就被释放了。\n```\n+ (void)_yy_ExecBlock:(NSTimer *)timer {\n if ([timer userInfo]) {\n void (^block)(NSTimer *timer) = (void (^)(NSTimer *timer))[timer userInfo];\n block(timer);\n }\n}\n+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds \n block:(void (^)(NSTimer *timer))block \n repeats:(BOOL)repeats {\n \n return [NSTimer scheduledTimerWithTimeInterval:seconds \n target:self\n selector:@selector(_yy_ExecBlock:)\n userInfo:[block copy]\n repeats:repeats];\n}\n```\n\n \n\n \n\n\n \n\n\n\n\n","slug":"2017-01-22-Effective Objective-C 2.0:编写高质量iOS与OS X代码的52个有效方法-","published":1,"updated":"2017-03-05T04:16:26.000Z","photos":[],"link":"","_id":"cj0l1ptb9000x0er98j0iiczd","content":"<p>写出优雅高效的代码是每个程序员的最高追求,最近静下心里细细的品味一下一些提高代码质量的技巧,与君共勉之。<br><a id=\"more\"></a></p>\n<h2 id=\"熟悉Objective-C\"><a href=\"#熟悉Objective-C\" class=\"headerlink\" title=\"熟悉Objective-C\"></a>熟悉Objective-C</h2><h3 id=\"了解Objective-C语言的起源\"><a href=\"#了解Objective-C语言的起源\" class=\"headerlink\" title=\"了解Objective-C语言的起源\"></a>了解Objective-C语言的起源</h3><p>1、区别于C++, Java等面向对象的语言,Objective-C在 运行中是“消息转发”而非“函数调用”,运行时所执行的代码由运行环境决定,而非编译器决定。<br>2、NSString *someString = @”The string”; someString指针变量被分配在“栈帧”中,@“The string”对象则被分配在“堆空间”中,分配在堆中的内存必须直接管理,而分配在栈上用于保存变量的内存则会在其“栈帧”自动弹出时清理。在Objective-C中,内存管理指的是堆上的这部分内存。</p>\n<h3 id=\"在类的头文件中尽量少引用其他头文件\"><a href=\"#在类的头文件中尽量少引用其他头文件\" class=\"headerlink\" title=\"在类的头文件中尽量少引用其他头文件\"></a>在类的头文件中尽量少引用其他头文件</h3><p>1、不要为了省事,直接在头文件中引用其他类的头文件,将头文件引入的时间尽量延后,可以用”@class”来声明类,减少编译器的负担。<br>2、如果两个类互相引入对方的头文件会造成“循环引用”,无法正常编译。经测试:只互相引用头文件可正常编译,但是如果在类里面使用对方头文件变量时,就无法编译通过。<br>3、某个类如果要实现某个协议,尽量把协议的声明写在“类扩展”,即”.m”文件的”@interface xxx<xxxdelegate> @end”,如果实在不行,那就最好吧协议单独放在一个头文件中,然后将其引入。</xxxdelegate></p>\n<h3 id=\"多用字面量语法,少用与之等价的方法\"><a href=\"#多用字面量语法,少用与之等价的方法\" class=\"headerlink\" title=\"多用字面量语法,少用与之等价的方法\"></a>多用字面量语法,少用与之等价的方法</h3><p>好处:<br>1、书写简洁,便于阅读。<br>2、使用字面量数组时可以更快的抛出异常,更加安全。<br>局限性:<br>1、自定义创建子类的实例,需要采取“非字面量语法”。</p>\n<h3 id=\"多用类型常量,少用-define预处理指令\"><a href=\"#多用类型常量,少用-define预处理指令\" class=\"headerlink\" title=\"多用类型常量,少用#define预处理指令\"></a>多用类型常量,少用#define预处理指令</h3><p><del>#define ANIMATION_DURATION 0.3</del></p>\n<figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div></pre></td><td class=\"code\"><pre><div class=\"line\">static const NSTimeInterval kAnimationDuration = 0.3</div></pre></td></tr></table></figure>\n<p>1、如果不打算公开变量,可在.m文件中,同时使用static和const来定义常量,如果试图修改该变量编译器就会报错。这种变量只在编译单元内可见,由于不在”全局符号表“中所以无需增加前缀。<br>2、如果打算公开某个常量,则需要这样来实现<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div></pre></td><td class=\"code\"><pre><div class=\"line\">// EOCAnimatedView.h</div><div class=\"line\">extern const NSTimerInterval EOCAnimatedViewAnimationDuration;</div><div class=\"line\">// EOCAnimatedView.m</div><div class=\"line\">const NSTimerInterval EOCAnimatedViewAnimationDuration = 0.3;</div></pre></td></tr></table></figure></p>\n<p>在头文件中声明,在实现文件中定义,由于在”全局符号表“中,为避免名称冲突,最好用与之相关的类名作为前缀。这样定义常量是不可被更改的,而使用#define预处理指令定义的常量很可能遭到别人的无意更改,这是非常危险的事情。</p>\n<h3 id=\"多用类型常量,少用-define预处理指令-1\"><a href=\"#多用类型常量,少用-define预处理指令-1\" class=\"headerlink\" title=\"多用类型常量,少用#define预处理指令\"></a>多用类型常量,少用#define预处理指令</h3><p>1、使用NS_ENUM与NS_OPTIONS宏来定义枚举类型并指明其数据结构。<br>2、应该用枚举来表示状态机的状态,状态码等值。<br>3、如果枚举的多个选项可以同时组合,将这些项定义为2的幂,以便可以通过按位或操作将其组合起来。<br>例如:AnimationEasyIn | AnimationLeft<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div></pre></td><td class=\"code\"><pre><div class=\"line\">typedef NS_ENUM(NSUInteger, AnimationBehavior) {</div><div class=\"line\">AnimationEasyIn = 1 << 0,</div><div class=\"line\">AnimationLeft = 1 << 1</div><div class=\"line\">};</div></pre></td></tr></table></figure></p>\n<p>4、处理枚举类型的switch语句中不要实现default分支,这样的话有新枚举加入,编译器就会提示开发者,switch语句中并未处理所有的枚举。</p>\n<h2 id=\"对象、消息、运行期\"><a href=\"#对象、消息、运行期\" class=\"headerlink\" title=\"对象、消息、运行期\"></a>对象、消息、运行期</h2><h3 id=\"理解“属性”这一概念\"><a href=\"#理解“属性”这一概念\" class=\"headerlink\" title=\"理解“属性”这一概念\"></a>理解“属性”这一概念</h3><p>1、尽量不要直接定义实例变量,推荐使用属性”@proproty”来合成存取方法。使用点语法调用来访问变量。<br>2、在设置属性所对应的实例变量时,一定要遵循该属性所声明的语义。<br>即:<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div></pre></td><td class=\"code\"><pre><div class=\"line\">@property (nonatomic, copy)NSString *name;</div><div class=\"line\">\t</div><div class=\"line\">- (void)setName:(NSString *)name</div><div class=\"line\">{</div><div class=\"line\"> _name = [name copy];</div><div class=\"line\">}</div><div class=\"line\">疑问:</div><div class=\"line\">- (void)setName:(NSString *)name</div><div class=\"line\">{</div><div class=\"line\"> // _name = [name copy];</div><div class=\"line\"> _name = name;</div><div class=\"line\">}</div></pre></td></tr></table></figure></p>\n<p>经过测试,使用_name = name,和上面的效果是一样的,内存地址发生了变化。</p>\n<h3 id=\"在对象内部尽量直接访问实例变量\"><a href=\"#在对象内部尽量直接访问实例变量\" class=\"headerlink\" title=\"在对象内部尽量直接访问实例变量\"></a>在对象内部尽量直接访问实例变量</h3><p>强烈建议在读取实例变量时候采用直接访问的形式,而在设置实例变量的时候通过属性来做。</p>\n<p>理由:<br>1、直接访问属性,而不经过存取方法,直接访问那块内存,速度当然比较快,但是可以忽略不计。<br>2、直接访问属性就绕过了如“strong”、“copy”,等“管理语义”,如果在ARC下直接访问一个声明为copy的对象,并不会拷贝改属性,只会保留新值并释放旧值。<br>3、直接访问实例变量,不会触发“KVO”,<br>合理的方案:<br>在对象内部读取数据时,直接通过实例变量来读,在写入数据时,通过属性来写。<br>注意:<br>1、在初始化方法和dealloc方法中,应该直接访问实例变量,防止子类覆盖设置方法。<br>2、懒加载中,通过获取方法来访问属性,否则实例变量永远不会被初始化。<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div></pre></td><td class=\"code\"><pre><div class=\"line\">- (Person *)person {</div><div class=\"line\">\tif (!_person) {</div><div class=\"line\">\t\t_person = [Person alloc] init];</div><div class=\"line\">\t}</div><div class=\"line\">\treturn _person;</div><div class=\"line\">}</div></pre></td></tr></table></figure></p>\n<h3 id=\"理解“对象等同性”这一概念\"><a href=\"#理解“对象等同性”这一概念\" class=\"headerlink\" title=\"理解“对象等同性”这一概念\"></a>理解“对象等同性”这一概念</h3><p>1、重写isEqual和hash方法,判断对象的等同性。<br>2、利用标识符,类似于数据库的主键,来判断对象的等同性。<br>3、容器中放入可变对象时,慎重改变其哈希码,如:NSMutableSet中加入NSMutableArray。<br>4、不盲目地检查每条属性,按照具体需求来制定检测对象。<br>5、相同的对象必须具有相同的哈希码,但是哈希码相同的对象未必相同。<br>6、编写hash方法时,应该使用计算速度快而且哈希码碰撞几率低的算法。</p>\n<p><a href=\"https://zh.wikipedia.org/wiki/%E5%93%88%E5%B8%8C%E8%A1%A8\" target=\"_blank\" rel=\"external\">哈希介绍</a><br><a href=\"http://nshipster.cn/equality/\" target=\"_blank\" rel=\"external\">Equality</a></p>\n<h3 id=\"以“类族模式”隐藏实现细节\"><a href=\"#以“类族模式”隐藏实现细节\" class=\"headerlink\" title=\"以“类族模式”隐藏实现细节\"></a>以“类族模式”隐藏实现细节</h3><p>1、使用类方法创建实例,如:+ (UIButton *)buttonWithType:<br>2、从类族的公共抽象基类中继承子类时要当心,子类应当覆写父类中指明需要覆写的方法</p>\n<h3 id=\"在既有类中使用关联对象存放自定义数据\"><a href=\"#在既有类中使用关联对象存放自定义数据\" class=\"headerlink\" title=\"在既有类中使用关联对象存放自定义数据\"></a>在既有类中使用关联对象存放自定义数据</h3><p>“关联对象”(Associated Object),可以在外部给类添加属性,常用在Category中添加。</p>\n<h3 id=\"理解objc-msgSend的作用\"><a href=\"#理解objc-msgSend的作用\" class=\"headerlink\" title=\"理解objc_msgSend的作用\"></a>理解objc_msgSend的作用</h3><p>1、“静态绑定”编译器在编译阶段就能生成调用函数指令,“动态绑定”运行期才可以生成函数调用指令。<br>2、objc_msgSend函数会在接收者所属类中的“方法列表”中寻找符合的方法,如果找到就执行实现代码,如果找不到,就沿着继承体系,向上继续寻找,如果最终还是找不到,就执行“消息转发操作”,此处可进行手动拦截。<br>3、尾调用优化对于递归具有重要意义,大大减少调用栈的调用记录,防止栈溢出。</p>\n<p><a href=\"http://www.ruanyifeng.com/blog/2015/04/tail-call.html\" target=\"_blank\" rel=\"external\">尾调用优化</a></p>\n<h3 id=\"理解消息转发机制\"><a href=\"#理解消息转发机制\" class=\"headerlink\" title=\"理解消息转发机制\"></a>理解消息转发机制</h3><p>1、运行时系统没有找到消息的接收者,会发起消息转发,给接收者最后一次机会,所有的细节封装在NSInvocation对象中,在此可以进行拦截处理。<br>2、对象无法收到解读的消息后,首先调用其所属类的类方法:<br>第一步:</p>\n<ul>\n<li>(BOOL)resolveInstanceMethod:(SEL)selector 此处可以使用class_addMethod()添加新方法。<br>第二步:为消息寻找一个备用的接收者,但无法操作这一步的消息。</li>\n</ul>\n<ul>\n<li>(id)forwardingTargetForSelector:(SEL)selector<br>第三步:若发现某调用操作不应该由本类处理,则需要调用超类的同名方法,这样,继承体系的每个子类都有机会处理此调用请求,直至NSObject,如果最后调用了NSObject的方法,会抛出异常,表明消息未得到处理。</li>\n<li>(void)forwardingInvocation:(NSInvocation *)invocation</li>\n</ul>\n<h3 id=\"用“方法调配技术”测试“黑盒方法”\"><a href=\"#用“方法调配技术”测试“黑盒方法”\" class=\"headerlink\" title=\"用“方法调配技术”测试“黑盒方法”\"></a>用“方法调配技术”测试“黑盒方法”</h3><p>在运行期,通过runtime向类中添加或者交换方法实现。</p>\n<h3 id=\"理解“类对象”的用意\"><a href=\"#理解“类对象”的用意\" class=\"headerlink\" title=\"理解“类对象”的用意\"></a>理解“类对象”的用意</h3><p>1、如果类型无法在编译器确定,那么就应该使用类型信息查询方法来探知。isMemberOfClass:判断对象是否为某个类的实例,isKindOfClass:判断对象是否为某个类或者其子类的实例。<br>2、尽量使用类型信息确定对象类型,不要直接比较类对象,因为某些对象可能实现了消息转发功能。<br>如:<br><del>if([object class] == [Person class]){<br>}<del><br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div></pre></td><td class=\"code\"><pre><div class=\"line\">if([object isMemberOfClass:[Person class]] {</div><div class=\"line\">}</div></pre></td></tr></table></figure></del></del></p>\n<h2 id=\"接口与API设计\"><a href=\"#接口与API设计\" class=\"headerlink\" title=\"接口与API设计\"></a>接口与API设计</h2><h3 id=\"用前缀避免命名空间冲突\"><a href=\"#用前缀避免命名空间冲突\" class=\"headerlink\" title=\"用前缀避免命名空间冲突\"></a>用前缀避免命名空间冲突</h3><p>1、选择与你公司,应用程序或者与之相关的名称作为类名前缀,并在所有代码中统一所有前缀。<br>2、在Category中给变量,方法添加前缀。<br>3、若自己所开发的程序中用到了第三方库,则应为其中的名称加上前缀。<br>4、所选的前缀应为三个字母(苹果规定的)。</p>\n<h3 id=\"提供全能的初始化方法\"><a href=\"#提供全能的初始化方法\" class=\"headerlink\" title=\"提供全能的初始化方法\"></a>提供全能的初始化方法</h3><p>1、在类中提供一个全能的初始化方法,供其他初始化方法调用。<br>2、若全能初始化方法与超类的不同,则需要覆写超类中对应的方法。<br>3、如果超类的初始化方法不适用于子类,那么应该覆写这个超类方法,并在其中抛出异常。<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div></pre></td><td class=\"code\"><pre><div class=\"line\">-(id)initWithWidth:(float)width andHeight:(float)height</div><div class=\"line\">{</div><div class=\"line\"> @throw [NSException exceptionWithName:...];</div><div class=\"line\">}</div></pre></td></tr></table></figure></p>\n<h3 id=\"实现description方法\"><a href=\"#实现description方法\" class=\"headerlink\" title=\"实现description方法\"></a>实现description方法</h3><p>1、实现description方法返回一串有意义的字符串,来描述该对象,使用NSLog()打印对象时调用。<br>2、实现debugDescription方法返回一串有意义的字符串,来描述该对象,在开发者断点调试通过LLDB命令po对象时调用。</p>\n<h3 id=\"尽量使用不可变对象\"><a href=\"#尽量使用不可变对象\" class=\"headerlink\" title=\"尽量使用不可变对象\"></a>尽量使用不可变对象</h3><p>1、尽量把对外部公布出去的属性设置为只读(readonly)<br>2、如果想修改封装在对象内部的数据,但是又不想别人在外部修改,这时需要在.m文件中重新把属性声明为readwrite,但是这样会产生“竞态条件”,需要将对象的所有数据进行同步,参见41条。<br>3、通过KVC仍可以修改只读属性的值,这时不符合API规范的。<br>4、不要把可变的集合对象作为属性公开,而是提供相应的方法修改集合对象。</p>\n<h3 id=\"使用清晰而协调的命名方式\"><a href=\"#使用清晰而协调的命名方式\" class=\"headerlink\" title=\"使用清晰而协调的命名方式\"></a>使用清晰而协调的命名方式</h3><p>1、尽量使用长方法名,清晰的说明方法的意思,但是也要尽量言简意赅,可参考UIKit命名规范。</p>\n<p><del>-(id)initWithSize:(float)width :(float)height<del><br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div></pre></td><td class=\"code\"><pre><div class=\"line\">-(id)initWithWidth:(float)width andHeight:(float)height</div></pre></td></tr></table></figure></del></del></p>\n<h3 id=\"为私有方法名加前缀\"><a href=\"#为私有方法名加前缀\" class=\"headerlink\" title=\"为私有方法名加前缀\"></a>为私有方法名加前缀</h3><p>1、给私有方法的名称加上前缀,便于跟公共方法区分。<br>2、不能用单一下划线做前缀,这是苹果私有API的前缀,会冲突。</p>\n<h3 id=\"理解Objective-C错误模型\"><a href=\"#理解Objective-C错误模型\" class=\"headerlink\" title=\"理解Objective-C错误模型\"></a>理解Objective-C错误模型</h3><p>1、“-fojc-arc-exception”编译标识可以在执行异常代码时不抛出异常<br>2、异常用于处理致命问题,无需考虑恢复问题,应用程序直接退出,非致命问题使用NSError对象。<br>3、通过“输出参数”方式把NSError对象回传给调用者<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div><div class=\"line\">13</div><div class=\"line\">14</div><div class=\"line\">15</div></pre></td><td class=\"code\"><pre><div class=\"line\">NSError *error = nil;</div><div class=\"line\">BOOL ret = [object doSomething:&error];</div><div class=\"line\">if (ret) {</div><div class=\"line\"> // There was an error</div><div class=\"line\">}</div><div class=\"line\">- (Bool)doSomething:(NSError **)error {</div><div class=\"line\"> if (// there was an error) {</div><div class=\"line\"> if (error) {</div><div class=\"line\"> *error = [NSError errorWithDomain:...];</div><div class=\"line\"> }</div><div class=\"line\"> return NO;</div><div class=\"line\"> } else {</div><div class=\"line\"> return YES;</div><div class=\"line\"> }</div><div class=\"line\">}</div></pre></td></tr></table></figure></p>\n<p>在error要指向一个新的对象时(解引用),必须先保证error参数不是nil,因为空指针解引用会导致“段错误”,并使应用程序崩溃。调用者在不关心具体错误时,会给error参数传入nil,因此必须判断这种情况。</p>\n<h3 id=\"理解NSCopying协议\"><a href=\"#理解NSCopying协议\" class=\"headerlink\" title=\"理解NSCopying协议\"></a>理解NSCopying协议</h3><p>1、想让自定义对象具有拷贝功能,需要实现NSCopying协议。<br>2、对象拷贝分为深拷贝和浅拷贝,一般情况下尽量执行浅拷贝。<br>3、如果对象需要深拷贝,可以考虑增加一个专门执行深拷贝的方法。<br>4、如果自定义对象分为可变和不可变版本,需要同时实现NSCopying和NSMutableCopying协议。</p>\n<h2 id=\"协议与分类\"><a href=\"#协议与分类\" class=\"headerlink\" title=\"协议与分类\"></a>协议与分类</h2><h3 id=\"通过委托与数据源协议进行对象间通信\"><a href=\"#通过委托与数据源协议进行对象间通信\" class=\"headerlink\" title=\"通过委托与数据源协议进行对象间通信\"></a>通过委托与数据源协议进行对象间通信</h3><p>1、委托模式为对象提供一套接口,通过接口可将相关事件告知其他对象。<br>2、将委托对象应该支持的接口定义成协议,在协议中将可能需要处理的事件定义为方法。<br>3、当使用委托模式传递数据时,该模式也叫“数据源协议”,如UITableViewDataSource<br>4、使用“位域”(含有位段的结构体),将委托对象是否响应相关协议的信息缓存其中。<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div><div class=\"line\">13</div></pre></td><td class=\"code\"><pre><div class=\"line\">struct {</div><div class=\"line\"> unsigned int didReceiveData : 1;</div><div class=\"line\"> unsigned int didFailWithError : 1;</div><div class=\"line\"> unsigned int didUpdateProgressTo : 1;</div><div class=\"line\">} _delegateFlags;</div><div class=\"line\"> </div><div class=\"line\">- (void)setDelegate:(id<...>)delegate {</div><div class=\"line\"> _delegateFlags.didReceiveData = [delegate respondsToSelector:@selctor(...)];</div><div class=\"line\">}</div><div class=\"line\"> </div><div class=\"line\">if (_delegateFlags.didReceiveData) {</div><div class=\"line\"> [_delegate ....];</div><div class=\"line\">}</div></pre></td></tr></table></figure></p>\n<h3 id=\"将类的实现代码分散到便于管理的数个分类之中\"><a href=\"#将类的实现代码分散到便于管理的数个分类之中\" class=\"headerlink\" title=\"将类的实现代码分散到便于管理的数个分类之中\"></a>将类的实现代码分散到便于管理的数个分类之中</h3><p>1、使用分类机制把类的实现代码划分成易于管理的小块。<br>2、将应该私有的方法归入名叫Private的分类中,以隐藏实现细节。</p>\n<h3 id=\"总是为第三方类的分类名称加前缀\"><a href=\"#总是为第三方类的分类名称加前缀\" class=\"headerlink\" title=\"总是为第三方类的分类名称加前缀\"></a>总是为第三方类的分类名称加前缀</h3><p>1、如果多个分类重载“主实现”的相关方法,以最后一个分类为主,即:分类在项目中编译的顺序。<br>2、以命名空间来区分分类中所定义的方法,三个小写字母加下划线:abc_xxx</p>\n<h3 id=\"请勿在分类中声明属性\"><a href=\"#请勿在分类中声明属性\" class=\"headerlink\" title=\"请勿在分类中声明属性\"></a>请勿在分类中声明属性</h3><p>1、分类不可以定义属性,如果非要这么做,可以使用“关联对象”。<br>2、把封装数据所用的全部属性都定义在主类中。<br>3、可以定义存取方法但是尽量不要定义属性。</p>\n<h3 id=\"使用“class-continuation分类”隐藏实现细节\"><a href=\"#使用“class-continuation分类”隐藏实现细节\" class=\"headerlink\" title=\"使用“class-continuation分类”隐藏实现细节\"></a>使用“class-continuation分类”隐藏实现细节</h3><p>“class-continuation分类”也叫“类扩展”。<br>1、通过“class-continuation分类”,向类中增加实例变量。<br>2、私有方法声明在“class-continuation分类”中。<br>3、私有的协议也可以声明在“class-continuation分类”中。</p>\n<h3 id=\"通过协议提供匿名对象\"><a href=\"#通过协议提供匿名对象\" class=\"headerlink\" title=\"通过协议提供匿名对象\"></a>通过协议提供匿名对象</h3><p>1、协议可以在某种程度上提供匿名类型,具体对象类型可以淡化为遵从某一协议的id类型,协议里规定了对象所应该实现的方法。<br>2、使用匿名对象id<xxx>来隐藏类型名称。<br>3、如果具体类型不重要,重要的是对象能够响应协议里的特定方法,那么可以用匿名对象来表示。也就是说,只暴露使用者关心的,隐藏其不需要关注的。</xxx></p>\n<h2 id=\"内存管理\"><a href=\"#内存管理\" class=\"headerlink\" title=\"内存管理\"></a>内存管理</h2><h3 id=\"理解引用计数器\"><a href=\"#理解引用计数器\" class=\"headerlink\" title=\"理解引用计数器\"></a>理解引用计数器</h3><p>1、非ARC通过引用计数器增减来管理内存,对象创建好之后,引用计数器至少为1,若引用计数为正,对 象继续存活,当保留计数降为0时,对象就被销毁了。<br>2、在对象生命周期中,其他对象通过引用来保留或者释放此对象,保留与释放操作分别会使引用计数递增和递减。<br>3、不要操作“悬挂指针”(野指针),会引起崩溃,最好将其变为“空指针”。<br>4、set方法 strong retain新值,release旧值,然后赋值。<br>5、autoreleasepool能延长对象生命期,在下次运行循环或者更早一些release对象。<br>6、使用“弱引用”可以防止循环引用。</p>\n<h3 id=\"以ARC简化引用计数\"><a href=\"#以ARC简化引用计数\" class=\"headerlink\" title=\"以ARC简化引用计数\"></a>以ARC简化引用计数</h3><p>1、ARC会自动补上引用计数代码,但是并没有使用Objective-C的消息转发,而是直接通过C代码,性能会更好。<br>2、ARC只管理Objective-C对象的内存,CoreFoundation对象不归ARC管理,开发者必须适时调用CFRetain/CFRelease。<br>3、ARC对引用计数进行了特殊优化,如果发现对象在运行期进行多次保留和释放操作,会成对的移除这些操作,只保留有用操作,从而提高效率。<br>4、ARC对存取方法进行了优化,不需要再去关注先保留新值,再释放旧值,直接赋值即可。<br>5、ARC借助Objective-C++的特性清理对象,回收Objective-C对象调用多有C++对象的“析构函数”,如发现某个对象里面有C++对象,会生成.cxx_destruct的方法,并在该方法中生成清理内存所需代码。如果有非Objective-C对象(CoreFoundation对象或者malloc()分配的堆内存),不会调用父类的dealloc方法,会生成.cxx_destruct的方法,并在该方法中生成清理内存所需代码,在生成的代码中自动调用父类的dealloc方法。因此可以这样写:<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div></pre></td><td class=\"code\"><pre><div class=\"line\">-(void)dealloc {</div><div class=\"line\"> CFRelease(...);</div><div class=\"line\"> free(...);</div><div class=\"line\">}</div></pre></td></tr></table></figure></p>\n<h3 id=\"在dealloc方法中只释放引用并解除监听\"><a href=\"#在dealloc方法中只释放引用并解除监听\" class=\"headerlink\" title=\"在dealloc方法中只释放引用并解除监听\"></a>在dealloc方法中只释放引用并解除监听</h3><p>1、可以在dealloc方法中注销通知观察者等。<br>2、比如文件,套接字,大块内存等开销较大或者系统内稀缺资源不可以在dealloc方法中释放,需要用完即释放。<br>3、系统并不能保证每个创建的对象的dealloc方法都会调用,个别对象在应用程序终止时仍处于存活状态,由于应用程序终止,将内存返还给操作系统,所以实际上这些对象也算是销毁了。所以在系统回收之前我们可以手动清理这些对象,在UIApplicationDelegate/NSApplicationDelegate的委托方法中处理比较合适。<br>4、不要再dealloc方法中随便调用别的方法,存取方法也不要调用,因为这样可能会触发观察者,还是使用下划线比较稳妥。</p>\n<h3 id=\"编写”异常安全代码“时留意内存管理问题\"><a href=\"#编写”异常安全代码“时留意内存管理问题\" class=\"headerlink\" title=\"编写”异常安全代码“时留意内存管理问题\"></a>编写”异常安全代码“时留意内存管理问题</h3><p>1、捕获异常时,一定要将try块内的对象清理干净。<br>2、在默认情况下,ARC不生成安全处理异常所需的清理代码,开启”-fobjc-arc-exceptions“标识后,可生成这种代码,不过会导致应用程序变大,而且会降低运行效率。<br>3、如果发现大量异常捕获操作时,考虑使用NSError错误传递来重构。</p>\n<h3 id=\"以弱引用避免保留环\"><a href=\"#以弱引用避免保留环\" class=\"headerlink\" title=\"以弱引用避免保留环\"></a>以弱引用避免保留环</h3><p>1、某些引用设置为weak可以避免出现”保留环“(循环引用)。<br>2、weak与unsafe_unretained的区别:<br>相同:都是弱引用,用来表示”非拥有关系“。<br>不同:weak 系统如果把属性回收,属性自动设置为nil;unsafe_unretained 系统如果把属性回收,属性仍然指向那个已经回收的实例,也就是”野指针“,继续操作属性会使程序崩溃,<br>总的来说,weak更加安全一些,但是性能比unsafe_unretained低些。<br>3、一般来说,如果不拥有某个对象就不要去保留它。这条规则对集合类对象例外,因为集合类对象并不直接拥有其内容,而是通过自己内部的元素来保留这个对象。使用weak尽量也不要去使用一个已经释放的弱引用对象,尽管不会崩溃,但是这依然是一个bug。</p>\n<h3 id=\"以”自动释放池块“降低内存峰值\"><a href=\"#以”自动释放池块“降低内存峰值\" class=\"headerlink\" title=\"以”自动释放池块“降低内存峰值\"></a>以”自动释放池块“降低内存峰值</h3><p>1、自动释放池排布在栈中,对象收到autorelease消息后,系统将其放入最顶端的池里。<br>2、合理利用自动释放池可以降低内存峰值,如:在for循环内部使用自动释放池包裹代码。<br>3、@autoreleasepool这种写法可以创建更轻便的自动释放池。</p>\n<h3 id=\"用”僵尸对象“调试内存管理问题\"><a href=\"#用”僵尸对象“调试内存管理问题\" class=\"headerlink\" title=\"用”僵尸对象“调试内存管理问题\"></a>用”僵尸对象“调试内存管理问题</h3><p>1、系统再回收对象时,可以不将其真的回收,而是把它转化成僵尸对象,通过环境变量NSZombieEnabled可以开启此功能。<br>2、系统会修改对象的isa指针,另其指向特殊的僵尸类,从而使该对象变为僵尸对象,僵尸类能够响应所有的选择子,响应方式为:打印一条包含信息内容及接收者的消息,然后终止程序。</p>\n<h3 id=\"不要使用retainCount\"><a href=\"#不要使用retainCount\" class=\"headerlink\" title=\"不要使用retainCount\"></a>不要使用retainCount</h3><p>1、在ARC中retainCount方法已经被废弃,因为它只能返回特定时间点的引用计数器,而未考虑系统稍后会吧自动释放池清空的情况。或者是retainCount永远不返回0,因为系统可能会优化对象的释放行为,在引用计数是1的时候就回收对象,引用计数可能永远不会是0,所以引用计数是不准确的,就算能够正常返回时凭运气。<br>2、单例对象的引用计数是不会改变的,其保留和释放都是空操作,retainCount已经被废弃了,任何对象的retainCount都是不确定的,所以retainCount绝对不要用。</p>\n<h2 id=\"块与大中枢派发\"><a href=\"#块与大中枢派发\" class=\"headerlink\" title=\"块与大中枢派发\"></a>块与大中枢派发</h2><h3 id=\"理解“块”这一概念\"><a href=\"#理解“块”这一概念\" class=\"headerlink\" title=\"理解“块”这一概念\"></a>理解“块”这一概念</h3><p>1、默认情况,block所捕获的变量不能被修改,声明变量时加上<strong>block就可以修改。但是类的实例变量不需要加</strong>block即可被修改。<br>2、使用block小心因捕获了self而造成循环引用的情况。如果访问了类的实例变量,self也会被捕获。<br>3、block可以分配在栈或者堆上,也可以是全局的。分配在栈上的block可以拷贝到堆上,这样的话,就和标准的Objective-C对象一样,具备引用计数了。<br>4、全局的block无法捕获任何状态(变量),运行时也无需状态参与,所使用的内存区域在编译时就确定了。<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div></pre></td><td class=\"code\"><pre><div class=\"line\">void (^block)() = ^{</div><div class=\"line\"> NSLog("This is a block!");</div><div class=\"line\">};</div></pre></td></tr></table></figure></p>\n<h3 id=\"为常用的块类型创建typedef\"><a href=\"#为常用的块类型创建typedef\" class=\"headerlink\" title=\"为常用的块类型创建typedef\"></a>为常用的块类型创建typedef</h3><p>1、以typedef重新定义block类型,可令块block变量用起来更加简单,可读性更好。<br>2、定义新类型时遵循现有命名习惯,不要发生命名冲突。<br>3、不妨为同一个block定义多个类型别名,如果要重构的代码使用了block类型的某个别名,那么只需修改相应typedef中的签名即可,无需改动其他typedef。</p>\n<h3 id=\"用handler块降低代码分散程度\"><a href=\"#用handler块降低代码分散程度\" class=\"headerlink\" title=\"用handler块降低代码分散程度\"></a>用handler块降低代码分散程度</h3><p>1、使用block来取代delegate可以使代码更加紧凑,便于阅读。<br>2、在网络请求的API设计中,尽量用一个handlerl来处理数据及错误,更加灵活。<br>推荐:<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div></pre></td><td class=\"code\"><pre><div class=\"line\">[fetcher startWithCompletionHander:^(NSData *data, NSError *error){</div><div class=\"line\"> if (error) {</div><div class=\"line\"> // failed</div><div class=\"line\"> } else {</div><div class=\"line\"> // success</div><div class=\"line\"> }</div><div class=\"line\">}];</div></pre></td></tr></table></figure></p>\n<p>不推荐:<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div></pre></td><td class=\"code\"><pre><div class=\"line\">[fetcher startWithCompletionHandler:^(NSData *data){</div><div class=\"line\"> // success</div><div class=\"line\">} failureHandler:^(NSError *error){</div><div class=\"line\"> // failed</div><div class=\"line\">}];</div></pre></td></tr></table></figure></p>\n<p>3、设计API是如果用到handler块,可以增加一个参数,使调用者可以通过此参数来决定应该把块安排在哪个队列执行。</p>\n<h3 id=\"使用块引用其所属对象时不要出现保留环\"><a href=\"#使用块引用其所属对象时不要出现保留环\" class=\"headerlink\" title=\"使用块引用其所属对象时不要出现保留环\"></a>使用块引用其所属对象时不要出现保留环</h3><p>1、如果块所捕获的对象直接或者间接保留了块本身,那么就会造成保留环问题。<br>2、一定要找一个适当的时机解除保留环,而不能把责任推给API的调用者。<br>以下是两种会出现保留环的写法:<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div></pre></td><td class=\"code\"><pre><div class=\"line\">1、_fetcher捕获了block block捕获了_fetcher</div><div class=\"line\">_fetcher = [[xxx alloc] init];// 属性</div><div class=\"line\">[_fetcher startWithCompletionHander:^(NSData *data, NSError *error){</div><div class=\"line\"> NSLog(@"%@", fetcher.url);</div><div class=\"line\"> _fetchData = data;</div><div class=\"line\">}];</div><div class=\"line\">2、fetcher捕获了block block捕获了fetcher.url</div><div class=\"line\">xxx *fetcher = [[xxx alloc] init];// 临时变量</div><div class=\"line\">[fetcher startWithCompletionHander:^(NSData *data, NSError *error){</div><div class=\"line\"> NSLog(@"%@", fetcher.url);</div><div class=\"line\"> _fetchData = data;</div><div class=\"line\">}];</div></pre></td></tr></table></figure></p>\n<p>解决方案:<br>1、weakSelf和strongSelf。<br>2、在block调用后置为nil。</p>\n<h3 id=\"多用派发队列,少用同步锁\"><a href=\"#多用派发队列,少用同步锁\" class=\"headerlink\" title=\"多用派发队列,少用同步锁\"></a>多用派发队列,少用同步锁</h3><p>1、使用锁可以用来实现同步机制,但会带来性能甚至死锁的问题。<br>2、将同步与异步派发结合起来,可以实现与普通锁一样的同步行为,而这么做也不会阻塞执行异步派发的线程。<br>3、使用同步队列及栅栏块(dispatch_barrier_xxx),可以令同步行为更加高效。</p>\n<h3 id=\"多用GCD,少用performSelector系列方法\"><a href=\"#多用GCD,少用performSelector系列方法\" class=\"headerlink\" title=\"多用GCD,少用performSelector系列方法\"></a>多用GCD,少用performSelector系列方法</h3><p>1、使用[object performSelector:@selector(selectorName)]方法可能会造成内存泄漏,ARC不会添加相关的释放操作,因此有可能会造成内存泄漏。<br>2、可以使用GCD来代替。</p>\n<h3 id=\"掌握GCD及操作队列的使用时机\"><a href=\"#掌握GCD及操作队列的使用时机\" class=\"headerlink\" title=\"掌握GCD及操作队列的使用时机\"></a>掌握GCD及操作队列的使用时机</h3><p>1、GCD并不是最优的办法,在某些情况下使用操作队列(NSOperation)可能会更好一些。<br>2、NSOperation的优势:取消某个操作,制定操作的依赖关系,通过KVO监控NSOperation对象属性,指定操作优先级。<br>3、GCD基于任务的队列,NSOperation基于操作的队列。</p>\n<h3 id=\"通过Dispatch-Group机制,根据系统资源状况来执行任务\"><a href=\"#通过Dispatch-Group机制,根据系统资源状况来执行任务\" class=\"headerlink\" title=\"通过Dispatch Group机制,根据系统资源状况来执行任务\"></a>通过Dispatch Group机制,根据系统资源状况来执行任务</h3><p>1、一系列任务可放在一个dispatch group中,开发者可以在这组任务执行完获得通知。<br>2、通过dispatch group,可以并发执行多项任务,GCD会根据系统资源来调度执行任务。</p>\n<h3 id=\"使用dispatch-once来执行只需运行一次的线程安全代码\"><a href=\"#使用dispatch-once来执行只需运行一次的线程安全代码\" class=\"headerlink\" title=\"使用dispatch_once来执行只需运行一次的线程安全代码\"></a>使用dispatch_once来执行只需运行一次的线程安全代码</h3><p>1、使用dispatch_once实现单例可以保证线程安全。<br>2、标记声明为static或者global作用域中,这样可以保证执行dispatch_once函数时,传入的标记也是相同的。</p>\n<h3 id=\"不要使用dispatch-get-current-queue\"><a href=\"#不要使用dispatch-get-current-queue\" class=\"headerlink\" title=\"不要使用dispatch_get_current_queue\"></a>不要使用dispatch_get_current_queue</h3><p>1、dispatch_get_current_queue已经废弃,最好不要使用,可能会产生死锁问题。</p>\n<h2 id=\"系统框架\"><a href=\"#系统框架\" class=\"headerlink\" title=\"系统框架\"></a>系统框架</h2><h3 id=\"熟悉系统框架\"><a href=\"#熟悉系统框架\" class=\"headerlink\" title=\"熟悉系统框架\"></a>熟悉系统框架</h3><p>请记住:用纯C写成的框架与用Objective-C写成的一样重要,若想成为优秀的Objective-C开发者,应掌握C语言的核心概念。</p>\n<h3 id=\"多用块枚举,少用for循环\"><a href=\"#多用块枚举,少用for循环\" class=\"headerlink\" title=\"多用块枚举,少用for循环\"></a>多用块枚举,少用for循环</h3><p>1、遍历集合有四种方式,最基本的办法是for循环,其次是NSEnumerator遍历法及快速遍历法,最新,最先进的方式是“块枚举法”,也就是block。<br>2.“块枚举法”通过GCD并发执行遍历操作,效率较高,推荐使用。<br>3、若提前知道待遍历的collection含有何种对象,则应修改块签名,指出对象的类型。</p>\n<h3 id=\"对自定义其内存管理语义的collection使用无缝桥接\"><a href=\"#对自定义其内存管理语义的collection使用无缝桥接\" class=\"headerlink\" title=\"对自定义其内存管理语义的collection使用无缝桥接\"></a>对自定义其内存管理语义的collection使用无缝桥接</h3><p>1、<strong>bridge本身意思是:ARC仍然具备这个Objective-C对象的所有权。</strong>bridge_retained则与之相反,意味着ARC交出所有权,后面需要加上CFRelease()以释放对象。<br>2、通过无缝桥接技术,可以在Foundation框架中的Objective-C对象与CoreFoundation框架中的C语言数据结构之间来回转换。<br>2、在CoreFoundation层面创建collection时,可以指定许多回调函数,这些函数表示此collection应该如何处理元素,然后,可以运用无缝桥接技术,将其转换成具备特殊内存管理语义的Objective-C collection。</p>\n<h3 id=\"构建缓存时选用NSCache而非NSDictionary\"><a href=\"#构建缓存时选用NSCache而非NSDictionary\" class=\"headerlink\" title=\"构建缓存时选用NSCache而非NSDictionary\"></a>构建缓存时选用NSCache而非NSDictionary</h3><p>1、NSCache胜过NSDictionary之处在于,当系统资源将要耗尽时,他可以自动删减缓存。NSCache并不会“拷贝”键,而是会”保留“它,而且是线程安全的。<br>2、可以给NSCache对象设置上限,用以限制缓存中的对象总个数及“总成本”,而这些尺度则定义了缓存删减其中对象的时机。但是绝对不要把这些尺度当成可靠的“硬限制”,他们仅对NSCache起到指导作用。<br>3、将NSPurgeableData与NSCache搭配使用,可实现自动清除数据的功能,也就是说当NSPurgeableData对象所占内存为系统所丢弃时,该对象自身也将从缓存中清除。<br>4、如果缓存使用得当,那么应用程序的响应速度就能提高。只有那种“重新计算起来很费事的”数据,才值得放入缓存,比如那些需要从网络获取或者从磁盘中读取的数据。</p>\n<h3 id=\"精简initialize与load的实现代码\"><a href=\"#精简initialize与load的实现代码\" class=\"headerlink\" title=\"精简initialize与load的实现代码\"></a>精简initialize与load的实现代码</h3><p>1、+ (void)load 当包含类或者分类的程序载入系统时,就会执行此方法,通常是指程序启动的时候,此时运行时是混乱的状态,如果使用了其他的类,其他的类并不一定是初始化好了的。<br>2、load方法的实现尽量精简,它不遵循那套继承规则,很难确定执行顺序,且load方式执行时应用会阻塞,如果在该方法里面执行了大量的耗时操作,那么程序就会无响应,所以一般不要使用此方法。<br>3、+(void)initialize 会在程序首次使用该类之前调用,且只调用一次。与load方法的区别:首先它是“惰性”调用,只有程序在用到该类才会调用。此时运行时是正常状态,且执行环境是线程安全的。<br>4、在编写load方法与initialize要保证代码实现尽量简单,除了初始化全局属性外,最好也不要调用自己的其他的方法。如:无法再编译期设定的全局常量,可以放在initialize方法里面初始化。</p>\n<h3 id=\"别忘了NSTimer会保留其目标对象\"><a href=\"#别忘了NSTimer会保留其目标对象\" class=\"headerlink\" title=\"别忘了NSTimer会保留其目标对象\"></a>别忘了NSTimer会保留其目标对象</h3><p>1、NSTimer对象会保留其目标对象,直到计时器本身失效为止,调用invalidate方法可令计时器失效,另外,一次性的计时器在触发完任务之后也会失效。<br>2、反复执行任务的计时器很容易引入保留环,如果计时器的目标对象又保留了计时器本身,那么肯定会导致保留环,这种保留环关系,可能是由于直接或者间接发生的。<br>3、可以扩充NSTimer的功能,用block来打破保留环。<br> // 把block作为userInfo的参数传入,一定要先拷贝到堆上,不然一会执行block时可能就被释放了。<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div><div class=\"line\">13</div><div class=\"line\">14</div><div class=\"line\">15</div><div class=\"line\">16</div></pre></td><td class=\"code\"><pre><div class=\"line\">+ (void)_yy_ExecBlock:(NSTimer *)timer {</div><div class=\"line\"> if ([timer userInfo]) {</div><div class=\"line\"> void (^block)(NSTimer *timer) = (void (^)(NSTimer *timer))[timer userInfo];</div><div class=\"line\"> block(timer);</div><div class=\"line\"> }</div><div class=\"line\">}</div><div class=\"line\">+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds </div><div class=\"line\"> block:(void (^)(NSTimer *timer))block </div><div class=\"line\"> repeats:(BOOL)repeats {</div><div class=\"line\"> </div><div class=\"line\"> return [NSTimer scheduledTimerWithTimeInterval:seconds </div><div class=\"line\"> target:self</div><div class=\"line\"> selector:@selector(_yy_ExecBlock:)</div><div class=\"line\"> userInfo:[block copy]</div><div class=\"line\"> repeats:repeats];</div><div class=\"line\">}</div></pre></td></tr></table></figure></p>\n","excerpt":"<p>写出优雅高效的代码是每个程序员的最高追求,最近静下心里细细的品味一下一些提高代码质量的技巧,与君共勉之。<br>","more":"</p>\n<h2 id=\"熟悉Objective-C\"><a href=\"#熟悉Objective-C\" class=\"headerlink\" title=\"熟悉Objective-C\"></a>熟悉Objective-C</h2><h3 id=\"了解Objective-C语言的起源\"><a href=\"#了解Objective-C语言的起源\" class=\"headerlink\" title=\"了解Objective-C语言的起源\"></a>了解Objective-C语言的起源</h3><p>1、区别于C++, Java等面向对象的语言,Objective-C在 运行中是“消息转发”而非“函数调用”,运行时所执行的代码由运行环境决定,而非编译器决定。<br>2、NSString *someString = @”The string”; someString指针变量被分配在“栈帧”中,@“The string”对象则被分配在“堆空间”中,分配在堆中的内存必须直接管理,而分配在栈上用于保存变量的内存则会在其“栈帧”自动弹出时清理。在Objective-C中,内存管理指的是堆上的这部分内存。</p>\n<h3 id=\"在类的头文件中尽量少引用其他头文件\"><a href=\"#在类的头文件中尽量少引用其他头文件\" class=\"headerlink\" title=\"在类的头文件中尽量少引用其他头文件\"></a>在类的头文件中尽量少引用其他头文件</h3><p>1、不要为了省事,直接在头文件中引用其他类的头文件,将头文件引入的时间尽量延后,可以用”@class”来声明类,减少编译器的负担。<br>2、如果两个类互相引入对方的头文件会造成“循环引用”,无法正常编译。经测试:只互相引用头文件可正常编译,但是如果在类里面使用对方头文件变量时,就无法编译通过。<br>3、某个类如果要实现某个协议,尽量把协议的声明写在“类扩展”,即”.m”文件的”@interface xxx<XXXDelegate> @end”,如果实在不行,那就最好吧协议单独放在一个头文件中,然后将其引入。</p>\n<h3 id=\"多用字面量语法,少用与之等价的方法\"><a href=\"#多用字面量语法,少用与之等价的方法\" class=\"headerlink\" title=\"多用字面量语法,少用与之等价的方法\"></a>多用字面量语法,少用与之等价的方法</h3><p>好处:<br>1、书写简洁,便于阅读。<br>2、使用字面量数组时可以更快的抛出异常,更加安全。<br>局限性:<br>1、自定义创建子类的实例,需要采取“非字面量语法”。</p>\n<h3 id=\"多用类型常量,少用-define预处理指令\"><a href=\"#多用类型常量,少用-define预处理指令\" class=\"headerlink\" title=\"多用类型常量,少用#define预处理指令\"></a>多用类型常量,少用#define预处理指令</h3><p><del>#define ANIMATION_DURATION 0.3</del></p>\n<figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div></pre></td><td class=\"code\"><pre><div class=\"line\">static const NSTimeInterval kAnimationDuration = 0.3</div></pre></td></tr></table></figure>\n<p>1、如果不打算公开变量,可在.m文件中,同时使用static和const来定义常量,如果试图修改该变量编译器就会报错。这种变量只在编译单元内可见,由于不在”全局符号表“中所以无需增加前缀。<br>2、如果打算公开某个常量,则需要这样来实现<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div></pre></td><td class=\"code\"><pre><div class=\"line\">// EOCAnimatedView.h</div><div class=\"line\">extern const NSTimerInterval EOCAnimatedViewAnimationDuration;</div><div class=\"line\">// EOCAnimatedView.m</div><div class=\"line\">const NSTimerInterval EOCAnimatedViewAnimationDuration = 0.3;</div></pre></td></tr></table></figure></p>\n<p>在头文件中声明,在实现文件中定义,由于在”全局符号表“中,为避免名称冲突,最好用与之相关的类名作为前缀。这样定义常量是不可被更改的,而使用#define预处理指令定义的常量很可能遭到别人的无意更改,这是非常危险的事情。</p>\n<h3 id=\"多用类型常量,少用-define预处理指令-1\"><a href=\"#多用类型常量,少用-define预处理指令-1\" class=\"headerlink\" title=\"多用类型常量,少用#define预处理指令\"></a>多用类型常量,少用#define预处理指令</h3><p>1、使用NS_ENUM与NS_OPTIONS宏来定义枚举类型并指明其数据结构。<br>2、应该用枚举来表示状态机的状态,状态码等值。<br>3、如果枚举的多个选项可以同时组合,将这些项定义为2的幂,以便可以通过按位或操作将其组合起来。<br>例如:AnimationEasyIn | AnimationLeft<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div></pre></td><td class=\"code\"><pre><div class=\"line\">typedef NS_ENUM(NSUInteger, AnimationBehavior) {</div><div class=\"line\">AnimationEasyIn = 1 << 0,</div><div class=\"line\">AnimationLeft = 1 << 1</div><div class=\"line\">};</div></pre></td></tr></table></figure></p>\n<p>4、处理枚举类型的switch语句中不要实现default分支,这样的话有新枚举加入,编译器就会提示开发者,switch语句中并未处理所有的枚举。</p>\n<h2 id=\"对象、消息、运行期\"><a href=\"#对象、消息、运行期\" class=\"headerlink\" title=\"对象、消息、运行期\"></a>对象、消息、运行期</h2><h3 id=\"理解“属性”这一概念\"><a href=\"#理解“属性”这一概念\" class=\"headerlink\" title=\"理解“属性”这一概念\"></a>理解“属性”这一概念</h3><p>1、尽量不要直接定义实例变量,推荐使用属性”@proproty”来合成存取方法。使用点语法调用来访问变量。<br>2、在设置属性所对应的实例变量时,一定要遵循该属性所声明的语义。<br>即:<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div></pre></td><td class=\"code\"><pre><div class=\"line\">@property (nonatomic, copy)NSString *name;</div><div class=\"line\">\t</div><div class=\"line\">- (void)setName:(NSString *)name</div><div class=\"line\">{</div><div class=\"line\"> _name = [name copy];</div><div class=\"line\">}</div><div class=\"line\">疑问:</div><div class=\"line\">- (void)setName:(NSString *)name</div><div class=\"line\">{</div><div class=\"line\"> // _name = [name copy];</div><div class=\"line\"> _name = name;</div><div class=\"line\">}</div></pre></td></tr></table></figure></p>\n<p>经过测试,使用_name = name,和上面的效果是一样的,内存地址发生了变化。</p>\n<h3 id=\"在对象内部尽量直接访问实例变量\"><a href=\"#在对象内部尽量直接访问实例变量\" class=\"headerlink\" title=\"在对象内部尽量直接访问实例变量\"></a>在对象内部尽量直接访问实例变量</h3><p>强烈建议在读取实例变量时候采用直接访问的形式,而在设置实例变量的时候通过属性来做。</p>\n<p>理由:<br>1、直接访问属性,而不经过存取方法,直接访问那块内存,速度当然比较快,但是可以忽略不计。<br>2、直接访问属性就绕过了如“strong”、“copy”,等“管理语义”,如果在ARC下直接访问一个声明为copy的对象,并不会拷贝改属性,只会保留新值并释放旧值。<br>3、直接访问实例变量,不会触发“KVO”,<br>合理的方案:<br>在对象内部读取数据时,直接通过实例变量来读,在写入数据时,通过属性来写。<br>注意:<br>1、在初始化方法和dealloc方法中,应该直接访问实例变量,防止子类覆盖设置方法。<br>2、懒加载中,通过获取方法来访问属性,否则实例变量永远不会被初始化。<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div></pre></td><td class=\"code\"><pre><div class=\"line\">- (Person *)person {</div><div class=\"line\">\tif (!_person) {</div><div class=\"line\">\t\t_person = [Person alloc] init];</div><div class=\"line\">\t}</div><div class=\"line\">\treturn _person;</div><div class=\"line\">}</div></pre></td></tr></table></figure></p>\n<h3 id=\"理解“对象等同性”这一概念\"><a href=\"#理解“对象等同性”这一概念\" class=\"headerlink\" title=\"理解“对象等同性”这一概念\"></a>理解“对象等同性”这一概念</h3><p>1、重写isEqual和hash方法,判断对象的等同性。<br>2、利用标识符,类似于数据库的主键,来判断对象的等同性。<br>3、容器中放入可变对象时,慎重改变其哈希码,如:NSMutableSet中加入NSMutableArray。<br>4、不盲目地检查每条属性,按照具体需求来制定检测对象。<br>5、相同的对象必须具有相同的哈希码,但是哈希码相同的对象未必相同。<br>6、编写hash方法时,应该使用计算速度快而且哈希码碰撞几率低的算法。</p>\n<p><a href=\"https://zh.wikipedia.org/wiki/%E5%93%88%E5%B8%8C%E8%A1%A8\">哈希介绍</a><br><a href=\"http://nshipster.cn/equality/\">Equality</a></p>\n<h3 id=\"以“类族模式”隐藏实现细节\"><a href=\"#以“类族模式”隐藏实现细节\" class=\"headerlink\" title=\"以“类族模式”隐藏实现细节\"></a>以“类族模式”隐藏实现细节</h3><p>1、使用类方法创建实例,如:+ (UIButton *)buttonWithType:<br>2、从类族的公共抽象基类中继承子类时要当心,子类应当覆写父类中指明需要覆写的方法</p>\n<h3 id=\"在既有类中使用关联对象存放自定义数据\"><a href=\"#在既有类中使用关联对象存放自定义数据\" class=\"headerlink\" title=\"在既有类中使用关联对象存放自定义数据\"></a>在既有类中使用关联对象存放自定义数据</h3><p>“关联对象”(Associated Object),可以在外部给类添加属性,常用在Category中添加。</p>\n<h3 id=\"理解objc-msgSend的作用\"><a href=\"#理解objc-msgSend的作用\" class=\"headerlink\" title=\"理解objc_msgSend的作用\"></a>理解objc_msgSend的作用</h3><p>1、“静态绑定”编译器在编译阶段就能生成调用函数指令,“动态绑定”运行期才可以生成函数调用指令。<br>2、objc_msgSend函数会在接收者所属类中的“方法列表”中寻找符合的方法,如果找到就执行实现代码,如果找不到,就沿着继承体系,向上继续寻找,如果最终还是找不到,就执行“消息转发操作”,此处可进行手动拦截。<br>3、尾调用优化对于递归具有重要意义,大大减少调用栈的调用记录,防止栈溢出。</p>\n<p><a href=\"http://www.ruanyifeng.com/blog/2015/04/tail-call.html\">尾调用优化</a></p>\n<h3 id=\"理解消息转发机制\"><a href=\"#理解消息转发机制\" class=\"headerlink\" title=\"理解消息转发机制\"></a>理解消息转发机制</h3><p>1、运行时系统没有找到消息的接收者,会发起消息转发,给接收者最后一次机会,所有的细节封装在NSInvocation对象中,在此可以进行拦截处理。<br>2、对象无法收到解读的消息后,首先调用其所属类的类方法:<br>第一步:</p>\n<ul>\n<li>(BOOL)resolveInstanceMethod:(SEL)selector 此处可以使用class_addMethod()添加新方法。<br>第二步:为消息寻找一个备用的接收者,但无法操作这一步的消息。</li>\n</ul>\n<ul>\n<li>(id)forwardingTargetForSelector:(SEL)selector<br>第三步:若发现某调用操作不应该由本类处理,则需要调用超类的同名方法,这样,继承体系的每个子类都有机会处理此调用请求,直至NSObject,如果最后调用了NSObject的方法,会抛出异常,表明消息未得到处理。</li>\n<li>(void)forwardingInvocation:(NSInvocation *)invocation</li>\n</ul>\n<h3 id=\"用“方法调配技术”测试“黑盒方法”\"><a href=\"#用“方法调配技术”测试“黑盒方法”\" class=\"headerlink\" title=\"用“方法调配技术”测试“黑盒方法”\"></a>用“方法调配技术”测试“黑盒方法”</h3><p>在运行期,通过runtime向类中添加或者交换方法实现。</p>\n<h3 id=\"理解“类对象”的用意\"><a href=\"#理解“类对象”的用意\" class=\"headerlink\" title=\"理解“类对象”的用意\"></a>理解“类对象”的用意</h3><p>1、如果类型无法在编译器确定,那么就应该使用类型信息查询方法来探知。isMemberOfClass:判断对象是否为某个类的实例,isKindOfClass:判断对象是否为某个类或者其子类的实例。<br>2、尽量使用类型信息确定对象类型,不要直接比较类对象,因为某些对象可能实现了消息转发功能。<br>如:<br><del>if([object class] == [Person class]){<br>}<del><br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div></pre></td><td class=\"code\"><pre><div class=\"line\">if([object isMemberOfClass:[Person class]] {</div><div class=\"line\">}</div></pre></td></tr></table></figure></p>\n<h2 id=\"接口与API设计\"><a href=\"#接口与API设计\" class=\"headerlink\" title=\"接口与API设计\"></a>接口与API设计</h2><h3 id=\"用前缀避免命名空间冲突\"><a href=\"#用前缀避免命名空间冲突\" class=\"headerlink\" title=\"用前缀避免命名空间冲突\"></a>用前缀避免命名空间冲突</h3><p>1、选择与你公司,应用程序或者与之相关的名称作为类名前缀,并在所有代码中统一所有前缀。<br>2、在Category中给变量,方法添加前缀。<br>3、若自己所开发的程序中用到了第三方库,则应为其中的名称加上前缀。<br>4、所选的前缀应为三个字母(苹果规定的)。</p>\n<h3 id=\"提供全能的初始化方法\"><a href=\"#提供全能的初始化方法\" class=\"headerlink\" title=\"提供全能的初始化方法\"></a>提供全能的初始化方法</h3><p>1、在类中提供一个全能的初始化方法,供其他初始化方法调用。<br>2、若全能初始化方法与超类的不同,则需要覆写超类中对应的方法。<br>3、如果超类的初始化方法不适用于子类,那么应该覆写这个超类方法,并在其中抛出异常。<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div></pre></td><td class=\"code\"><pre><div class=\"line\">-(id)initWithWidth:(float)width andHeight:(float)height</div><div class=\"line\">{</div><div class=\"line\"> @throw [NSException exceptionWithName:...];</div><div class=\"line\">}</div></pre></td></tr></table></figure></p>\n<h3 id=\"实现description方法\"><a href=\"#实现description方法\" class=\"headerlink\" title=\"实现description方法\"></a>实现description方法</h3><p>1、实现description方法返回一串有意义的字符串,来描述该对象,使用NSLog()打印对象时调用。<br>2、实现debugDescription方法返回一串有意义的字符串,来描述该对象,在开发者断点调试通过LLDB命令po对象时调用。</p>\n<h3 id=\"尽量使用不可变对象\"><a href=\"#尽量使用不可变对象\" class=\"headerlink\" title=\"尽量使用不可变对象\"></a>尽量使用不可变对象</h3><p>1、尽量把对外部公布出去的属性设置为只读(readonly)<br>2、如果想修改封装在对象内部的数据,但是又不想别人在外部修改,这时需要在.m文件中重新把属性声明为readwrite,但是这样会产生“竞态条件”,需要将对象的所有数据进行同步,参见41条。<br>3、通过KVC仍可以修改只读属性的值,这时不符合API规范的。<br>4、不要把可变的集合对象作为属性公开,而是提供相应的方法修改集合对象。</p>\n<h3 id=\"使用清晰而协调的命名方式\"><a href=\"#使用清晰而协调的命名方式\" class=\"headerlink\" title=\"使用清晰而协调的命名方式\"></a>使用清晰而协调的命名方式</h3><p>1、尽量使用长方法名,清晰的说明方法的意思,但是也要尽量言简意赅,可参考UIKit命名规范。</p>\n<p><del>-(id)initWithSize:(float)width :(float)height<del><br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div></pre></td><td class=\"code\"><pre><div class=\"line\">-(id)initWithWidth:(float)width andHeight:(float)height</div></pre></td></tr></table></figure></p>\n<h3 id=\"为私有方法名加前缀\"><a href=\"#为私有方法名加前缀\" class=\"headerlink\" title=\"为私有方法名加前缀\"></a>为私有方法名加前缀</h3><p>1、给私有方法的名称加上前缀,便于跟公共方法区分。<br>2、不能用单一下划线做前缀,这是苹果私有API的前缀,会冲突。</p>\n<h3 id=\"理解Objective-C错误模型\"><a href=\"#理解Objective-C错误模型\" class=\"headerlink\" title=\"理解Objective-C错误模型\"></a>理解Objective-C错误模型</h3><p>1、“-fojc-arc-exception”编译标识可以在执行异常代码时不抛出异常<br>2、异常用于处理致命问题,无需考虑恢复问题,应用程序直接退出,非致命问题使用NSError对象。<br>3、通过“输出参数”方式把NSError对象回传给调用者<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div><div class=\"line\">13</div><div class=\"line\">14</div><div class=\"line\">15</div></pre></td><td class=\"code\"><pre><div class=\"line\">NSError *error = nil;</div><div class=\"line\">BOOL ret = [object doSomething:&error];</div><div class=\"line\">if (ret) {</div><div class=\"line\"> // There was an error</div><div class=\"line\">}</div><div class=\"line\">- (Bool)doSomething:(NSError **)error {</div><div class=\"line\"> if (// there was an error) {</div><div class=\"line\"> if (error) {</div><div class=\"line\"> *error = [NSError errorWithDomain:...];</div><div class=\"line\"> }</div><div class=\"line\"> return NO;</div><div class=\"line\"> } else {</div><div class=\"line\"> return YES;</div><div class=\"line\"> }</div><div class=\"line\">}</div></pre></td></tr></table></figure></p>\n<p>在error要指向一个新的对象时(解引用),必须先保证error参数不是nil,因为空指针解引用会导致“段错误”,并使应用程序崩溃。调用者在不关心具体错误时,会给error参数传入nil,因此必须判断这种情况。</p>\n<h3 id=\"理解NSCopying协议\"><a href=\"#理解NSCopying协议\" class=\"headerlink\" title=\"理解NSCopying协议\"></a>理解NSCopying协议</h3><p>1、想让自定义对象具有拷贝功能,需要实现NSCopying协议。<br>2、对象拷贝分为深拷贝和浅拷贝,一般情况下尽量执行浅拷贝。<br>3、如果对象需要深拷贝,可以考虑增加一个专门执行深拷贝的方法。<br>4、如果自定义对象分为可变和不可变版本,需要同时实现NSCopying和NSMutableCopying协议。</p>\n<h2 id=\"协议与分类\"><a href=\"#协议与分类\" class=\"headerlink\" title=\"协议与分类\"></a>协议与分类</h2><h3 id=\"通过委托与数据源协议进行对象间通信\"><a href=\"#通过委托与数据源协议进行对象间通信\" class=\"headerlink\" title=\"通过委托与数据源协议进行对象间通信\"></a>通过委托与数据源协议进行对象间通信</h3><p>1、委托模式为对象提供一套接口,通过接口可将相关事件告知其他对象。<br>2、将委托对象应该支持的接口定义成协议,在协议中将可能需要处理的事件定义为方法。<br>3、当使用委托模式传递数据时,该模式也叫“数据源协议”,如UITableViewDataSource<br>4、使用“位域”(含有位段的结构体),将委托对象是否响应相关协议的信息缓存其中。<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div><div class=\"line\">13</div></pre></td><td class=\"code\"><pre><div class=\"line\">struct {</div><div class=\"line\"> unsigned int didReceiveData : 1;</div><div class=\"line\"> unsigned int didFailWithError : 1;</div><div class=\"line\"> unsigned int didUpdateProgressTo : 1;</div><div class=\"line\">} _delegateFlags;</div><div class=\"line\"> </div><div class=\"line\">- (void)setDelegate:(id<...>)delegate {</div><div class=\"line\"> _delegateFlags.didReceiveData = [delegate respondsToSelector:@selctor(...)];</div><div class=\"line\">}</div><div class=\"line\"> </div><div class=\"line\">if (_delegateFlags.didReceiveData) {</div><div class=\"line\"> [_delegate ....];</div><div class=\"line\">}</div></pre></td></tr></table></figure></p>\n<h3 id=\"将类的实现代码分散到便于管理的数个分类之中\"><a href=\"#将类的实现代码分散到便于管理的数个分类之中\" class=\"headerlink\" title=\"将类的实现代码分散到便于管理的数个分类之中\"></a>将类的实现代码分散到便于管理的数个分类之中</h3><p>1、使用分类机制把类的实现代码划分成易于管理的小块。<br>2、将应该私有的方法归入名叫Private的分类中,以隐藏实现细节。</p>\n<h3 id=\"总是为第三方类的分类名称加前缀\"><a href=\"#总是为第三方类的分类名称加前缀\" class=\"headerlink\" title=\"总是为第三方类的分类名称加前缀\"></a>总是为第三方类的分类名称加前缀</h3><p>1、如果多个分类重载“主实现”的相关方法,以最后一个分类为主,即:分类在项目中编译的顺序。<br>2、以命名空间来区分分类中所定义的方法,三个小写字母加下划线:abc_xxx</p>\n<h3 id=\"请勿在分类中声明属性\"><a href=\"#请勿在分类中声明属性\" class=\"headerlink\" title=\"请勿在分类中声明属性\"></a>请勿在分类中声明属性</h3><p>1、分类不可以定义属性,如果非要这么做,可以使用“关联对象”。<br>2、把封装数据所用的全部属性都定义在主类中。<br>3、可以定义存取方法但是尽量不要定义属性。</p>\n<h3 id=\"使用“class-continuation分类”隐藏实现细节\"><a href=\"#使用“class-continuation分类”隐藏实现细节\" class=\"headerlink\" title=\"使用“class-continuation分类”隐藏实现细节\"></a>使用“class-continuation分类”隐藏实现细节</h3><p>“class-continuation分类”也叫“类扩展”。<br>1、通过“class-continuation分类”,向类中增加实例变量。<br>2、私有方法声明在“class-continuation分类”中。<br>3、私有的协议也可以声明在“class-continuation分类”中。</p>\n<h3 id=\"通过协议提供匿名对象\"><a href=\"#通过协议提供匿名对象\" class=\"headerlink\" title=\"通过协议提供匿名对象\"></a>通过协议提供匿名对象</h3><p>1、协议可以在某种程度上提供匿名类型,具体对象类型可以淡化为遵从某一协议的id类型,协议里规定了对象所应该实现的方法。<br>2、使用匿名对象id<xxx>来隐藏类型名称。<br>3、如果具体类型不重要,重要的是对象能够响应协议里的特定方法,那么可以用匿名对象来表示。也就是说,只暴露使用者关心的,隐藏其不需要关注的。</p>\n<h2 id=\"内存管理\"><a href=\"#内存管理\" class=\"headerlink\" title=\"内存管理\"></a>内存管理</h2><h3 id=\"理解引用计数器\"><a href=\"#理解引用计数器\" class=\"headerlink\" title=\"理解引用计数器\"></a>理解引用计数器</h3><p>1、非ARC通过引用计数器增减来管理内存,对象创建好之后,引用计数器至少为1,若引用计数为正,对 象继续存活,当保留计数降为0时,对象就被销毁了。<br>2、在对象生命周期中,其他对象通过引用来保留或者释放此对象,保留与释放操作分别会使引用计数递增和递减。<br>3、不要操作“悬挂指针”(野指针),会引起崩溃,最好将其变为“空指针”。<br>4、set方法 strong retain新值,release旧值,然后赋值。<br>5、autoreleasepool能延长对象生命期,在下次运行循环或者更早一些release对象。<br>6、使用“弱引用”可以防止循环引用。</p>\n<h3 id=\"以ARC简化引用计数\"><a href=\"#以ARC简化引用计数\" class=\"headerlink\" title=\"以ARC简化引用计数\"></a>以ARC简化引用计数</h3><p>1、ARC会自动补上引用计数代码,但是并没有使用Objective-C的消息转发,而是直接通过C代码,性能会更好。<br>2、ARC只管理Objective-C对象的内存,CoreFoundation对象不归ARC管理,开发者必须适时调用CFRetain/CFRelease。<br>3、ARC对引用计数进行了特殊优化,如果发现对象在运行期进行多次保留和释放操作,会成对的移除这些操作,只保留有用操作,从而提高效率。<br>4、ARC对存取方法进行了优化,不需要再去关注先保留新值,再释放旧值,直接赋值即可。<br>5、ARC借助Objective-C++的特性清理对象,回收Objective-C对象调用多有C++对象的“析构函数”,如发现某个对象里面有C++对象,会生成.cxx_destruct的方法,并在该方法中生成清理内存所需代码。如果有非Objective-C对象(CoreFoundation对象或者malloc()分配的堆内存),不会调用父类的dealloc方法,会生成.cxx_destruct的方法,并在该方法中生成清理内存所需代码,在生成的代码中自动调用父类的dealloc方法。因此可以这样写:<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div></pre></td><td class=\"code\"><pre><div class=\"line\">-(void)dealloc {</div><div class=\"line\"> CFRelease(...);</div><div class=\"line\"> free(...);</div><div class=\"line\">}</div></pre></td></tr></table></figure></p>\n<h3 id=\"在dealloc方法中只释放引用并解除监听\"><a href=\"#在dealloc方法中只释放引用并解除监听\" class=\"headerlink\" title=\"在dealloc方法中只释放引用并解除监听\"></a>在dealloc方法中只释放引用并解除监听</h3><p>1、可以在dealloc方法中注销通知观察者等。<br>2、比如文件,套接字,大块内存等开销较大或者系统内稀缺资源不可以在dealloc方法中释放,需要用完即释放。<br>3、系统并不能保证每个创建的对象的dealloc方法都会调用,个别对象在应用程序终止时仍处于存活状态,由于应用程序终止,将内存返还给操作系统,所以实际上这些对象也算是销毁了。所以在系统回收之前我们可以手动清理这些对象,在UIApplicationDelegate/NSApplicationDelegate的委托方法中处理比较合适。<br>4、不要再dealloc方法中随便调用别的方法,存取方法也不要调用,因为这样可能会触发观察者,还是使用下划线比较稳妥。</p>\n<h3 id=\"编写”异常安全代码“时留意内存管理问题\"><a href=\"#编写”异常安全代码“时留意内存管理问题\" class=\"headerlink\" title=\"编写”异常安全代码“时留意内存管理问题\"></a>编写”异常安全代码“时留意内存管理问题</h3><p>1、捕获异常时,一定要将try块内的对象清理干净。<br>2、在默认情况下,ARC不生成安全处理异常所需的清理代码,开启”-fobjc-arc-exceptions“标识后,可生成这种代码,不过会导致应用程序变大,而且会降低运行效率。<br>3、如果发现大量异常捕获操作时,考虑使用NSError错误传递来重构。</p>\n<h3 id=\"以弱引用避免保留环\"><a href=\"#以弱引用避免保留环\" class=\"headerlink\" title=\"以弱引用避免保留环\"></a>以弱引用避免保留环</h3><p>1、某些引用设置为weak可以避免出现”保留环“(循环引用)。<br>2、weak与unsafe_unretained的区别:<br>相同:都是弱引用,用来表示”非拥有关系“。<br>不同:weak 系统如果把属性回收,属性自动设置为nil;unsafe_unretained 系统如果把属性回收,属性仍然指向那个已经回收的实例,也就是”野指针“,继续操作属性会使程序崩溃,<br>总的来说,weak更加安全一些,但是性能比unsafe_unretained低些。<br>3、一般来说,如果不拥有某个对象就不要去保留它。这条规则对集合类对象例外,因为集合类对象并不直接拥有其内容,而是通过自己内部的元素来保留这个对象。使用weak尽量也不要去使用一个已经释放的弱引用对象,尽管不会崩溃,但是这依然是一个bug。</p>\n<h3 id=\"以”自动释放池块“降低内存峰值\"><a href=\"#以”自动释放池块“降低内存峰值\" class=\"headerlink\" title=\"以”自动释放池块“降低内存峰值\"></a>以”自动释放池块“降低内存峰值</h3><p>1、自动释放池排布在栈中,对象收到autorelease消息后,系统将其放入最顶端的池里。<br>2、合理利用自动释放池可以降低内存峰值,如:在for循环内部使用自动释放池包裹代码。<br>3、@autoreleasepool这种写法可以创建更轻便的自动释放池。</p>\n<h3 id=\"用”僵尸对象“调试内存管理问题\"><a href=\"#用”僵尸对象“调试内存管理问题\" class=\"headerlink\" title=\"用”僵尸对象“调试内存管理问题\"></a>用”僵尸对象“调试内存管理问题</h3><p>1、系统再回收对象时,可以不将其真的回收,而是把它转化成僵尸对象,通过环境变量NSZombieEnabled可以开启此功能。<br>2、系统会修改对象的isa指针,另其指向特殊的僵尸类,从而使该对象变为僵尸对象,僵尸类能够响应所有的选择子,响应方式为:打印一条包含信息内容及接收者的消息,然后终止程序。</p>\n<h3 id=\"不要使用retainCount\"><a href=\"#不要使用retainCount\" class=\"headerlink\" title=\"不要使用retainCount\"></a>不要使用retainCount</h3><p>1、在ARC中retainCount方法已经被废弃,因为它只能返回特定时间点的引用计数器,而未考虑系统稍后会吧自动释放池清空的情况。或者是retainCount永远不返回0,因为系统可能会优化对象的释放行为,在引用计数是1的时候就回收对象,引用计数可能永远不会是0,所以引用计数是不准确的,就算能够正常返回时凭运气。<br>2、单例对象的引用计数是不会改变的,其保留和释放都是空操作,retainCount已经被废弃了,任何对象的retainCount都是不确定的,所以retainCount绝对不要用。</p>\n<h2 id=\"块与大中枢派发\"><a href=\"#块与大中枢派发\" class=\"headerlink\" title=\"块与大中枢派发\"></a>块与大中枢派发</h2><h3 id=\"理解“块”这一概念\"><a href=\"#理解“块”这一概念\" class=\"headerlink\" title=\"理解“块”这一概念\"></a>理解“块”这一概念</h3><p>1、默认情况,block所捕获的变量不能被修改,声明变量时加上<strong>block就可以修改。但是类的实例变量不需要加</strong>block即可被修改。<br>2、使用block小心因捕获了self而造成循环引用的情况。如果访问了类的实例变量,self也会被捕获。<br>3、block可以分配在栈或者堆上,也可以是全局的。分配在栈上的block可以拷贝到堆上,这样的话,就和标准的Objective-C对象一样,具备引用计数了。<br>4、全局的block无法捕获任何状态(变量),运行时也无需状态参与,所使用的内存区域在编译时就确定了。<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div></pre></td><td class=\"code\"><pre><div class=\"line\">void (^block)() = ^{</div><div class=\"line\"> NSLog("This is a block!");</div><div class=\"line\">};</div></pre></td></tr></table></figure></p>\n<h3 id=\"为常用的块类型创建typedef\"><a href=\"#为常用的块类型创建typedef\" class=\"headerlink\" title=\"为常用的块类型创建typedef\"></a>为常用的块类型创建typedef</h3><p>1、以typedef重新定义block类型,可令块block变量用起来更加简单,可读性更好。<br>2、定义新类型时遵循现有命名习惯,不要发生命名冲突。<br>3、不妨为同一个block定义多个类型别名,如果要重构的代码使用了block类型的某个别名,那么只需修改相应typedef中的签名即可,无需改动其他typedef。</p>\n<h3 id=\"用handler块降低代码分散程度\"><a href=\"#用handler块降低代码分散程度\" class=\"headerlink\" title=\"用handler块降低代码分散程度\"></a>用handler块降低代码分散程度</h3><p>1、使用block来取代delegate可以使代码更加紧凑,便于阅读。<br>2、在网络请求的API设计中,尽量用一个handlerl来处理数据及错误,更加灵活。<br>推荐:<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div></pre></td><td class=\"code\"><pre><div class=\"line\">[fetcher startWithCompletionHander:^(NSData *data, NSError *error){</div><div class=\"line\"> if (error) {</div><div class=\"line\"> // failed</div><div class=\"line\"> } else {</div><div class=\"line\"> // success</div><div class=\"line\"> }</div><div class=\"line\">}];</div></pre></td></tr></table></figure></p>\n<p>不推荐:<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div></pre></td><td class=\"code\"><pre><div class=\"line\">[fetcher startWithCompletionHandler:^(NSData *data){</div><div class=\"line\"> // success</div><div class=\"line\">} failureHandler:^(NSError *error){</div><div class=\"line\"> // failed</div><div class=\"line\">}];</div></pre></td></tr></table></figure></p>\n<p>3、设计API是如果用到handler块,可以增加一个参数,使调用者可以通过此参数来决定应该把块安排在哪个队列执行。</p>\n<h3 id=\"使用块引用其所属对象时不要出现保留环\"><a href=\"#使用块引用其所属对象时不要出现保留环\" class=\"headerlink\" title=\"使用块引用其所属对象时不要出现保留环\"></a>使用块引用其所属对象时不要出现保留环</h3><p>1、如果块所捕获的对象直接或者间接保留了块本身,那么就会造成保留环问题。<br>2、一定要找一个适当的时机解除保留环,而不能把责任推给API的调用者。<br>以下是两种会出现保留环的写法:<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div></pre></td><td class=\"code\"><pre><div class=\"line\">1、_fetcher捕获了block block捕获了_fetcher</div><div class=\"line\">_fetcher = [[xxx alloc] init];// 属性</div><div class=\"line\">[_fetcher startWithCompletionHander:^(NSData *data, NSError *error){</div><div class=\"line\"> NSLog(@"%@", fetcher.url);</div><div class=\"line\"> _fetchData = data;</div><div class=\"line\">}];</div><div class=\"line\">2、fetcher捕获了block block捕获了fetcher.url</div><div class=\"line\">xxx *fetcher = [[xxx alloc] init];// 临时变量</div><div class=\"line\">[fetcher startWithCompletionHander:^(NSData *data, NSError *error){</div><div class=\"line\"> NSLog(@"%@", fetcher.url);</div><div class=\"line\"> _fetchData = data;</div><div class=\"line\">}];</div></pre></td></tr></table></figure></p>\n<p>解决方案:<br>1、weakSelf和strongSelf。<br>2、在block调用后置为nil。</p>\n<h3 id=\"多用派发队列,少用同步锁\"><a href=\"#多用派发队列,少用同步锁\" class=\"headerlink\" title=\"多用派发队列,少用同步锁\"></a>多用派发队列,少用同步锁</h3><p>1、使用锁可以用来实现同步机制,但会带来性能甚至死锁的问题。<br>2、将同步与异步派发结合起来,可以实现与普通锁一样的同步行为,而这么做也不会阻塞执行异步派发的线程。<br>3、使用同步队列及栅栏块(dispatch_barrier_xxx),可以令同步行为更加高效。</p>\n<h3 id=\"多用GCD,少用performSelector系列方法\"><a href=\"#多用GCD,少用performSelector系列方法\" class=\"headerlink\" title=\"多用GCD,少用performSelector系列方法\"></a>多用GCD,少用performSelector系列方法</h3><p>1、使用[object performSelector:@selector(selectorName)]方法可能会造成内存泄漏,ARC不会添加相关的释放操作,因此有可能会造成内存泄漏。<br>2、可以使用GCD来代替。</p>\n<h3 id=\"掌握GCD及操作队列的使用时机\"><a href=\"#掌握GCD及操作队列的使用时机\" class=\"headerlink\" title=\"掌握GCD及操作队列的使用时机\"></a>掌握GCD及操作队列的使用时机</h3><p>1、GCD并不是最优的办法,在某些情况下使用操作队列(NSOperation)可能会更好一些。<br>2、NSOperation的优势:取消某个操作,制定操作的依赖关系,通过KVO监控NSOperation对象属性,指定操作优先级。<br>3、GCD基于任务的队列,NSOperation基于操作的队列。</p>\n<h3 id=\"通过Dispatch-Group机制,根据系统资源状况来执行任务\"><a href=\"#通过Dispatch-Group机制,根据系统资源状况来执行任务\" class=\"headerlink\" title=\"通过Dispatch Group机制,根据系统资源状况来执行任务\"></a>通过Dispatch Group机制,根据系统资源状况来执行任务</h3><p>1、一系列任务可放在一个dispatch group中,开发者可以在这组任务执行完获得通知。<br>2、通过dispatch group,可以并发执行多项任务,GCD会根据系统资源来调度执行任务。</p>\n<h3 id=\"使用dispatch-once来执行只需运行一次的线程安全代码\"><a href=\"#使用dispatch-once来执行只需运行一次的线程安全代码\" class=\"headerlink\" title=\"使用dispatch_once来执行只需运行一次的线程安全代码\"></a>使用dispatch_once来执行只需运行一次的线程安全代码</h3><p>1、使用dispatch_once实现单例可以保证线程安全。<br>2、标记声明为static或者global作用域中,这样可以保证执行dispatch_once函数时,传入的标记也是相同的。</p>\n<h3 id=\"不要使用dispatch-get-current-queue\"><a href=\"#不要使用dispatch-get-current-queue\" class=\"headerlink\" title=\"不要使用dispatch_get_current_queue\"></a>不要使用dispatch_get_current_queue</h3><p>1、dispatch_get_current_queue已经废弃,最好不要使用,可能会产生死锁问题。</p>\n<h2 id=\"系统框架\"><a href=\"#系统框架\" class=\"headerlink\" title=\"系统框架\"></a>系统框架</h2><h3 id=\"熟悉系统框架\"><a href=\"#熟悉系统框架\" class=\"headerlink\" title=\"熟悉系统框架\"></a>熟悉系统框架</h3><p>请记住:用纯C写成的框架与用Objective-C写成的一样重要,若想成为优秀的Objective-C开发者,应掌握C语言的核心概念。</p>\n<h3 id=\"多用块枚举,少用for循环\"><a href=\"#多用块枚举,少用for循环\" class=\"headerlink\" title=\"多用块枚举,少用for循环\"></a>多用块枚举,少用for循环</h3><p>1、遍历集合有四种方式,最基本的办法是for循环,其次是NSEnumerator遍历法及快速遍历法,最新,最先进的方式是“块枚举法”,也就是block。<br>2.“块枚举法”通过GCD并发执行遍历操作,效率较高,推荐使用。<br>3、若提前知道待遍历的collection含有何种对象,则应修改块签名,指出对象的类型。</p>\n<h3 id=\"对自定义其内存管理语义的collection使用无缝桥接\"><a href=\"#对自定义其内存管理语义的collection使用无缝桥接\" class=\"headerlink\" title=\"对自定义其内存管理语义的collection使用无缝桥接\"></a>对自定义其内存管理语义的collection使用无缝桥接</h3><p>1、<strong>bridge本身意思是:ARC仍然具备这个Objective-C对象的所有权。</strong>bridge_retained则与之相反,意味着ARC交出所有权,后面需要加上CFRelease()以释放对象。<br>2、通过无缝桥接技术,可以在Foundation框架中的Objective-C对象与CoreFoundation框架中的C语言数据结构之间来回转换。<br>2、在CoreFoundation层面创建collection时,可以指定许多回调函数,这些函数表示此collection应该如何处理元素,然后,可以运用无缝桥接技术,将其转换成具备特殊内存管理语义的Objective-C collection。</p>\n<h3 id=\"构建缓存时选用NSCache而非NSDictionary\"><a href=\"#构建缓存时选用NSCache而非NSDictionary\" class=\"headerlink\" title=\"构建缓存时选用NSCache而非NSDictionary\"></a>构建缓存时选用NSCache而非NSDictionary</h3><p>1、NSCache胜过NSDictionary之处在于,当系统资源将要耗尽时,他可以自动删减缓存。NSCache并不会“拷贝”键,而是会”保留“它,而且是线程安全的。<br>2、可以给NSCache对象设置上限,用以限制缓存中的对象总个数及“总成本”,而这些尺度则定义了缓存删减其中对象的时机。但是绝对不要把这些尺度当成可靠的“硬限制”,他们仅对NSCache起到指导作用。<br>3、将NSPurgeableData与NSCache搭配使用,可实现自动清除数据的功能,也就是说当NSPurgeableData对象所占内存为系统所丢弃时,该对象自身也将从缓存中清除。<br>4、如果缓存使用得当,那么应用程序的响应速度就能提高。只有那种“重新计算起来很费事的”数据,才值得放入缓存,比如那些需要从网络获取或者从磁盘中读取的数据。</p>\n<h3 id=\"精简initialize与load的实现代码\"><a href=\"#精简initialize与load的实现代码\" class=\"headerlink\" title=\"精简initialize与load的实现代码\"></a>精简initialize与load的实现代码</h3><p>1、+ (void)load 当包含类或者分类的程序载入系统时,就会执行此方法,通常是指程序启动的时候,此时运行时是混乱的状态,如果使用了其他的类,其他的类并不一定是初始化好了的。<br>2、load方法的实现尽量精简,它不遵循那套继承规则,很难确定执行顺序,且load方式执行时应用会阻塞,如果在该方法里面执行了大量的耗时操作,那么程序就会无响应,所以一般不要使用此方法。<br>3、+(void)initialize 会在程序首次使用该类之前调用,且只调用一次。与load方法的区别:首先它是“惰性”调用,只有程序在用到该类才会调用。此时运行时是正常状态,且执行环境是线程安全的。<br>4、在编写load方法与initialize要保证代码实现尽量简单,除了初始化全局属性外,最好也不要调用自己的其他的方法。如:无法再编译期设定的全局常量,可以放在initialize方法里面初始化。</p>\n<h3 id=\"别忘了NSTimer会保留其目标对象\"><a href=\"#别忘了NSTimer会保留其目标对象\" class=\"headerlink\" title=\"别忘了NSTimer会保留其目标对象\"></a>别忘了NSTimer会保留其目标对象</h3><p>1、NSTimer对象会保留其目标对象,直到计时器本身失效为止,调用invalidate方法可令计时器失效,另外,一次性的计时器在触发完任务之后也会失效。<br>2、反复执行任务的计时器很容易引入保留环,如果计时器的目标对象又保留了计时器本身,那么肯定会导致保留环,这种保留环关系,可能是由于直接或者间接发生的。<br>3、可以扩充NSTimer的功能,用block来打破保留环。<br> // 把block作为userInfo的参数传入,一定要先拷贝到堆上,不然一会执行block时可能就被释放了。<br><figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div><div class=\"line\">13</div><div class=\"line\">14</div><div class=\"line\">15</div><div class=\"line\">16</div></pre></td><td class=\"code\"><pre><div class=\"line\">+ (void)_yy_ExecBlock:(NSTimer *)timer {</div><div class=\"line\"> if ([timer userInfo]) {</div><div class=\"line\"> void (^block)(NSTimer *timer) = (void (^)(NSTimer *timer))[timer userInfo];</div><div class=\"line\"> block(timer);</div><div class=\"line\"> }</div><div class=\"line\">}</div><div class=\"line\">+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)seconds </div><div class=\"line\"> block:(void (^)(NSTimer *timer))block </div><div class=\"line\"> repeats:(BOOL)repeats {</div><div class=\"line\"> </div><div class=\"line\"> return [NSTimer scheduledTimerWithTimeInterval:seconds </div><div class=\"line\"> target:self</div><div class=\"line\"> selector:@selector(_yy_ExecBlock:)</div><div class=\"line\"> userInfo:[block copy]</div><div class=\"line\"> repeats:repeats];</div><div class=\"line\">}</div></pre></td></tr></table></figure></p>"},{"layout":"post","title":"Python爬虫实践","date":"2017-03-21T16:00:00.000Z","comments":1,"keywords":"Python爬虫实践","publish":true,"description":"Python爬虫实践","_content":">看了[廖雪峰老师的Python教程](http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000)觉得非常的棒,浅显易懂,知识丰富,很适合初学者入门。看了一段时间,决定写点小东西练习一下,于是,就打算使用Python抓取一下廖雪峰老师的Python教程😏。\n\n<!-- more -->\n## 前言\n打开廖雪峰老师的Python3教程,由于是个人博客,内容也十分简洁,而我们需要抓取的内容也很容易找到。工欲善其事必先利其器,先安装好Python3和PyCharm开发工具,这里就不在赘述了。\n## 分析\n\n我们先打开这篇教程,就是这个:\n\n\n\n在抓取前我们先看一下网页的源码,找到我们需要抓取的标签。如图:\n\n\n\n不难发现,上图的`<ul>`标签就是我们需要抓取的目标,也就是网页左侧的目录,我们需要的文章链接和标题都在这里。\nOK!现在万事具备了,大致可以指定以下流程了:\n\n```\n1. 获取整个html的内容;\n2. 从html中匹配出我们所需的文章链接及标题;\n3. 下载整个html或者是保存为PDF\n```\n大致就是这个样子吧,至于步骤三如果下载html的话还需要下载整个页面的css文件,这里先只下载html吧。\n## 开始\n为了完成步骤1,我们先编写一个根据url地址,获取网页内容的函数:\n\n```\ndef url_open(url):\n url = re.sub(r'^//*', 'http://', url)\n html = urllib.request.urlopen(url)\n return html.read()\n```\n`re`是Python内置的处理正则的模块,上面的代码把以`//`开头的链接替换为`http://`开头的完整url,并读取整个html的内容。\n之后我们就可以在整个页面的内容中寻找我们所需要的内容了,这并没有什么难度,关键是如何利用好正则。\n\n```\n# 获取文章标题和链接\ndef find_itemlist(url):\n html = url_open(url).decode('utf-8')\n soup = BeautifulSoup(html)\n # 获取<ul>标签内容\n ul = soup.find_all('ul', class_='uk-nav uk-nav-side', style=\"margin-right:-15px;\")\n print(ul)\n if len(ul):\n ulstr = str(ul[0])\n # 获取<a>标签内容\n pattern = r'<a.*>.*</a>'\n li = re.findall(pattern, ulstr)\n items = []\n for a in li:\n # 获取href标签内容\n hrefs = re.findall(r'href=\".*\"', a)\n if len(hrefs):\n href = hrefs[0]\n href = href[6:-1]\n print(href)\n # 获取文章标题\n titles = re.findall(r'>.*</a>', a)\n if len(titles):\n title = titles[0]\n title = title[1:-4]\n print(title)\n items.append({'title':title, 'href':href})\n return items\n```\n原谅我渣渣的正则水平,我先使用Python的BeautifulSoup模块获取了`<ul>...</ul>`标签内容,然后又从中获取到了`<a>`标签内容,最后从`<a>`标签中获取`href`标签内容和文章的标题。现在我们有了一个装有文章标题和链接的数组,接下来想干嘛就可以干嘛了😏。\n\n```\n# 保存html文件\ndef save_html(url, file_name):\n html = url_open(url)\n # 注意文件名称不能带有斜杠,需要用其他字符串代替。\n with open(file_name.replace('/','_') + '.html', 'wb') as f:\n try:\n f.write(html)\n print(file_name + '保存完成')\n except:\n print(file_name + '写入失败')\n \n# 遍历数组,开始写入文件 \ndef download(items):\n # 创建根文件夹\n root = 'XXX'\n if os.path.exists(root):\n os.remove(root)\n os.mkdir(root)\n os.chdir(root)\n basurl = 'http://www.liaoxuefeng.com'\n for item in items:\n url = item['href']\n url = basurl + url\n file_name = item['title']\n save_html(url, file_name,)\n os.close()\n print(\"全部文章共%s篇,保存完成!\" % len(items))\n\n```\n至此,我们的小爬虫就算完成了,虽然很简单,但也是一个好的开始,如果你有兴趣可以吧所有内容转换成PDF保存,我尝试了第三方生成PDF的库`pdfkit`,转成PDF的效果并不是很好,代码其实很简单,如下:\n\n```\ndef save_pdf(url, file_name):\n try:\n pdfkit.from_url(url, file_name.replace('/','_') + '.pdf')\n print(file_name + '保存完成')\n except:\n print(file_name + '写入失败')\n```\n## 最后\n其实,这里写入文件的操作用多线程效率会更加的高一些,留着下次尝试吧,本篇结束😝。\n\n","source":"_posts/2017-03-22-Python爬虫实践.md","raw":"---\nlayout: post\ntitle: \"Python爬虫实践\"\ndate: 2017-03-22\ncomments: true\ncategories: Python\ntags: [Python]\nkeywords: Python爬虫实践\npublish: true\ndescription: Python爬虫实践\n---\n>看了[廖雪峰老师的Python教程](http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000)觉得非常的棒,浅显易懂,知识丰富,很适合初学者入门。看了一段时间,决定写点小东西练习一下,于是,就打算使用Python抓取一下廖雪峰老师的Python教程😏。\n\n<!-- more -->\n## 前言\n打开廖雪峰老师的Python3教程,由于是个人博客,内容也十分简洁,而我们需要抓取的内容也很容易找到。工欲善其事必先利其器,先安装好Python3和PyCharm开发工具,这里就不在赘述了。\n## 分析\n\n我们先打开这篇教程,就是这个:\n\n\n\n在抓取前我们先看一下网页的源码,找到我们需要抓取的标签。如图:\n\n\n\n不难发现,上图的`<ul>`标签就是我们需要抓取的目标,也就是网页左侧的目录,我们需要的文章链接和标题都在这里。\nOK!现在万事具备了,大致可以指定以下流程了:\n\n```\n1. 获取整个html的内容;\n2. 从html中匹配出我们所需的文章链接及标题;\n3. 下载整个html或者是保存为PDF\n```\n大致就是这个样子吧,至于步骤三如果下载html的话还需要下载整个页面的css文件,这里先只下载html吧。\n## 开始\n为了完成步骤1,我们先编写一个根据url地址,获取网页内容的函数:\n\n```\ndef url_open(url):\n url = re.sub(r'^//*', 'http://', url)\n html = urllib.request.urlopen(url)\n return html.read()\n```\n`re`是Python内置的处理正则的模块,上面的代码把以`//`开头的链接替换为`http://`开头的完整url,并读取整个html的内容。\n之后我们就可以在整个页面的内容中寻找我们所需要的内容了,这并没有什么难度,关键是如何利用好正则。\n\n```\n# 获取文章标题和链接\ndef find_itemlist(url):\n html = url_open(url).decode('utf-8')\n soup = BeautifulSoup(html)\n # 获取<ul>标签内容\n ul = soup.find_all('ul', class_='uk-nav uk-nav-side', style=\"margin-right:-15px;\")\n print(ul)\n if len(ul):\n ulstr = str(ul[0])\n # 获取<a>标签内容\n pattern = r'<a.*>.*</a>'\n li = re.findall(pattern, ulstr)\n items = []\n for a in li:\n # 获取href标签内容\n hrefs = re.findall(r'href=\".*\"', a)\n if len(hrefs):\n href = hrefs[0]\n href = href[6:-1]\n print(href)\n # 获取文章标题\n titles = re.findall(r'>.*</a>', a)\n if len(titles):\n title = titles[0]\n title = title[1:-4]\n print(title)\n items.append({'title':title, 'href':href})\n return items\n```\n原谅我渣渣的正则水平,我先使用Python的BeautifulSoup模块获取了`<ul>...</ul>`标签内容,然后又从中获取到了`<a>`标签内容,最后从`<a>`标签中获取`href`标签内容和文章的标题。现在我们有了一个装有文章标题和链接的数组,接下来想干嘛就可以干嘛了😏。\n\n```\n# 保存html文件\ndef save_html(url, file_name):\n html = url_open(url)\n # 注意文件名称不能带有斜杠,需要用其他字符串代替。\n with open(file_name.replace('/','_') + '.html', 'wb') as f:\n try:\n f.write(html)\n print(file_name + '保存完成')\n except:\n print(file_name + '写入失败')\n \n# 遍历数组,开始写入文件 \ndef download(items):\n # 创建根文件夹\n root = 'XXX'\n if os.path.exists(root):\n os.remove(root)\n os.mkdir(root)\n os.chdir(root)\n basurl = 'http://www.liaoxuefeng.com'\n for item in items:\n url = item['href']\n url = basurl + url\n file_name = item['title']\n save_html(url, file_name,)\n os.close()\n print(\"全部文章共%s篇,保存完成!\" % len(items))\n\n```\n至此,我们的小爬虫就算完成了,虽然很简单,但也是一个好的开始,如果你有兴趣可以吧所有内容转换成PDF保存,我尝试了第三方生成PDF的库`pdfkit`,转成PDF的效果并不是很好,代码其实很简单,如下:\n\n```\ndef save_pdf(url, file_name):\n try:\n pdfkit.from_url(url, file_name.replace('/','_') + '.pdf')\n print(file_name + '保存完成')\n except:\n print(file_name + '写入失败')\n```\n## 最后\n其实,这里写入文件的操作用多线程效率会更加的高一些,留着下次尝试吧,本篇结束😝。\n\n","slug":"2017-03-22-Python爬虫实践","published":1,"updated":"2017-03-22T15:32:00.000Z","photos":[],"link":"","_id":"cj0l4nlys000072r9fnu27z9p","content":"<blockquote>\n<p>看了<a href=\"http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000\" target=\"_blank\" rel=\"external\">廖雪峰老师的Python教程</a>觉得非常的棒,浅显易懂,知识丰富,很适合初学者入门。看了一段时间,决定写点小东西练习一下,于是,就打算使用Python抓取一下廖雪峰老师的Python教程😏。</p>\n</blockquote>\n<a id=\"more\"></a>\n<h2 id=\"前言\"><a href=\"#前言\" class=\"headerlink\" title=\"前言\"></a>前言</h2><p>打开廖雪峰老师的Python3教程,由于是个人博客,内容也十分简洁,而我们需要抓取的内容也很容易找到。工欲善其事必先利其器,先安装好Python3和PyCharm开发工具,这里就不在赘述了。</p>\n<h2 id=\"分析\"><a href=\"#分析\" class=\"headerlink\" title=\"分析\"></a>分析</h2><p>我们先打开这篇教程,就是这个:</p>\n<p><img src=\"http://om6homgqk.bkt.clouddn.com/教程首页.png\" alt=\"教程首页\"></p>\n<p>在抓取前我们先看一下网页的源码,找到我们需要抓取的标签。如图:</p>\n<p><img src=\"http://om6homgqk.bkt.clouddn.com/网页源码.png\" alt=\"网页源码\"></p>\n<p>不难发现,上图的<code><ul></code>标签就是我们需要抓取的目标,也就是网页左侧的目录,我们需要的文章链接和标题都在这里。<br>OK!现在万事具备了,大致可以指定以下流程了:</p>\n<figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div></pre></td><td class=\"code\"><pre><div class=\"line\">1. 获取整个html的内容;</div><div class=\"line\">2. 从html中匹配出我们所需的文章链接及标题;</div><div class=\"line\">3. 下载整个html或者是保存为PDF</div></pre></td></tr></table></figure>\n<p>大致就是这个样子吧,至于步骤三如果下载html的话还需要下载整个页面的css文件,这里先只下载html吧。</p>\n<h2 id=\"开始\"><a href=\"#开始\" class=\"headerlink\" title=\"开始\"></a>开始</h2><p>为了完成步骤1,我们先编写一个根据url地址,获取网页内容的函数:</p>\n<figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div></pre></td><td class=\"code\"><pre><div class=\"line\">def url_open(url):</div><div class=\"line\"> url = re.sub(r'^//*', 'http://', url)</div><div class=\"line\"> html = urllib.request.urlopen(url)</div><div class=\"line\"> return html.read()</div></pre></td></tr></table></figure>\n<p><code>re</code>是Python内置的处理正则的模块,上面的代码把以<code>//</code>开头的链接替换为<code>http://</code>开头的完整url,并读取整个html的内容。<br>之后我们就可以在整个页面的内容中寻找我们所需要的内容了,这并没有什么难度,关键是如何利用好正则。</p>\n<figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div><div class=\"line\">13</div><div class=\"line\">14</div><div class=\"line\">15</div><div class=\"line\">16</div><div class=\"line\">17</div><div class=\"line\">18</div><div class=\"line\">19</div><div class=\"line\">20</div><div class=\"line\">21</div><div class=\"line\">22</div><div class=\"line\">23</div><div class=\"line\">24</div><div class=\"line\">25</div><div class=\"line\">26</div><div class=\"line\">27</div><div class=\"line\">28</div></pre></td><td class=\"code\"><pre><div class=\"line\"># 获取文章标题和链接</div><div class=\"line\">def find_itemlist(url):</div><div class=\"line\"> html = url_open(url).decode('utf-8')</div><div class=\"line\"> soup = BeautifulSoup(html)</div><div class=\"line\"> # 获取<ul>标签内容</div><div class=\"line\"> ul = soup.find_all('ul', class_='uk-nav uk-nav-side', style="margin-right:-15px;")</div><div class=\"line\"> print(ul)</div><div class=\"line\"> if len(ul):</div><div class=\"line\"> ulstr = str(ul[0])</div><div class=\"line\"> # 获取<a>标签内容</div><div class=\"line\"> pattern = r'<a.*>.*</a>'</div><div class=\"line\"> li = re.findall(pattern, ulstr)</div><div class=\"line\"> items = []</div><div class=\"line\"> for a in li:</div><div class=\"line\"> # 获取href标签内容</div><div class=\"line\"> hrefs = re.findall(r'href=".*"', a)</div><div class=\"line\"> if len(hrefs):</div><div class=\"line\"> href = hrefs[0]</div><div class=\"line\"> href = href[6:-1]</div><div class=\"line\"> print(href)</div><div class=\"line\"> # 获取文章标题</div><div class=\"line\"> titles = re.findall(r'>.*</a>', a)</div><div class=\"line\"> if len(titles):</div><div class=\"line\"> title = titles[0]</div><div class=\"line\"> title = title[1:-4]</div><div class=\"line\"> print(title)</div><div class=\"line\"> items.append({'title':title, 'href':href})</div><div class=\"line\"> return items</div></pre></td></tr></table></figure>\n<p>原谅我渣渣的正则水平,我先使用Python的BeautifulSoup模块获取了<code><ul>...</ul></code>标签内容,然后又从中获取到了<code><a></code>标签内容,最后从<code><a></code>标签中获取<code>href</code>标签内容和文章的标题。现在我们有了一个装有文章标题和链接的数组,接下来想干嘛就可以干嘛了😏。</p>\n<figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div><div class=\"line\">13</div><div class=\"line\">14</div><div class=\"line\">15</div><div class=\"line\">16</div><div class=\"line\">17</div><div class=\"line\">18</div><div class=\"line\">19</div><div class=\"line\">20</div><div class=\"line\">21</div><div class=\"line\">22</div><div class=\"line\">23</div><div class=\"line\">24</div><div class=\"line\">25</div><div class=\"line\">26</div><div class=\"line\">27</div></pre></td><td class=\"code\"><pre><div class=\"line\"># 保存html文件</div><div class=\"line\">def save_html(url, file_name):</div><div class=\"line\"> html = url_open(url)</div><div class=\"line\"> # 注意文件名称不能带有斜杠,需要用其他字符串代替。</div><div class=\"line\"> with open(file_name.replace('/','_') + '.html', 'wb') as f:</div><div class=\"line\"> try:</div><div class=\"line\"> f.write(html)</div><div class=\"line\"> print(file_name + '保存完成')</div><div class=\"line\"> except:</div><div class=\"line\"> print(file_name + '写入失败')</div><div class=\"line\"> </div><div class=\"line\"># 遍历数组,开始写入文件 </div><div class=\"line\">def download(items):</div><div class=\"line\"> # 创建根文件夹</div><div class=\"line\"> root = 'XXX'</div><div class=\"line\"> if os.path.exists(root):</div><div class=\"line\"> os.remove(root)</div><div class=\"line\"> os.mkdir(root)</div><div class=\"line\"> os.chdir(root)</div><div class=\"line\"> basurl = 'http://www.liaoxuefeng.com'</div><div class=\"line\"> for item in items:</div><div class=\"line\"> url = item['href']</div><div class=\"line\"> url = basurl + url</div><div class=\"line\"> file_name = item['title']</div><div class=\"line\"> save_html(url, file_name,)</div><div class=\"line\"> os.close()</div><div class=\"line\"> print("全部文章共%s篇,保存完成!" % len(items))</div></pre></td></tr></table></figure>\n<p>至此,我们的小爬虫就算完成了,虽然很简单,但也是一个好的开始,如果你有兴趣可以吧所有内容转换成PDF保存,我尝试了第三方生成PDF的库<code>pdfkit</code>,转成PDF的效果并不是很好,代码其实很简单,如下:</p>\n<figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div></pre></td><td class=\"code\"><pre><div class=\"line\">def save_pdf(url, file_name):</div><div class=\"line\"> try:</div><div class=\"line\"> pdfkit.from_url(url, file_name.replace('/','_') + '.pdf')</div><div class=\"line\"> print(file_name + '保存完成')</div><div class=\"line\"> except:</div><div class=\"line\"> print(file_name + '写入失败')</div></pre></td></tr></table></figure>\n<h2 id=\"最后\"><a href=\"#最后\" class=\"headerlink\" title=\"最后\"></a>最后</h2><p>其实,这里写入文件的操作用多线程效率会更加的高一些,留着下次尝试吧,本篇结束😝。</p>\n","excerpt":"<blockquote>\n<p>看了<a href=\"http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000\">廖雪峰老师的Python教程</a>觉得非常的棒,浅显易懂,知识丰富,很适合初学者入门。看了一段时间,决定写点小东西练习一下,于是,就打算使用Python抓取一下廖雪峰老师的Python教程😏。</p>\n</blockquote>","more":"<h2 id=\"前言\"><a href=\"#前言\" class=\"headerlink\" title=\"前言\"></a>前言</h2><p>打开廖雪峰老师的Python3教程,由于是个人博客,内容也十分简洁,而我们需要抓取的内容也很容易找到。工欲善其事必先利其器,先安装好Python3和PyCharm开发工具,这里就不在赘述了。</p>\n<h2 id=\"分析\"><a href=\"#分析\" class=\"headerlink\" title=\"分析\"></a>分析</h2><p>我们先打开这篇教程,就是这个:</p>\n<p><img src=\"http://om6homgqk.bkt.clouddn.com/教程首页.png\" alt=\"教程首页\"></p>\n<p>在抓取前我们先看一下网页的源码,找到我们需要抓取的标签。如图:</p>\n<p><img src=\"http://om6homgqk.bkt.clouddn.com/网页源码.png\" alt=\"网页源码\"></p>\n<p>不难发现,上图的<code><ul></code>标签就是我们需要抓取的目标,也就是网页左侧的目录,我们需要的文章链接和标题都在这里。<br>OK!现在万事具备了,大致可以指定以下流程了:</p>\n<figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div></pre></td><td class=\"code\"><pre><div class=\"line\">1. 获取整个html的内容;</div><div class=\"line\">2. 从html中匹配出我们所需的文章链接及标题;</div><div class=\"line\">3. 下载整个html或者是保存为PDF</div></pre></td></tr></table></figure>\n<p>大致就是这个样子吧,至于步骤三如果下载html的话还需要下载整个页面的css文件,这里先只下载html吧。</p>\n<h2 id=\"开始\"><a href=\"#开始\" class=\"headerlink\" title=\"开始\"></a>开始</h2><p>为了完成步骤1,我们先编写一个根据url地址,获取网页内容的函数:</p>\n<figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div></pre></td><td class=\"code\"><pre><div class=\"line\">def url_open(url):</div><div class=\"line\"> url = re.sub(r'^//*', 'http://', url)</div><div class=\"line\"> html = urllib.request.urlopen(url)</div><div class=\"line\"> return html.read()</div></pre></td></tr></table></figure>\n<p><code>re</code>是Python内置的处理正则的模块,上面的代码把以<code>//</code>开头的链接替换为<code>http://</code>开头的完整url,并读取整个html的内容。<br>之后我们就可以在整个页面的内容中寻找我们所需要的内容了,这并没有什么难度,关键是如何利用好正则。</p>\n<figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div><div class=\"line\">13</div><div class=\"line\">14</div><div class=\"line\">15</div><div class=\"line\">16</div><div class=\"line\">17</div><div class=\"line\">18</div><div class=\"line\">19</div><div class=\"line\">20</div><div class=\"line\">21</div><div class=\"line\">22</div><div class=\"line\">23</div><div class=\"line\">24</div><div class=\"line\">25</div><div class=\"line\">26</div><div class=\"line\">27</div><div class=\"line\">28</div></pre></td><td class=\"code\"><pre><div class=\"line\"># 获取文章标题和链接</div><div class=\"line\">def find_itemlist(url):</div><div class=\"line\"> html = url_open(url).decode('utf-8')</div><div class=\"line\"> soup = BeautifulSoup(html)</div><div class=\"line\"> # 获取<ul>标签内容</div><div class=\"line\"> ul = soup.find_all('ul', class_='uk-nav uk-nav-side', style="margin-right:-15px;")</div><div class=\"line\"> print(ul)</div><div class=\"line\"> if len(ul):</div><div class=\"line\"> ulstr = str(ul[0])</div><div class=\"line\"> # 获取<a>标签内容</div><div class=\"line\"> pattern = r'<a.*>.*</a>'</div><div class=\"line\"> li = re.findall(pattern, ulstr)</div><div class=\"line\"> items = []</div><div class=\"line\"> for a in li:</div><div class=\"line\"> # 获取href标签内容</div><div class=\"line\"> hrefs = re.findall(r'href=".*"', a)</div><div class=\"line\"> if len(hrefs):</div><div class=\"line\"> href = hrefs[0]</div><div class=\"line\"> href = href[6:-1]</div><div class=\"line\"> print(href)</div><div class=\"line\"> # 获取文章标题</div><div class=\"line\"> titles = re.findall(r'>.*</a>', a)</div><div class=\"line\"> if len(titles):</div><div class=\"line\"> title = titles[0]</div><div class=\"line\"> title = title[1:-4]</div><div class=\"line\"> print(title)</div><div class=\"line\"> items.append({'title':title, 'href':href})</div><div class=\"line\"> return items</div></pre></td></tr></table></figure>\n<p>原谅我渣渣的正则水平,我先使用Python的BeautifulSoup模块获取了<code><ul>...</ul></code>标签内容,然后又从中获取到了<code><a></code>标签内容,最后从<code><a></code>标签中获取<code>href</code>标签内容和文章的标题。现在我们有了一个装有文章标题和链接的数组,接下来想干嘛就可以干嘛了😏。</p>\n<figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div><div class=\"line\">7</div><div class=\"line\">8</div><div class=\"line\">9</div><div class=\"line\">10</div><div class=\"line\">11</div><div class=\"line\">12</div><div class=\"line\">13</div><div class=\"line\">14</div><div class=\"line\">15</div><div class=\"line\">16</div><div class=\"line\">17</div><div class=\"line\">18</div><div class=\"line\">19</div><div class=\"line\">20</div><div class=\"line\">21</div><div class=\"line\">22</div><div class=\"line\">23</div><div class=\"line\">24</div><div class=\"line\">25</div><div class=\"line\">26</div><div class=\"line\">27</div></pre></td><td class=\"code\"><pre><div class=\"line\"># 保存html文件</div><div class=\"line\">def save_html(url, file_name):</div><div class=\"line\"> html = url_open(url)</div><div class=\"line\"> # 注意文件名称不能带有斜杠,需要用其他字符串代替。</div><div class=\"line\"> with open(file_name.replace('/','_') + '.html', 'wb') as f:</div><div class=\"line\"> try:</div><div class=\"line\"> f.write(html)</div><div class=\"line\"> print(file_name + '保存完成')</div><div class=\"line\"> except:</div><div class=\"line\"> print(file_name + '写入失败')</div><div class=\"line\"> </div><div class=\"line\"># 遍历数组,开始写入文件 </div><div class=\"line\">def download(items):</div><div class=\"line\"> # 创建根文件夹</div><div class=\"line\"> root = 'XXX'</div><div class=\"line\"> if os.path.exists(root):</div><div class=\"line\"> os.remove(root)</div><div class=\"line\"> os.mkdir(root)</div><div class=\"line\"> os.chdir(root)</div><div class=\"line\"> basurl = 'http://www.liaoxuefeng.com'</div><div class=\"line\"> for item in items:</div><div class=\"line\"> url = item['href']</div><div class=\"line\"> url = basurl + url</div><div class=\"line\"> file_name = item['title']</div><div class=\"line\"> save_html(url, file_name,)</div><div class=\"line\"> os.close()</div><div class=\"line\"> print("全部文章共%s篇,保存完成!" % len(items))</div></pre></td></tr></table></figure>\n<p>至此,我们的小爬虫就算完成了,虽然很简单,但也是一个好的开始,如果你有兴趣可以吧所有内容转换成PDF保存,我尝试了第三方生成PDF的库<code>pdfkit</code>,转成PDF的效果并不是很好,代码其实很简单,如下:</p>\n<figure class=\"highlight plain\"><table><tr><td class=\"gutter\"><pre><div class=\"line\">1</div><div class=\"line\">2</div><div class=\"line\">3</div><div class=\"line\">4</div><div class=\"line\">5</div><div class=\"line\">6</div></pre></td><td class=\"code\"><pre><div class=\"line\">def save_pdf(url, file_name):</div><div class=\"line\"> try:</div><div class=\"line\"> pdfkit.from_url(url, file_name.replace('/','_') + '.pdf')</div><div class=\"line\"> print(file_name + '保存完成')</div><div class=\"line\"> except:</div><div class=\"line\"> print(file_name + '写入失败')</div></pre></td></tr></table></figure>\n<h2 id=\"最后\"><a href=\"#最后\" class=\"headerlink\" title=\"最后\"></a>最后</h2><p>其实,这里写入文件的操作用多线程效率会更加的高一些,留着下次尝试吧,本篇结束😝。</p>"}],"PostAsset":[],"PostCategory":[{"post_id":"cj0l1ptad00060er9clkr9rbk","category_id":"cj0l1pta800030er904gg70hz","_id":"cj0l1ptap000c0er9qu42ai5p"},{"post_id":"cj0l1pt9y00010er95l7simo0","category_id":"cj0l1pta800030er904gg70hz","_id":"cj0l1ptat000g0er9qf2q4gnb"},{"post_id":"cj0l1ptag00070er92x287u8k","category_id":"cj0l1pta800030er904gg70hz","_id":"cj0l1ptax000j0er9ska1m4vk"},{"post_id":"cj0l1pta300020er9d75o18cw","category_id":"cj0l1pta800030er904gg70hz","_id":"cj0l1ptb0000o0er9ott72fdf"},{"post_id":"cj0l1ptaq000d0er9i23sim55","category_id":"cj0l1pta800030er904gg70hz","_id":"cj0l1ptb3000r0er9ovf74gki"},{"post_id":"cj0l1ptau000h0er988xdu1g0","category_id":"cj0l1pta800030er904gg70hz","_id":"cj0l1ptb8000w0er9gweirowe"},{"post_id":"cj0l1ptac00050er9iih2lbw9","category_id":"cj0l1pta800030er904gg70hz","_id":"cj0l1ptbd000z0er9ovrwlmpp"},{"post_id":"cj0l1ptb1000p0er9bhskkf18","category_id":"cj0l1pta800030er904gg70hz","_id":"cj0l1ptbf00120er9w6h9zq4d"},{"post_id":"cj0l1ptak000b0er9n8jlc6y3","category_id":"cj0l1ptaz000l0er9tysqqva3","_id":"cj0l1ptbg00140er94d8r8eez"},{"post_id":"cj0l1ptb3000s0er9g8s2e4o3","category_id":"cj0l1ptaz000l0er9tysqqva3","_id":"cj0l1ptbh00160er91k3k4erb"},{"post_id":"cj0l1ptb9000x0er98j0iiczd","category_id":"cj0l1pta800030er904gg70hz","_id":"cj0l1ptbk00180er9tsm86kip"},{"post_id":"cj0l1ptax000k0er90j4wkuer","category_id":"cj0l1ptb6000u0er92o8x0h45","_id":"cj0l1ptbk00190er9m0flbegs"},{"post_id":"cj0l4nlys000072r9fnu27z9p","category_id":"cj0l4nlzc000172r99wvlz96d","_id":"cj0l4nlzl000472r9sh3cqqi7"}],"PostTag":[{"post_id":"cj0l1pt9y00010er95l7simo0","tag_id":"cj0l1ptab00040er90uqprx3r","_id":"cj0l1ptaj000a0er98l10dbcd"},{"post_id":"cj0l1pta300020er9d75o18cw","tag_id":"cj0l1ptah00090er9nmfxl7od","_id":"cj0l1ptaw000i0er9ou6mxbhx"},{"post_id":"cj0l1ptaq000d0er9i23sim55","tag_id":"cj0l1ptah00090er9nmfxl7od","_id":"cj0l1ptaz000m0er9wq66ejrn"},{"post_id":"cj0l1ptau000h0er988xdu1g0","tag_id":"cj0l1ptah00090er9nmfxl7od","_id":"cj0l1ptb2000q0er9az0tftcd"},{"post_id":"cj0l1ptac00050er9iih2lbw9","tag_id":"cj0l1ptah00090er9nmfxl7od","_id":"cj0l1ptb5000t0er98a98zh6p"},{"post_id":"cj0l1ptb1000p0er9bhskkf18","tag_id":"cj0l1ptah00090er9nmfxl7od","_id":"cj0l1ptbd000y0er9q70ik8l4"},{"post_id":"cj0l1ptad00060er9clkr9rbk","tag_id":"cj0l1ptah00090er9nmfxl7od","_id":"cj0l1ptbe00100er9qi0nb5rw"},{"post_id":"cj0l1ptag00070er92x287u8k","tag_id":"cj0l1ptah00090er9nmfxl7od","_id":"cj0l1ptbf00130er95znyvzvu"},{"post_id":"cj0l1ptak000b0er9n8jlc6y3","tag_id":"cj0l1ptbf00110er9xeyabdxu","_id":"cj0l1ptbj00170er9f101oow6"},{"post_id":"cj0l1ptax000k0er90j4wkuer","tag_id":"cj0l1ptbg00150er9nwcfg9cv","_id":"cj0l1ptbl001b0er946kpe5wj"},{"post_id":"cj0l1ptb3000s0er9g8s2e4o3","tag_id":"cj0l1ptbf00110er9xeyabdxu","_id":"cj0l1ptbm001d0er9hnmbn1zy"},{"post_id":"cj0l1ptb9000x0er98j0iiczd","tag_id":"cj0l1ptbl001c0er9zg0iafo1","_id":"cj0l1ptbm001e0er9kze53rz7"},{"post_id":"cj0l4nlys000072r9fnu27z9p","tag_id":"cj0l4nlzi000272r9tk7midyx","_id":"cj0l4nlzk000372r9rzelrl0l"}],"Tag":[{"name":"iOS工具","_id":"cj0l1ptab00040er90uqprx3r"},{"name":"iOS","_id":"cj0l1ptah00090er9nmfxl7od"},{"name":"Mac工具","_id":"cj0l1ptbf00110er9xeyabdxu"},{"name":"随笔","_id":"cj0l1ptbg00150er9nwcfg9cv"},{"name":"读书笔记","_id":"cj0l1ptbl001c0er9zg0iafo1"},{"name":"Python","_id":"cj0l4nlzi000272r9tk7midyx"}]}}