Why did I choose Mantle and ios6.0mantle for iOS 6.0?

Source: Internet
Author: User

Why did I choose Mantle and ios6.0mantle for iOS 6.0?

Recently, CHANGBA iOS 6.0 has been launched successfully. 18-person-month investment, 2500 commit, several 100,000 lines of code modification. CHANGBA iOS has taken a new look from the inside out. Thanks to our friends who are working together.

6.0 a major modification was the reconstruction (new) of the Model layer based on Mantle. Here, I will not introduce Mantle more. I will only share the decision-making and execution process of using Mantle.

Problems we encountered

CHANGBA is an App that has been launched for more than two years. Its product form is evolving and iterated fast. Therefore, various problems are inevitable:

  • The Model layer is not sound and there is no uniform structure. Different engineers have very different practices. Most of them are dumb and there is no unified serialization mechanism.
  • Business Logic redundancy, dispersion, and inconsistency
  • Random module division, chaotic dependency, and difficult maintenance
  • NSDictionary appears everywhere as the data type that carries the business (sqlite, Model object, API, Notification, web, OpenURL etc .), the correctness of parameters and values is not checked by the compiler at all. It is easy to write errors in strings, and the risk is extended to runtime, which leads to low-level bugs.
  • There are basically no documents and comments (combined with the above, it is difficult to understand the code without a debugger)
  • Hundreds of APIS, complex services, fast changes, and difficult reconstruction. The same API request may be duplicated and inconsistent.
  • Some parameters and return values of the API, the same parameter/return value may have different types. Because the API needs to be forward compatible, it is costly to modify the API.

In addition, there are other engineering constraints:

  • The existing API cannot be affected, and all things are limited to iOS-side modifications.
  • Code is a document, because there is no effort to maintain the document
  • Migrate the persistence methods of different models
  • Avoid writing large sections of boring Model serialization/deserialization code
  • There is no time to create mature, robust, reusable components and write documents

The above problems are long-standing and need to be solved. Otherwise, the development efficiency and code quality will be seriously affected. When I was still playing social games for 11 years, I designed and implemented a simple Objective-C Runtime-based value table Model structure and Conversion Tool (Model <=> csv) for numerical planning. However, there is still some distance between writing a mature solution, and there is no resource or time for maintenance, testing and documentation.

Following this idea, we found JSONModel and Mantle. The former is just 1.0. The latter is widely used in Github for Mac and the community is more mature (even the Slack has a channel ), so it became a better choice.

It turns out that this option is correct. After the launch of 6.0, the crash rate is significantly lower than the previous version, and the Mantle-related crash rate is less than 3%, large products can be used directly on large products.

In addition to maturity and stability, Mantle basically solves all the problems we encountered. The following describes some general Mantle usage experience. For basic usage, please directly move to Mantle's README.


Property name Conversion

Because the development language used by the API is different from Objective-C used by iOS, some reserved keywords may be used as the property name (such as id ), or accidentally override the attributes of the base class (such as description ). It is also possible that a bad name is used in the API, or a name that does not comply with the Objective-C naming convention is used, which must be converted.

You only need to implementMTLJSONSerializingProtocol and+JSONKeyPathsByPropertyKeyThe ing between the new and old names can be defined in the method. Mantle will automatically convert the attribute names during serialization and deserialization.


+ (NSDictionary *)JSONKeyPathsByPropertyKey {return @{@"identifier": @"id",@"displayDiscription": @"description",@"thisIsANewShit": @"newShit",@"creativeProduct": @"copyToChina",@"betterPropertyName": @"m_wired_propertyName"}}

A lot better, right? Yes, you only need to define a name ing relationship once. Mantle is responsible for Bidirectional conversion between the model and JSON. This logic does not need to be written at all, and its consistency must be maintained.

In iOS, Property type ing uses the NSURL type for processing URLs, but JSON only supports basic strings. Mantle can automatically convert the string to NSURL.

+ (NSValueTransformer *)URLJSONTransformer {return [NSValueTransformer valueTransformerForName:MTLURLValueTransformerName];}
NSValueTransformer is responsible for Bidirectional conversion between different types. Please study the implementation method of Mantle. On this premise, let readers have a question (in fact, this is a real story, and there are many similar stories. For details, see the top 10 teammates in iOS app development ):

Suppose we have an entity named KTVConcreteEntity. It has an attribute named entityID and its type is NSInteger. The problem is that entityID may be of the string type in the response of another API. How can this problem be solved without directly modifying the Mantle source code? You are welcome to leave a message below for discussion.


When an empty scalar exception occurs, API response has a null value, for example copyToChinaThis may not happen every time. JSON is like this:

{"copyToChina": null}

Mantle converts newShit to nil in this case, but what if it is a scalar such as NSInteger? KVC will directly raiseNSInvalidArgumentException.

Mantle assigns a value to the property based on KVC. KVC provides- (void)setNilValueForKey:(NSString *)keyMethod, let's specify a reasonable alternative value for nil. Let's take a look at the explanation of this method:

Invoked by setValue:forKey: when it’s given a nil value for a scalar value (such as an int or float).Subclasses can override this method to handle the request in some other way, such as by substituting 0 or a sentinel value for nil and invoking setValue:forKey: again or setting the variable directly. The default implementation raises an NSInvalidArgumentException.

For a scalar, the reasonable value is 0 in most cases. Let's look at the Code:

@interface MTLModel (KTVNullableScalar)@end@implementation MTLModel (KTVNullableScalar)- (void)setNilValueForKey:(NSString *)key {[self setValue:@0 forKey:key]; // For NSInteger/CGFloat/BOOL}@end


The problem is solved perfectly, and there is no need to write boring if/else everywhere.


Other important features

Mantle brings us a lot of convenience:

  • ImplementedNSCopyingProtocol, how nice it is to copy sub-classes directly
  • ImplementedNSCodingProtocol, say goodbye to NSUserDefaults
  • Provided-isEqual:And-hashBy default, the model makes the NSDictionary key much easier
  • Simple and Easy to do, without network-related operations

With such a strong and elegant design, I have to pay tribute to Github engineers!


I will only discuss several typical questions at the end of the article. You are welcome to discuss them. However, if your App has only tens of thousands of lines of code, or there are only a dozen APIs, or you haven't encountered any of our legacy problems, I suggest you do not introduce them. It is enough to use a nail clippers to kill chickens, you can find the key to the problem. Anyway and Mantle's implementation and ideas are worth learning and learning from every iOS engineer.


Original article link






Select the iOS 6 firmware of your device (Note: it is not the iOS 601 firmware) and ask what to do during jailbreak?

Is it an A4 device? The jailbreak is not perfect. C: \ Users \ Administrator Account Name \ AppData \ Roaming \ Apple Computer \ iTunes \ iPhone Software Updates is here ..... Note: The iPhone Software Updates folder is hidden.

The songs recorded by CHANGBA are shared to the circle of friends, but they always fail. I use Apple 4 S IOS601 for help.

Have you set an avatar for CHANGBA? If you have set the Avatar, it will work; otherwise, the sharing will fail ~

Related Article

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.