iOS mantle in combat

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.

Brief analysis

First, briefly analyze the advantages and disadvantages of the various methods of building the model layer:

First, tool generation model

Advantages:

1, easy to use, novice can also be 10 seconds to get started

2, have a certain fault-tolerant code

3, code generation is relatively neat and specification, some tools can also choose whether to use arc

4. Less time to generate simple model

Disadvantages:

1, the tool generated by the class name or attribute name does not meet the requirements, often need to modify themselves, but the change is rather cumbersome, but need to be quite focused in case there is no place to forget to modify.

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 of some inheritance relationship or need to modify their own inheritance to achieve.

Second, the model based on the runtime generation (mantle this type)

Advantages:

1. Reduce the number of template code

2. Easy to modify field mappings

3, the extension is relatively convenient

4. More complex mapping relationships and numerical conversions can be achieved

5, debugging the exception can be better to find the problem

6, the realization ofNSCopying和NSCoding协议,可以轻松序列化

Disadvantages:

1, based on the runtime attribute mapping, has some impact on performance

2, some fault-tolerant processing needs to resolve itself, otherwise it is likely to crash (detailed below)

3, Frame code a lot

Three, nsdictionary model

Advantages:

1, without any foundation, directly available

2. Relatively high fault tolerance

3, ignoring any data structure, can adapt to

Disadvantages:

1, maintenance costs are expensive

2, the compiler cannot check spelling, need to define a large number of key constants, otherwise extremely easy to write wrong

3, Debugging relative trouble

In fact, nsdictionary model still has a certain use, after all, in some cases, do not 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, the JSON returns a null value, so when the mantle generates the model, it breaks down decisively. This question and solution is the same as "Why do you sing iOS 6.0 select Mantle" , the model is implemented setNilValueForKey : method. It is recommended to use base class inheritance, so writing this method solves this problem for all model.

Reasonable mapping of key values

1 {2     "code": 13     "Result": {4         "Access_token": "M_xxxxxxx" , 5         " user_id ": 11116    }7 }

For example, the JSON above assumes that the entire JSON is a model, so if you map directly in JSON format, create an additional model class "result". But maybe it doesn't have to be so complicated, but it can be written.

 1  + (nsdictionary *) Jsonkeypathsbypropertykey  2  { Span style= "color: #008080;" >3  return  @{@ " accesstoken  : @"  result.access_token   ,  4  @ " userid   ": @"  result.user_id   " };  5 } 

This makes it easy to map to the corresponding attribute and does not require additional new model classes. Why do not write "code" here, because if the property name and the key name of the JSON is consistent, you can omit the non-write mapping, specifically, we can look at mantle source code.

Type issues for values

This problem is the most tricky, not to say back pit teammates, but JSON numeric types and documents do not match the usual. 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, the conversion model before the preprocessing JSON data, the type does not match the value of the conversion or deletion

2, for these easy to break the value, all write the Nsvaluetransformer conversion

These can really solve the problem, but the efficiency is much lower, you have to pay attention to a variety of possible situations. Believe me, if you do this, you can't sleep well.

Let me enumerate the exceptions that can result from several types of inconsistencies:

1. The attribute is of type bool and the return value is of type string.

2, the 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 an object type (for example, an array type).

4, the attribute 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, you may think it is too strange, why a small client also have to use a mantle to avoid so many traps. I just meet so many traps, think of the solution, I also grew up. For the JSON type, I have the following considerations:

JSON is actually just 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,github on the address, 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, the data returned by some interfaces is an array, but many times only the first element of the array needs to be used. We can directly allude to an element inside the array.

 1  + (nsvaluetransformer *) Pointlistjsontransformer  2  { Span style= "color: #008080;" >3  return  [Mtlvaluetransformer transformerwithblock:^id  (nsarray *array) { 4  return   [array firstobject];  5   6 } 

In addition to attribute mappings and fixed type conversions for each property, Mtljsonserializing's protocol also has classforparsingjsondictionary so that a method can change the interpreted class. For example, B, c both inherit 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 subclasses).

A little summary.

Model of the framework of the project has far-reaching impact, if in order not to leave a pit in the future, the model of this layer still need to think more, so as not to cause the maintenance of the situation.

iOS mantle in combat

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.