Http://www.jianshu.com/p/cb54054d3add
Cold elder brother teaches you to learn iOS-experience ramblewords 2848 Read 1896 comments
- Load Magical
- AOP-oriented tangent programming
- NSNumber Or Int
- @ () Suitable for 64-bit
1 Let appdelegate reduce the burden
After a long period of study you finally mastered the iOS Dafa you found a job with iOS development and vowed to start your coding career The boss is very important to you and then tell you that I think your technology is very diao, then this project you do it yourself. Oh, that means you're going to have to deal with this project. From the software architecture to the page show you??
With their own dabbler level PAPAPA coding determination must be the code package good write beautiful (actually listen to the big God said encapsulation actually don't understand)
The project comes to an end the boss tells you our app our app will have to share the function of the circle of friends in the future, otherwise how to embody my product
And then you hear that the Friend League is better (with the suspicion of advertising) you went to the Friends League to read their documents and he told you you were going to write this thing in the Appdelegate Didfinishlaunch method.
setAppKey:@"XX"]; // 注册 [UMSocialWechatHandler setWXAppId:@"XXX" appSecret:@"XX" url:@""]; // 注册QQ [UMSocialQQHandler setQQWithAppId:@"XXX" appKey:@"XXX" url:@""];
After a few days, the boss said we need to count the information on my page you have access to the Friends of the league statistics in Appdelegate Didfinishlaunch and more lines of code
The demand is endless I need bug stats (Fir HUD) to alert the user scoring system (irate) push (Jpush homing pigeon push. )
You were determined to have the code to encapsulate the perfect writing of the beautiful Heart has been completely defeated by the boss's needs
Don't worry, cold brother teaches you tips.
I don't know if you've used Iqkeyboardmanage and irate, this smart library.
Daniel's Readme wrote this passage.
Key Features
1) codeless, Zero line of code does not need to write any codes
2) Works automatically//auto work
3) No more Uiscrollview//no ScrollView required
4) No more subclasses//No need to inherit parent class
5) No more Manual work//No configuration required
6) No more #imports//no import required
It's not magical, it's just Daniel using the + Load method
Learning OC knows that this code will be automatically called when a class is loaded into the runtime.
Write a class that inherits from NSObject
#import<Foundation/Foundation.h>@interfaceThirdpartservice:NSObject@end#import"ThirdPartService.h"#import"UMSocial.h"#import"UMSocialWechatHandler.h"#import"UMSocialQQHandler.h"#import<MobClick.h>#import<FIR/FIR.h>@implementationThirdpartservice + (void) Load {Staticdispatch_once_t Oncetoken;Dispatch_once (&oncetoken, ^{TODO here is my own test of fir HUD [Fir Handlecrashwithkey:@ "XX"];Friends League [Umsocialdata Setappkey:@ "XX"]; //hide the platforms that are not installed [Umsocialconfig Hiddennotinstallplatforms:@[umsharetoqq,umsharetoqzone, Umsharetowechatsession,umsharetowechattimeline]]; //registration [Umsocialwechathandler setwxappid:@ "XX" AppSecret:@ "XX" Url:@ ""]; //registered QQ //TODO QQ is not true [Umsocialqqhandler setqqwithappid:< Span class= "hljs-string" >@ "xx" Appkey:@ "XX" Url:@ ""]; //TODO um statistics [mobclick startwithappkey:@ ""]; [Mobclick setcrashreportenabled:no]; nslog (@ "third party service Registration Complete");}); @end
Similar to positioning can also be written like this
Paste_image.png
Modules and services are completely disassembled
But some services such as APNs need launchoption that can only be written in appddelegate but so the words have been removed a lot of code, only a few fixed, then modify Appdelegate will feel very clear
2 Viewcontroller inheritance?
Then the above said that we have access to the Friends of the league statistics the most basic thing is the statistics page of PV
Paste_image.png
Friends of the League of this write for the novice we think this is not easy?
I opened a VC (Homeviewcontroller)
In the code, write this sentence.
-(void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated];#ifndef DEBUG [MobClick beginLogPageView:NSStringFromClass([self class])];#endif}-(void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated];#ifndef DEBUG [MobClick endLogPageView:NSStringFromClass([self class])];#endif}
And then I could have dozens of or even hundreds of pages in a project. PV I'm not going to write that on every show.
Smart, we think of inheritance.
Such asMyBaseViewController:UIViewController
This is going to do one thing. Change all classes in our project that inherit from Uiviewcontroller to inherit from it. MyBaseViewController
but do you really think that's okay? We have dozens of controllers in a project. I'm going to change every controller.
This repetitive work is boring, but it's easy to make mistakes. You're copying a replicator and you're missing out on a class. What's important is that many of the classes in our project are not directly inherited from the ones that UIViewController
might UITableViewController
UICollectionViewContr0ller
UINavigationController
or may not be common. UISearchDisPlayController
UIPopoverController
UIPresentController
Ah??
This is not the pit of the future you mix up Daniel recruit a little brother you tell him all the classes you have to inherit self-written all kinds of parents are always inadvertently make mistakes some classes forget to inherit the late check up difficult very large waste of time so this design is unreasonable
Here is an article from Nshipster Blogger in English
Chinese translation
and an article explaining the runtime. Portals
Practice
We can intercept the attraction method by crossing the code.
In this way, the idea of plane-oriented programming (AOP)
On the Code
#import<UIKit/UIKit.h>@interfaceUiviewcontroller (AOP)#warning run-time change method to do some aspect programming such as statistics and so on@end#import"Uiviewcontroller+aop.h"#import<objc/runtime.h>#import<MobClick.h>@implementationUiviewcontroller (AOP) + (void) Load {Staticdispatch_once_t Oncetoken;Dispatch_once (&oncetoken, ^{class = [Self class];When swizzling a class method, use the following:Class class = Object_getclass ((id) self); Swizzlemethod (class,@selector (Viewdidload),@selector (aop_viewdidload)); Swizzlemethod (class,@selector (viewdidappear:),@selector (aop_viewdidappear:)); Swizzlemethod (class,@selector (viewwillappear:),@selector (aop_viewwillappear:)); Swizzlemethod (class,@selector (viewwilldisappear:),@selector (aop_viewwilldisappear:));});}void Swizzlemethod (class class, Sel originalselector, sel swizzledselector) {Method Originalmethod = Class_ Getinstancemethod (class, Originalselector); Method Swizzledmethod = Class_getinstancemethod (class, Swizzledselector);BOOL Didaddmethod =class_addmethod (class, Originalselector, Method_getimplementation (Swizzledmethod), Method_ Gettypeencoding (Swizzledmethod));if (Didaddmethod) {Class_replacemethod (class, Swizzledselector, Method_getimplementation (Originalmethod), Method_ Gettypeencoding (Originalmethod));}else {method_exchangeimplementations (Originalmethod, Swizzledmethod);}} - (void) Aop_viewdidappear: (BOOL) Animated {[Self aop_viewdidappear:animated];} -(void) Aop_viewwillappear: (BOOL) Animated {[Self aop_viewwillappear:animated];#ifndef DEBUG [Mobclick beginlogpageview:Nsstringfromclass ([Self class]);#endif}-(void) Aop_viewwilldisappear: (BOOL) Animated {[Self aop_viewwilldisappear:animated];#ifndef DEBUG [Mobclick endlogpageview:Nsstringfromclass ([Self class]);#endif}-(void) Aop_viewdidload {[Self aop_viewdidload];if ([Self iskindofclass:[Uinavigationcontroller class]]) {Uinavigationcontroller *nav = (Uinavigationcontroller *)Self Nav. Navigationbar. Translucent =NO; Nav. Navigationbar. Bartintcolor = Global_nAvigation_bar_tin_color; Nav. Navigationbar. Tintcolor = [Uicolor Whitecolor];Nsdictionary *titleatt = @{nsforegroundcolorattributename:[UIColor WhiteColor]}; [[uinavigationbar appearance] settitletextattributes:titleatt]; [[uibarbuttonitem appearance] Setbackbuttontitlepositionadjustment:uioffsetmake (0,-60) ForBarMetrics:uibarmetricsdefault];} //self.view.backgroundColor = [Uicolor Whitecolor]; self.navigationcontroller.delegate = (id<uigesturerecognizerdelegate>) self;} @end
Picture code a convenient to watch
Paste_image.png
Paste_image.png
We've made full use of black magic to achieve the benefits of aspect-oriented programming
Thought source here http://casatwy.com/iosying-yong-jia-gou-tan-viewceng-de-zu-zhi-he-diao-yong-fang-an.html
黑魔法非毒药 遵守一个规范写出来的代码是不会Crash的 只要能帮我们解决问题就是好东西
黑魔法性能 有瓶颈? 都到runtime的底层了 你还担心有瓶颈 少年安心使用就好了 不服 可以用Time Profiel测试
黑魔法也非万能 像 我们在导航控制器要封装手势 统一管理左侧返回按钮 这些东西 还是继承来得好
Technology is the tool black Cat, White cat, catch mouse is a good cat
华丽的分割线
3 Network access parameters in the end with the basic data type or object
Here are two ways to see
Paste_image.png
+ (void) Getdataatpageno: (NSNumber *) PageNo PageSize: (NSNumber *) pageSize Complete: (completeblock) Complete {nsmutabledictionary *param = [nsmutabledictionary dictionary]; if (pageSize) {[param setobject:pagesize forkey:@ "PageSize"];} [Param Setobject:pageno Forkey:@ "PageNo"]; //SendRequest} + (void) Getdata2atpageno: (long) PageNo PageSize: (Long) PageSize Complete: ( Completeblock) Complete { nsmutabledictionary *param = [nsmutabledictionary dictionary]; [Param setobject:@ (pageSize) Forkey:@ "PageSize"]; [Param setobject:@ (PageNo) Forkey:@ "PageNo"]; //SendRequest}
The design of a method for parameter requests when accessing a network request is mainstream for both of the above
- Using objects as parameters
- Using basic data types to make parameters
In general, this is not a big difference, but Han's advice is that Never
basic data types appear
In general, developers may feel that there is no difference. Let me give you an example.
In the design of a paging display data: The logic on the page is the default loading of the first page per page length of ten (server side of the students are generally friendly by default, the length of each page is 10) but the pass will overwrite the default parameters of the background write, such as the upload of the server will spit 20 data
- In the first design scenario: A pageno PageSize member variable may be retained in a controller
对象
, and the corresponding parameter is passed to the request method when the drop-down refresh or pull-up is loaded, and if there is no special requirement, the PageSize object is optional. That is, it is possible for nil, that the corresponding param may not have this parameter passed to the server.
The Server will return 20 data from one page to us.
- In the second design: may also be in a controller to retain a pageno pagesize
基本数据类型
member variable, when accessing the network request to the corresponding method, generally no special needs we also do not set the value of pagesize, but the basic data type in OC and C language This traditional programming language has the default value for 0
, although we did not assign a value to pagesize but the default system defaults to 0 This initial value then passed to the server will overwrite the server write default pagesize=10 such requests will not error Nor does it return data
Super Hard to debug
So in the network access to the opinion of cold brother is the Never
emergence of basic data types
4 Benefits of using NSNumber than basic data types? 64-bit adaptation issues
We generally use it as a parameter cache for network requests or to display the page
- For the parameters of the network request because Nsdictionary can only put objects so nsnumber the best way
- The cache is cached to plist or keyarchive is required, so nsnumber is also a good fit.
3 Show to Page
I've seen a friend that assigns a value to a page.
Paste_image.png
It seems like there's nothing wrong with us seeing this.
But we switched the device to a 32-bit device below iphone5s.
Paste_image.png
Notice there's a warning here.
Why don't we take a look at Nsinteger's head file?
Paste_image.png
Under 32 the device is int in 64 bits is a long
We all know that Apple does not allow 64-bit apps to be shelves but it seems like we've never adapted for 32-bit and 64-bit.
In the case of printf and NSLog, the corresponding%d%zd%f placeholder is very strict if the item does not cause unexpected results
Paste_image.png
Paste_image.png
Actually get a nsnumber we don't know if he is an int long unsigned int Bool directly for a type conversion is risky but in fact clang provides us with a very useful macro@()
Paste_image.png
NSNumber is not a simple class it is an implementation reference for a class cluster in the cocoa
Http://www.cocoachina.com/ios/20140109/7681.html
Http://www.cocoachina.com/ios/20150106/10848.html
Http://www.cocoachina.com/ios/20141218/10688.html
I'm going to get an ad from the public, and my article will be published to this public number.
** 加个欢迎扫码关注吧**
Paste_image.png
Cold elder brother teaches you to learn iOS-experience ramble