iOS mantle real-combat analysis

Source: Internet
Author: User

The model layer code before the company project was that I used the JSON tool to generate the OBJECTIVE-C code directly, but I still felt it was quite easy, after all, I experienced the nsdictionary "dark" period without the model layer. But as the project progresses, the problem begins to emerge. So, one months ago, I saw the mention of mantle on the Objc.io, took a little time to look at, decided to first on the branch of the complete switch to mantle. Use for a period of time, performance does not cause any bottleneck, stability is acceptable. The network's requests were then integrated on the basis of mantle, MK and RAC, and were fully used on new projects. There was no problem at first, but then I gradually found out that the mantle was good, but it was not enough to solve all the problems.   Recently saw the "why sing iOS 6.0 chose mantle" article, I decided to write a blog down some model layer of the pit. A brief analysis of the advantages and disadvantages of the various building model layer methods: First, the tool generation model advantages: 1, easy to use,Beginners can also get started in 10 seconds2, there is a certain fault-tolerant code 3, the code generation is relatively neat and specification, some tools can also choose whether to use ARC 4, the generation of simple model time-consuming less shortcomings: 1, the tool generated by the class name or property name is not very consistent with the requirements, often need to modify itself, but the change is quite troublesome, It needs to be quite focused in case there is somewhere to forget to change. 2. The generated code is quite lengthy. 3, to adapt to change the field of the trouble, once the property needs to modify the field, either manually modify, or regenerate, but it is very likely to repeat the disadvantage of 1 steps. 4, the model between someThe inheritance relationship is also implemented by modifying the inheritance itself. Second, based on the operation of the model (mantle) Advantages: 1, reduce a large number of template code 2, modify the field mapping is quite simple 3, the extension is relatively convenient 4, can achieve more complex mapping relations and value conversion 5, debugging the exception can be better to find the problem 6, Implementation of the Nscopying and nscoding protocol, can easily serialize the disadvantage: 1, based on the runtime attribute mapping, has a certain impact on performance 2, some fault-tolerant processing needs to resolve itself, otherwise it is likely to crash (detailed below) 3,A lot of framework codeThree, nsdictionary model advantages: 1, without any foundation, directly available 2, fault tolerance is relatively high 3, ignoring anydata structure, all can adapt toDisadvantages: 1, the maintenance cost is very expensive 2,The compiler cannot check spelling, it needs to define a number of key constants, otherwise it is extremely easy to write wrong3, debugging relative Trouble in fact, nsdictionary typemodel still has a certain purpose, after all, in some cases, there is no need to waste energy to build a very short or soon will be released model. However, in most cases, it is necessary to build a reasonable model to ensure the robustness and development efficiency of the project. Previously, my boss and I said that iOS application MVC layer Three, m this layer actually has helped you to complete the majority of the server, to the client to deal with the model, both consumption performance and reduce the development efficiency. At the time, I thought it was more correct, but as MVC's C became bloated, M became more and more lightweight. A lot of things are coupled in the Controller,model this layer can do well, it can reduce the complexity of controller to some extent. Together with the work of the discovery, a only nsdictionary, no real model of commercial applications, really very detrimental to maintenance. For all these reasons, I have decided to formally use the mantle fully.   But mantle is not omnipotent, I still met a few problems. Null value if your property is a base numeric type, JSON returns a null value, so when the mantle generates the model, it crashes decisively. The problem and solution is the same as "why sing the iOS 6.0 choose Mantle", the model to implement the Setnilvalueforkey: method. Recommended use of base classesinherit, then write this method once to solve this problem for all model. Reasonable mapping of key values copy code 1 {2 "code": "Result": {4 "Access_token": "M_xxxxxxx", 5 "user_id": 11116}7} Copy code example Like the JSON above, suppose the entire JSON is amodel, if you are mapping directly in JSON format, create an additional model class of "result". But maybe it doesn't have to be so complicated, but it can be written.1 + (Nsdictionary *) JSONKeyPathsByPropertyKey2 {3 return @{@ "Accesstoken": @ "Result.access_token", 4 @ "UserId": @ "result.user_id"};5} This makes it easy to map to the corresponding property and does not require additional new model classes. Why not write the "code" mapping here, because if the property name and JSON key name is consistent, you can omit the non-write mapping, specifically, you can see the mantlesource code. The problem with the type of the value is the toughest, not the background pit mates, but JSON's numeric types and documentation are commonplace. As the most recent front line with the user, I can only try to finish the finishing touches, can not completely indulge in it. The usual methods are as follows: 1, conversionPre -processing JSON data before the model, converting or deleting a value that does not match the type  2, for these easy-to-collapse values, write Nsvaluetransformer conversion     These really solve the problem, but the efficiency drops a lot, you have to focus on a variety of possible situations. Believe me, if you do this, you can't sleep well.   I'll give you a list of the exceptions that are caused by several types of inconsistencies:  1, the bool type, and the string type of the return value. The  2, property is the NSString type, the return value is the number type, and mantle only converts the NSNumber type. When you call the dedicated method of length and other nsstring, you understand.  3, a mapping similar to the above "Result.access_token" is used, but the return value is not of type object (for example, array type).  4, the property is Nsarray, the conversion is used, and the return value is object.     rest assured, in the actual situation, there will be no more than 4 of these possibilities. Fortunately, mantle help you deal with 1, 3, 4 of these situations (if both object and array are using the conversion method, when the conversion will handle these exceptions), only in debug mode throws an exception, release will not crash. If you do not want to be interrupted by these exceptions during debugging, you can comment out the corresponding code in the Mtlvalidateandsetvalue method.   Next people may think it's too weird, why a small client has to avoid so many traps because of a mantle. I just meet so many traps, think of the solution, I also grew up. For JSON type, I have the following considerations:  json is actually only 4 types, string, number (int, bool ...), object, array. In objective-c correspondence that is, NSString, NSNumber, Nsdictionary, Nsarray, so to avoid the type problem is also from these several classes to start. Here to say why the attribute has int, bool, etc., I only belong to a class of nsnumber. Because essentially, mantle only converts objects of the NSNumber type, and in SetValue, the corresponding NSNumber method is called by the system according to the type. Because the type errors of number and string are the most common, but also the most covert (calls similar to the Intvalue method can not see the clue), for this I wrote a avoidmtlmodelcrash category, the address on GitHub, after using this category, the crash of NSString and NSNumber type problems can be solved basically. If it is Nsarray or nsdictionary set to NSString property is also undetectable, but in the face of such serious type problem, I would like to sit down with the small partners, talk about "life" it.     Flexible conversions   For example, some interfaces return data as arrays, but many times only the first element of the array is needed. We can directly allude to an element inside the array.  1 + (Nsvaluetransformer *) pointListJSONTransformer2 {3     return [Mtlvaluetransformer Transformerwithblock:^id (Nsarray *array) {4         return [array firstobject];5    }];6} except A property map and a fixed type conversion for each property, Mtljsonserializing's protocol and classforparsingjsondictionary such a method can change the interpreted class. For example, B, C areinherit a and use mantle to generate a Class A object. A class can use this method to select different subclasses to generate the object. But the externally visible interface is also a Class A interface, which is similar to Nsarray (Nsarray actually has a lot of sub-classes)

iOS mantle real-combat analysis

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.