├── .gitignore ├── LICENSE └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | # Xcode 2 | # 3 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore 4 | 5 | ## Build generated 6 | build/ 7 | DerivedData/ 8 | 9 | ## Various settings 10 | *.pbxuser 11 | !default.pbxuser 12 | *.mode1v3 13 | !default.mode1v3 14 | *.mode2v3 15 | !default.mode2v3 16 | *.perspectivev3 17 | !default.perspectivev3 18 | xcuserdata/ 19 | 20 | ## Other 21 | *.moved-aside 22 | *.xccheckout 23 | *.xcscmblueprint 24 | 25 | ## Obj-C/Swift specific 26 | *.hmap 27 | *.ipa 28 | *.dSYM.zip 29 | *.dSYM 30 | 31 | # CocoaPods 32 | # 33 | # We recommend against adding the Pods directory to your .gitignore. However 34 | # you should judge for yourself, the pros and cons are mentioned at: 35 | # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control 36 | # 37 | # Pods/ 38 | 39 | # Carthage 40 | # 41 | # Add this line if you want to avoid checking in source code from Carthage dependencies. 42 | # Carthage/Checkouts 43 | 44 | Carthage/Build 45 | 46 | # fastlane 47 | # 48 | # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the 49 | # screenshots whenever they are needed. 50 | # For more information about the recommended setup visit: 51 | # https://docs.fastlane.tools/best-practices/source-control/#source-control 52 | 53 | fastlane/report.xml 54 | fastlane/Preview.html 55 | fastlane/screenshots 56 | fastlane/test_output 57 | 58 | # Code Injection 59 | # 60 | # After new code Injection tools there's a generated folder /iOSInjectionProject 61 | # https://github.com/johnno1962/injectionforxcode 62 | 63 | iOSInjectionProject/ 64 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # Interview-Question & Answer 3 | 4 | 5 | 6 | ### 初级篇完结 7 | 起初乍一看感觉问题并不是很多,通过总结才发现面试官的准备十分充分,涵盖了很多方面,在总结的过程中,我也等于是复习了一遍。 8 | 9 | 目前针对初级篇的问题大致总结了一下,我看了中级以及高级的题目,**大致分为以下几类**: 10 | 11 | * **Runtime** [参考文章即可](http://yulingtianxia.com/blog/2014/11/05/objective-c-runtime/) 12 | * **RunLoop** [参考文章即可](https://blog.ibireme.com/2015/05/18/runloop/) 13 | * **Block** [参考文章即可](https://www.jianshu.com/p/14efa33b3562) 14 | * **KVC & KVO** [我的另一篇文章](https://github.com/liberalisman/KVC-KVO) 15 | * **三方框架的源代码解析(AFN、SDWebImage...)** 16 | * **数据结构** 17 | 18 | **再加上是基础题目里也有很多值得拓展的问题** 19 | 20 | * **内存管理** 21 | * **数据持久化** 22 | * **多线程** 23 | * **属性修饰符** 24 | * **内存语义。。。。** 25 | 26 | 27 | 关于中高级的问题,我会接下来做仔细的分析,我心里并没有十足的把握,或许上面的回答也是漏洞百出,但是希望各位同行能多多指教,指出我的不足,在此先行谢过。 28 | 29 | 在整理这篇答案的时候,借鉴了很多网上的资料,很杂,也很难一一列出。 30 | 31 | 32 | 喵神的关于`storyBoard`那篇 33 | 34 | 链接在此:[再看关于 Storyboard 的一些争论](https://onevcat.com/2017/04/storyboard-argue/) 35 | 36 | ----------------------- 37 | 此篇是根据知名博主 [J-Knight](http://weibo.com/u/1929625262?from=feed&loc=nickname) 所提供的面试题目,所整理的答案,感谢 [J-Knight](http://weibo.com/u/1929625262?from=feed&loc=nickname) 的分享,[点击查看原文。](https://juejin.im/post/5938dfdb8d6d810058481572?utm_source=weibo&utm_campaign=user。) 38 | 39 | 另外,我写此文的目的在于和广大的`iOS`开发者进行沟通交流,里面的内容有自己的理解,也有很大一部分参照网上的解释。很感谢之前的分享者,文末会附上相关的链接。如果在本文有理解不正确的地方,也希望大家多多指正。 40 | 41 | 面试题分为三个部分,我们先从基础开始。 42 | 43 | 44 | 45 | ## 基础 46 | ### 1. 为什么说Objective-C是一门动态的语言? 47 | 其实`Objective-C`是一门动态语言的用`运行时Runtime`可以更好地说明,但我看后面还有关于`运行时`的问题,在此处就先不展开了。 48 | 49 | 1. 动态类型:例如“id”类型,动态类型属于弱类型,在运行时才决定消息的接收者 50 | 2. 动态绑定:程序在运行时需要调用什么代码是在运行时决定的,而不是在编译时。 51 | 3. 动态载入:程序在运行时的代码模块以及相关资源是在运行时添加的,而不是启动时就加载所有资源 52 | 53 | 54 | ### 2.简要概括一下 **MVC** 和 **MVVM**,**MVP**三种模式。 55 | 56 | ##### MVC 57 | ![](http://image.beekka.com/blog/2015/bg2015020105.png) 58 | 59 | **`MVC`模式所有的模块通信都是单向的**(这一点个人持怀疑态度,希望大家提出意见) 60 | 61 | 1. `View`传递指令给`Controller` 62 | 2. `Controller` 完成业务逻辑后,要求 `Model` 改变状态 63 | 3. `Model` 将新的数据发送到 `View`,用户得到反馈 64 | 65 | **还有一种是`Controller`直接接受指令** 66 | 67 | ![](http://image.beekka.com/blog/2015/bg2015020107.png) 68 | 69 | ##### MVP 70 | **`MVP` 模式将 `Controller` 改名为 `Presenter`,同时改变了通信方向。** 71 | 72 | ![](http://image.beekka.com/blog/2015/bg2015020109.png) 73 | 74 | 1. 各部分之间的通信,都是双向的。 75 | 2. `View` 与 `Model` 不发生联系,都通过 `Presenter` 传递。 76 | 3. `View` 非常薄,不部署任何业务逻辑,称为"被动视图"(Passive View),即没有任何主动性,而 `Presenter`非常厚,所有逻辑都部署在那里。 77 | 78 | ##### MVVM 79 | `MVVM` 模式将 `Presenter` 改名为 `ViewModel`,基本上与 `MVP` 模式完全一致。 80 | ![](http://image.beekka.com/blog/2015/bg2015020110.png) 81 | 82 | 唯一的区别是,它采用`双向绑定(data-binding)`:`View`的变动,自动反映在 `ViewModel`,反之亦然。`Angular` 和 `Ember` 都采用这种模式。 83 | 84 | 85 | ### 3.为什么代理要用weak?代理的delegate和dataSource有什么区别?block和代理的区别? 86 | 87 | ##### 1.首先,为什么代理要用weak? 88 | 89 | **其实就是循环引用!!!** 90 | 我们一般在声明一个协议的时候,会定义一个代理属性,如果代理用的比较溜就会知道,一般都是别的类成为当前协议的代理,也就是说,代理实际是外部的一个类。代理属性的销毁不由当前协议类控制,而是由外部代理者自己控制。 91 | 如果在定义代理属性时,使用`Strong`,外界就无法销毁代理属性,造成循环引用,无法释放。 92 | 93 | ##### 2.代理的delegate和dataSource有什么区别。 94 | `delegate` 和 `dataSource` 常见于`UITableView`和`UICollectionView`。 95 | `dataSource`是数据源,决定了显示多少个`区域`,每个区域显示多少`行`,每行现实的`具体内容`,`头部,尾部`视图等。 96 | `delegate`是交互行为的代理,比如`点击`,`取消选中`,`是否高亮`等等。 97 | 98 | 关于这个问题我有一些疑惑,比如`delegate`里面也有决定头部视图显示什么,尾部视图显示什么的方法,按我的理解应该在`DataSource`才对,请大家指教。 99 | 100 | ##### 3.block和代理的区别? 101 | 102 | `Block`是带有局部变量的匿名函数,是一个代码段,`Block`更面向结果,他适合与状态无关的操作,例如直接返回某些值得时候,就比较适合用`Block`。 103 | 104 | `delegate`回调则更加面向过程,例如执行的回调需要几个不同的步骤,这个时候使用`delegate`则更为合适 105 | 106 | 107 | ### 4.属性的实质是什么?包括哪几个部分?属性默认的关键字都有哪些?@dynamic关键字和@synthesize关键字是用来做什么的? 108 | 109 | 想深入了解,可以看一下详细的总结 : https://github.com/liberalisman/2018-Interview-Preparation#04-property 110 | 111 | ##### 1.实质就是 ivar(实例变量)、存取方法(access method = getter + setter)。 112 | 113 | @property 的本质. 114 | 115 | ```objc 116 | @property = ivar + getter + setter; 117 | ``` 118 | 119 | ##### 2.属性可以拥有的特质分为四类: 120 | 121 | * **原子性--- nonatomic** 特质,在默认情况下,由编译器合成的方法会通过锁定机制确保其原子性`(atomicity)`。如果属性具备 `nonatomic` 特质,则不使用`自旋锁`。请注意,尽管没有名为`atomic`的特质(如果某属性不具备 `nonatomic` 特质,那它就是“原子的” ( `atomic`) ),但是仍然可以在属性特质中写明这一点,编译器不会报错。若是自己定义存取方法,那么就应该遵从与属性特质相符的原子性。 122 | 123 | * **读/写权限**---readwrite(读写)、readonly (只读) 124 | 125 | * **内存管理语义**---assign、strong、 weak、unsafe_unretained、copy 126 | * **方法名** - getter= 、setter= 127 | 128 | 129 | ##### 3.属性的默认关键字: 130 | 在 ARC 下,如果如果修饰的是 **Objective-C** 对象。 131 | 132 | ```objc 133 | @property (atomic,strong,readwrite) UIView *view; 134 | ``` 135 | 如果如果修饰的是基本数据类型。 136 | 137 | ```objc 138 | @property (atomic,assign,readwrite) int num; 139 | ``` 140 | 141 | 142 | 143 | ##### 4.“自动合成”( autosynthesis) 144 | 145 | >完成属性定义后,编译器会自动编写访问这些属性所需的方法,此过程叫做**“自动合成”(autosynthesis)**。需要强调的是,这个过程由编译 器在编译期执行,所以编辑器里看不到这些“合成方法”(synthesized method)的源代码。除了生成方法代码** getter、setter** 之外,编译器还要自动向类中添加适当类型的实例变量,并且在属性名前面加下划线,以此作为实例变量的名字。 146 | >也可以在类的实现代码里通过**@synthesize** 语法来指定实例变量的名字. 147 | 148 | 149 | ##### 5.@dynamic 150 | > 告诉编译器,属性的setter与getter方法由用户自己实现,不自动生成。 151 | 152 | 如果`@synthesize`和`@dynamic`都没写,那么默认的就是 153 | 154 | ```objc 155 | @syntheszie var = _var; 156 | 157 | // @synthesize的语义是如果你没有手动实现setter方法和getter方法,那么编译器会自动为你加上这两个方法。 158 | // @dynamic告诉编译器,属性的setter与getter方法由用户自己实现,不自动生成。 159 | ``` 160 | 161 | 162 | 163 | ##### 6.为了搞清属性是怎么实现的,反编译相关的代码,大致生成了五个东西 164 | 165 | ```objc 166 | 1. OBJC_IVAR_$类名$属性名称 :该属性的“偏移量” (offset),这个偏移量是“硬编码” (hardcode),表示该变量距离存放对象的内存区域的起始地址有多远。 167 | 2. setter 与 getter 方法对应的实现函数 168 | 3. ivar_list :成员变量列表 169 | 4. method_list :方法列表 170 | 5. prop_list :属性列表 171 | 也就是说我们每次在增加一个属性,系统都会在 ivar_list 中添加一个成员变量的描述, 172 | 在 method_list 中增加 setter 与 getter 方法的描述, 173 | 在属性列表中增加一个属性的描述, 174 | 然后计算该属性在对象中的偏移量, 175 | 然后给出 setter 与 getter 方法对应的实现, 176 | 在 setter 方法中从偏移量的位置开始赋值, 177 | 在 getter 方法中从偏移量开始取值, 178 | 为了能够读取正确字节数, 179 | 系统对象偏移量的指针类型进行了类型强转. 180 | ``` 181 | 182 | 183 | ### 5.NSString为什么要用copy关键字,如果用strong会有什么问题? 184 | 185 | `NSString`有可变的子类`NSMutableString`。因为父类指针可以指向子类,避免`NSMutableString`给`NSString`赋值,造成原有的值被无形修改,所以用`Copy`修饰。 186 | 187 | 我们修饰 `NSString` 使用 `Copy` 关键字。 188 | 189 | * 如果传进来的也是 `NSString`类型,这时候`Copy`作为指针拷贝,是浅拷贝,内容不会发生变化。 190 | 191 | * 如果传进来的是 `NSMutableString`类型,这时候`Copy`作为内容拷贝,是深拷贝,在内存中新开辟出一块儿新的地址,防止原有的值被改变。 192 | 193 | -------- 194 | 以上是我之前的回答,热心网友对此问题作了完善的补充 195 | 196 | > NSString 使用 copy 和它的子类并没有关系,而且凡是 NSObject 都有 copy 方法,并不是 NSString 独有。 197 | 198 | 如下代码: 199 | 200 | ```objc 201 | NSString *string = @"测试数据"; 202 | NSString *copyString = [string copy]; 203 | NSMutableString *mutableCopyString = [string mutableCopy]; 204 | NSMutableString *copyMutableString = [string copy]; 205 | NSLog(@"%p,%p,%p,%p", string, copyString, mutableCopyString, copyMutableString); 206 | ``` 207 | 208 | 输出它们的地址,`string` 和 `copyString` 的地址是相同的,说明它们的指针指向同一个地址,也就是说 `copy` 是浅拷贝,即`指针拷贝`;`mutableCopyString` 和其他的地址都不一样,说明新开辟了一块内存空间,也就是和前两个没有任何关系,也就是说 `mutableCopy` 发生了`深拷贝`; 209 | 210 | `copyMutableString` 和其他的地址也不一样,同 `mutableCopyString` ,也是发生了`深拷贝`。 211 | 212 | 对于 `copyString` 和 `copyMutableString` 同是使用的 `copy`,但是地址却不一样,是因为苹果对于不可变的对象执行的引用操作,而对于可变对象,相对于之前的不可变对象,那么地址肯定会不一样,所以这个时候就要拷贝一份,和之前的就没有任何关系了。 213 | 214 | 还有就是属性中的 copy 关键字,如下代码: 215 | 216 | ```objc 217 | @property (nonatomic, copy) NSString *copyString; 218 | @property (nonatomic, strong) NSString *strongString; 219 | ``` 220 | 221 | 对于上面的代码,`copyString` 和 `strongString` 的 `set` 方法中, 222 | 223 | ```objc 224 | -(void)setCopyString:(NSString *)copyString { 225 | _copyString = [copyString copy]; // 调用 copy 方法,所以并不是直接赋值 226 | } 227 | -(void)setStrongString:(NSString *)strongString { 228 | _strongString = strongString; // 直接引用 229 | } 230 | ``` 231 | 232 | 如果想要外界赋值的值对 `string` 有影响,那么就用 `strong`,这样两者相当于还是一个对象,如果在赋值以后不想要外界再对 `string` 有影响,那么就用 `copy`。也就是说用 `strong` 还是 `copy` 可以根据情况而定。 233 | 234 | 235 | ### 6.如何令自己所写的对象具有拷贝功能? 236 | 237 | 简单说就是遵守`NSCopying`,`NSMutableCopying`协议 238 | 239 | 并且实现`(id)copyWithZone:(NSZone *)zone`和`(id)mutableCopyWithZone:(NSZone *)zone`两个方法即可。 240 | 241 | 深入了解可看我的[其他文章](https://github.com/liberalisman/2018-Interview-Preparation#02-shallowcopy-deepcopy)。 242 | 243 | 244 | ### 7.`可变集合类` 和 `不可变集合类`的 `copy` 和 `mutablecopy` 有什么区别?如果是集合是内容复制的话,集合里面的元素也是内容复制么? 245 | 246 | 247 | | 源对象类型 | 拷贝方式 | 副本对象类型 | 是否有新的对象 | 248 | | --- | --- | --- | --- | 249 | | NSArray | Copy | NSArray | NO | 250 | | NSMutableArray | Copy | NSArray | YES | 251 | | NSMutableArray | MutableCopy | NSMutableArray | YES | 252 | | NSArray | MutableCopy | NSMutableArray | YES | 253 | 254 | 255 | 如果是集合内容复制,它的内容复制也分两种,一种是`单层复制`,一种是`完全复制`。上表的后三种全都是`单层内容复制`,只有最外面的容器被复制了,里面存储对象的指针地址不变。 256 | 257 | ### 8.为什么IBOutlet修饰的UIView使用weak关键字? 258 | 关于`IBOutlet`修饰的属性究竟是使用`strong`还是`weak`,网上的不同意见还是挺多的。 259 | 260 | 但我认为这可以分为两种情况: 261 | 262 | 1.如果从`storyBoard`或者`nib`拖出来的`插座属性`是`storyBoard`或者`nib`所直接拥有的,这个时候应该使用`Strong`修饰 263 | 264 | 2.如果是一个`storyBoard`或者`nib`的`子控件`再添加`子控件`,这个时候就应该用`weak`。 265 | 266 | 这么说可能比较不好理解。 267 | ![](http://okhqmtd8q.bkt.clouddn.com/Interview-QA/1.png) 268 | 269 | 此图控制器的View拖出来的线就是`strong`。 270 | 而如果往`View`上再次添加子控件的话,拖出来的线就是`weak`。 271 | 272 | ### 9.nonatomic和atomic的区别?atomic是绝对的线程安全么?为什么?如果不是,那应该如何实现? 273 | 274 | ##### 1.nonatomic和atomic的区别? 275 | `atomic-原子性` 276 | 277 | * 默认的属性 278 | * 保证CPU在别的线程来访问这个属性之前,先执行完当前线程 279 | * 速度较慢,因为要保证整体完成。 280 | 281 | `nonatomic-非原子性` 282 | 283 | * 非默认的属性 284 | * 线程不安全,如果两个线程同时访问,会出问题 285 | * 速度快 286 | 287 | ##### 2.atomic是绝对的线程安全么?如果不是,那应该如何实现? 288 | 很遗憾,并不是。。虽然`atomic-原子性`能保证不同的线程同时访问一个属性的时候,它的`Setter`和`getter`方法会有序执行,但如果此时有另一个线程调用该属性的`Release`方法,还是会出问题的,因为`atomic-原子性`只能管好它的`Setter`和`getter`方法。 289 | 290 | 再者开锁是很耗性能的,所以在移动端,一般使用`nonatomic`,而`Mac OS`不涉及到性能瓶颈,所在在`Mac OS`上使用`atomic`。 291 | 292 | 至于在`iOS`上保证属性在不同线程间访问的绝对安全,这块儿我暂时没有研究过,希望知道的朋友指教。 293 | 294 | 295 | 296 | ### 10.UICollectionView自定义layout如何实现? 297 | 298 | 自定义`Layout`需要实现以下几个步骤。 299 | 300 | ```swift 301 | // 1.collectionView每次需要重新布局(初始, layout 被设置为invalidated ...)的时候会首先调用这个方法prepareLayout() 302 | func prepareLayout() 303 | 304 | // 2.然后会调用layoutAttributesForElementsInRect(rect: CGRect)方法获取到rect范围内的cell的所有布局, 这个rect大家可以打印出来看下, 和collectionView的bounds不一样, size可能比collectionView大一些, 这样设计也许是为了缓冲 305 | func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? 306 | 307 | // 3.当collectionView的bounds变化的时候会调用shouldInvalidateLayoutForBoundsChange(newBounds: CGRect)这个方法 308 | public func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool 309 | 310 | // 4.需要设置collectionView 的滚动范围 collectionViewContentSize() 311 | // 自定义的时候, 必须重写这个方法, 并且返回正确的滚动范围, collectionView才能正常的滚动 312 | public func collectionViewContentSize() -> CGSize 313 | 314 | // 5.以下方法, Apple建议我们也重写, 返回正确的自定义对象的布局,因为有时候当collectionView执行一些操作(delete insert reload)等系统会调用这些方法获取布局, 如果没有重写, 可能发生意想不到的效果 315 | // 自定义cell布局的时候重写 316 | public func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? 317 | // 自定义SupplementaryView的时候重写 318 | public func layoutAttributesForSupplementaryViewOfKind(elementKind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? 319 | // 自定义DecorationView的时候重写 320 | public func layoutAttributesForDecorationViewOfKind(elementKind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? 321 | 322 | // 6.这个方法是当collectionView将停止滚动的时候调用,得到最终偏移量。我们可以重写它来实现, collectionView停在指定的位置(比如照片浏览的时候, 你可以通过这个实现居中显示照片...) 323 | public func targetContentOffsetForProposedContentOffset(proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint 324 | ``` 325 | 326 | ### 11.用StoryBoard开发界面有什么弊端?如何避免? 327 | 328 | 其实关于用`StoryBoard`还是纯代码的开发方式,争吵声一直都存在,其实我个人并不反感`StoryBoard`,反而还挺喜欢。开发速度快,如果协调好,可以减轻很多工作量。不过关于`StoryBoard`这个话题如果展开的话还是比较大,建议大家读一下。喵神最近写的一篇文章,附上[原文链接](https://onevcat.com/2017/04/storyboard-argue/),有异议的话也欢迎大家积极讨论。 329 | 330 | ### 12.进程和线程的区别?同步异步的区别?并行和并发的区别? 331 | 332 | ##### 1.进程和线程的区别? 333 | > 进程:进程是指在系统中正在运行的一个应用程序。每个进程之间是独立的,每个进程均运行在其专用且受保护的内存空间内。 334 | > 335 | > 线程:线程是进程的基本执行单元,一个进程的所有任务都在线程中执行。1个进程要想执行任务,必须得有线程,例如默认就是主线程。 336 | 337 | ##### 2.同步异步的区别? 338 | > 同步函数:不具备开线程的能力,只能串行按顺序执行任务 339 | > 340 | > 异步函数:具备开线程的能力,但并不是只要是异步函数就会开线程。 341 | 342 | ##### 3.并行和并发的区别? 343 | >并行:并行即同时执行。比如同时开启3条线程分别执行三个不同人物,这些任务执行时同时进行的。 344 | > 345 | >并发:并发指在同一时间里,CPU只能处理1条线程,只有1条线程在工作(执行)。多线程并发(同时)执行,其实是CPU快速地在多条线程之间调度(切换),如果CPU调度线程的时间足够快,就造成了多线程并发执行的假象。 346 | 347 | ### 13.线程间通信? 348 | 349 | ##### 1.NSThread 350 | 351 | ```objc 352 | // 第一种方式。 353 | [self performSelectorOnMainThread:@selector(showImage:) withObject:image waitUntilDone:YES]; 354 | 355 | // 第二种方式 356 | [self.imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:YES]; 357 | ``` 358 | 359 | ##### 2.GCD 360 | 361 | ```objc 362 | //0.获取一个全局的队列 363 | dispatch_queue_t queue = dispatch_get_global_queue(0, 0); 364 | 365 | //1.先开启一个线程,把下载图片的操作放在子线程中处理 366 | dispatch_async(queue, ^{ 367 | //2.下载图片 368 | NSURL *url = [NSURL URLWithString:@"http://h.hiphotos.baidu.com/zhidao/pic/item/6a63f6246b600c3320b14bb3184c510fd8f9a185.jpg"]; 369 | NSData *data = [NSData dataWithContentsOfURL:url]; 370 | UIImage *image = [UIImage imageWithData:data]; 371 | NSLog(@"下载操作所在的线程--%@",[NSThread currentThread]); 372 | //3.回到主线程刷新UI 373 | dispatch_async(dispatch_get_main_queue(), ^{ 374 | self.imageView.image = image; 375 | //打印查看当前线程 376 | NSLog(@"刷新UI---%@",[NSThread currentThread]); 377 | }); 378 | }); 379 | 380 | // GCD通过嵌套就可以实现线程间的通信。 381 | ``` 382 | 383 | ##### 3.NSOperationQueue 384 | 385 | ```objc 386 | //1.创建队列 387 | NSOperationQueue *queue = [[NSOperationQueue alloc]init]; 388 | 389 | //2.使用简便方法封装操作并添加到队列中 390 | [queue addOperationWithBlock:^{ 391 | 392 | //3.在该block中下载图片 393 | NSURL *url = [NSURL URLWithString:@"http://news.51sheyuan.com/uploads/allimg/111001/133442IB-2.jpg"]; 394 | NSData *data = [NSData dataWithContentsOfURL:url]; 395 | UIImage *image = [UIImage imageWithData:data]; 396 | NSLog(@"下载图片操作--%@",[NSThread currentThread]); 397 | 398 | //4.回到主线程刷新UI 399 | [[NSOperationQueue mainQueue] addOperationWithBlock:^{ 400 | self.imageView.image = image; 401 | NSLog(@"刷新UI操作---%@",[NSThread currentThread]); 402 | }]; 403 | }]; 404 | ``` 405 | 406 | ### 14.GCD的一些常用的函数? 407 | 408 | ##### 1.栅栏函数(控制任务的执行顺序) 409 | 410 | ```objc 411 | dispatch_barrier_async(queue, ^{ 412 | 413 | NSLog(@"barrier"); 414 | }); 415 | ``` 416 | 417 | ##### 2.延迟执行(延迟·控制在哪个线程执行) 418 | 419 | ```objc 420 | dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 421 | NSLog(@"---%@",[NSThread currentThread]); 422 | }); 423 | ``` 424 | 425 | ##### 3.一次性代码 426 | 427 | ```objc 428 | static dispatch_once_t onceToken; 429 | dispatch_once(&onceToken, ^{ 430 | 431 | NSLog(@"-----"); 432 | }); 433 | ``` 434 | 435 | ##### 4.快速迭代(开多个线程并发完成迭代操作) 436 | 437 | ```objc 438 | dispatch_apply(subpaths.count, queue, ^(size_t index) { 439 | }); 440 | ``` 441 | 442 | 443 | ##### 5.队列组(同栅栏函数) 444 | 445 | ```objc 446 | dispatch_group_t group = dispatch_group_create(); 447 | // 队列组中的任务执行完毕之后,执行该函数 448 | dispatch_group_notify(dispatch_group_t group,dispatch_queue_t queue,dispatch_block_t block); 449 | 450 | // 进入群组和离开群组 451 | dispatch_group_enter(group);//执行该函数后,后面异步执行的block会被gruop监听 452 | dispatch_group_leave(group);//异步block中,所有的任务都执行完毕,最后离开群组 453 | //注意:dispatch_group_enter|dispatch_group_leave必须成对使用 454 | ``` 455 | ##### 6.信号量(并发编程中很有用) 456 | 457 | ### 15.如何使用队列来避免资源抢夺? 458 | 459 | 可以用**串行队列**或者是**同步锁**。保证在同一时间内,只有一条线程在访问资源。 460 | 461 | 462 | ### 16.数据持久化的几个方案 463 | 464 | * plist文件(属性列表) 465 | * preference(偏好设置) 466 | * NSKeyedArchiver(归档) 467 | * SQLite 3 (FMDB) 468 | * CoreData 469 | 470 | 在此不展开了,篇幅比较大,详情见我[另一篇文章](https://github.com/liberalisman/iOS-Summary-Part1#08-ios数据持久化方案) 471 | 472 | ### 17.说一下AppDelegate的几个方法?从后台到前台调用了哪些方法?第一次启动调用了哪些方法?从前台到后台调用了哪些方法? 473 | 474 | 1.应用程序启动,并进行初始化时候调用该方法: 475 | 476 | ```objc 477 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 478 | } 479 | ``` 480 | 481 | 2、应用进入前台并处于活动状态时候调用: 482 | 483 | ```objc 484 | - (void)applicationDidBecomeActive:(UIApplication *)application {} 485 | ``` 486 | 487 | 3、应用从活动状态进入到非活动状态: 488 | 489 | ```objc 490 | - (void)applicationWillResignActive:(UIApplication *)application {} 491 | ``` 492 | 493 | 4、应用进入到后台时候调用的方法:applicationDidEnterBackground: 494 | 495 | ```objc 496 | - (void)applicationDidEnterBackground:(UIApplication *)application {} 497 | ``` 498 | 499 | 5、应用进入到前台时候调用的方法: 500 | 501 | ```objc 502 | - (void)applicationWillEnterForeground:(UIApplication *)application {} 503 | ``` 504 | 505 | 6、应用被终止的状态: 506 | 507 | ```objc 508 | - (void)applicationWillTerminate:(UIApplication *)application {} 509 | ``` 510 | 511 | ### 18.NSCache优于NSDictionary的几点? 512 | 513 | 在做缓存时,优先使用`NSCache`而不是`NSDictionary`,我们熟悉的框架`SDWebimage`就是采用的`NSCache`。 514 | 515 | `NSCache`优点如下: 516 | 517 | 1. 系统资源将要耗尽时,它可以自动删减缓存。 518 | 2. 可以设置最大缓存数量。 519 | 3. 可以设置最大占用内存值。 520 | 4. `NSCache`线程是安全的。 521 | 522 | ### 19.知不知道Designated Initializer?使用它的时候有什么需要注意的问题? 523 | 524 | 基本遵循以下三个规则(约束条件) 525 | 526 | 1. 子类如果有指定初始化函数,那么指定初始化函数实现时必须调用它的直接父类的指定初始化函数。 527 | 2. 如果子类有指定初始化函数,那么便利初始化函数必须调用自己的其它初始化函数(包括指定初始化函数以及其他的便利初始化函数),不能调用super的初始化 528 | 函数。 529 | 3. 如果子类提供了指定初始化函数,那么一定要实现所有父类的指定初始化函数。 530 | 531 | 这个问题没有想好该如何回答,希望大家指教。 532 | 533 | ### 20.实现description方法能取到什么效果? 534 | 535 | 举例来说明吧 536 | 537 | ##### 1.我们创建一个自定义对象 538 | 539 | ```objc 540 | @interface Person : NSObject 541 | 542 | @property (nonatomic,copy ) NSString *name; 543 | @property (nonatomic,copy ) NSString *hobbies; 544 | 545 | @end 546 | ``` 547 | 548 | ##### 2.在`ViewController`中,我们引用了`Person`类 549 | 550 | ```objc 551 | - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 552 | { 553 | Person *p = [[Person alloc] init]; 554 | 555 | p.name = @"lili"; 556 | 557 | p.hobbies = @"paint"; 558 | 559 | NSLog(@"%@",p); 560 | } 561 | ``` 562 | 此时打印出来的结果如图: 563 | 564 | ```objc 565 | 2017-06-15 13:12:00.471 cop[1561:258406] 566 | ``` 567 | 568 | **是不是和你预计的效果还是差了一些?** 569 | 570 | 此时我们就需要重写对象的**`description`**方法 571 | 572 | ##### 3.此时在`Person`的`.m`文件中,我们进行如下操作: 573 | 574 | ```objc 575 | #import "Person.h" 576 | 577 | @implementation Person 578 | 579 | - (NSString *)description { 580 | 581 | return [NSString stringWithFormat:@"_name = %@,_hobbies = %@",_name,_hobbies]; 582 | } 583 | @end 584 | ``` 585 | 586 | 再次打印 587 | 588 | ```objc 589 | 2017-06-15 13:21:20.132 cop[1593:275015] _name = lili,_hobbies = paint 590 | ``` 591 | 592 | 通过对比之后,大家一定就明白了 593 | 594 | 595 | ### 21.objc使用什么机制管理对象内存? 596 | 597 | Objective-C使用`AEC自动引用计数`来有效的管理内存。 598 | 599 | 他遵循的原则是,谁引用,谁销毁。 600 | 601 | `Retain`,`Copy`,`Alloc`,`New`等必然对应`Release`。 602 | 603 | 604 | 605 | 606 | 607 | 608 | 609 | 610 | --------------------------------------------------------------------------------