Rookie program Ape's Crawl Pit Diary (i)

Source: Internet
Author: User
Tags manual writing

1.NSDictionary initialization

Random into (a bit of nonsense): rarely with the notice, today conveniently wrote a notice to pass the value, dead or Alive pass, interrupted point find a half-day also did not find, finally is a friend found, send and receive the notification name write inconsistent ... I am also drunk, later or habitually to the notice name of the macro bar!!

In Objective-c, there are many ways to initialize nsdictionary.

Method 1: [Nsdictionary dictionarywithobjectsandkeys:<# (ID), ...#>*dic = @{@ "key  ": Value}

Where's The pit?

The pit is in the second method of initializationNSDictionary *dic = @{@"key":value}

How the hell does it pit?

If your value is nil, it will cause a crash:

‘NSInvalidArgumentException‘, reason: ‘*** -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]

This means using [__nsplaceholderdictionary InitWithObjects:forKeys:count:] This initialization method, found that the keys count and the number of objcects does not match

How to circumvent?

When using @{@ "key": value} This way, it is important to determine whether the value is nil, and nil to join the dictionary

Or

Use the standard initialization method:

NSDictionary dictionaryWithObjectsAndKeys:value1,@"v1",value2,@"v2",value3,@"v3", nil];

Or a few other initialization methods, so that if value is nil it will not be added to the dictionary, using Objectforkey: The object will be a nil object and will not cause a crash.

Association:

Initialize with the @[] method Nsarray also has this pit, the avoidance method is the same as the dictionary

2. Dictionary Turn model

Before writing the code, with Mjextension after a long time did not write.

+ (Instancetype) shopwithdict: (nsdictionary *) dict*shop = [[Self alloc] init]; [Shop setvaluesforkeyswithdictionary:dict]; return shop; }

Or

-(Instancetype) Initwithdict: (Nsdictionary *) dict{if (self = [super init]) {[Self setvaluesforkeyswithdictionary:dict] ;} return self;} + (Instancetype) shopwithdict: (nsdictionary *) Dict{return [[Self alloc] initwithdict:dict];}

In the model's. h file, you provide a property interface and these two instantiation methods that implement them in the. m file.

-(void) Setvaluesforkeyswithdictionary: (nsdictionary<nsstring *, id> *) keyedvalues;

Header file for method above: Given A dictionary containing keyed attribute values, to-one-related objects, and/or collections of To-many-rela Ted objects, set the keyed values. Dictionary entries whose values is NSNull result In-setvalue:nil forkey:key messages being sent to the receiver. (About Nsnul L
The pit that meets today,

Collapsed here, too young, looking for a long time, wasted a lot of times, and finally found that the properties of the model write a little, such as, the dictionary has eight key-value pairs, model attributes only 5. (As for why the following wireless calls cause memory crashes, not yet known-_-!) in short, the model properties can only be more than a few! Model properties can only be more than a few! Model properties can only be more than a few! The important thing to say three times

Use

-(void) Setvaluesforkeyswithdictionary:

This method also needs to be noted that the key value (key) in the dictionary must correspond to the property name one by one (same) and encounter the ID: When keywords:
Because of the many attributes. Manual writing SetValue too Troublesome

+ (Instancetype) Picinfo: (Nsdictionary *) dict{    *picmodel = [[Self alloc] init];    [Picmodel setvaluesforkeyswithdictionary:dict];     return Picmodel;}

单纯的运行setValuesForKeysWithDictionary是必然core的

-(void) SetValue: (ID) value forundefinedkey: (NSString *) key  {    if([key Isequaltostring:@ "ID"])        = value;

At this point only need to rewrite -(void) SetValue: (ID) value Forundefinedkey: (NSString *) Key method can be

and change the ID in the declaration to UserID.

This way, the execution of the program quickly, but also save a lot of manual code.

-(void) SetValue: (ID) value forundefinedkey: (NSString *) key{    if([key Isequaltostring:@"ID"])    {        @ "shop_id") ;    }    [Super Setvalue:value Forkey:key];    //     [Super Setvalue:value Forundefinedkey:key]; it's supposed to be up there, watch it when you knock.

Or like the above.

-(void) SetValue: (ID) value forundefinedkey: (NSString *) key{if([key Isequaltostring:@ "ID"= value;}}

For the mjextension I use now, incidentally, here's a note:
The more commonly used

1. plist→ Model Array

Reference #import "MJExtension.h" in the controller

Model array = [model class name objectarraywithfilename:@ "filename. plist"];

2. Optimization of NSLog, solve the problem when debugging, print model, only print out memory address

How to use: in a. m file of a model class, reference #import "MJExtension.h"

Between the @implementation and the @end, write Mjlogallivrs.

3. Optimization of the nscoding, no need to write cumbersome solutions and archiving methods

How to use: in a. m file of a model class, reference #import "MJExtension.h"

Between the @implementation and the @end, write Mjcodingimplementation.

4. Dictionary arrays → model arrays

4.1 Scene One: [ dictionary 1,

Dictionary 2,

Dictionary 3 ]

If each dictionary is a model, you can use the

Nsarray *modelarray = [model class name Objectarraywithkeyvaluesarray: Field array];

4.2 Scene Two: On the basis of scenario one, each dictionary has an array (assuming the array's key value is Arrayname), the array contains several identical models, using the following method

How to use:

First, in the model class. m file, introduce #import "MJExtension.h"

And then write between the @implementation and the @end.

-(Nsdictionary *) objectclassinarray{    return @{@ "arrayname"  Class]};}
5. If the dictionary key in the dictionary array that the server passes over is the key in OC, the premise of using Mjextention is that the attribute names in the model and the key of the group are identical (case-sensitive).

Using Replacedkeyfrompropertyname

How to use: 1. introducing "MJExtension.h" to the model class. m file

2. Implementation methods

+ (Nsdictionary *) replacedkeyfrompropertyname{    return  @{@ "non-keyword property name": @ "Array of Key"};}
6. Single dictionary → single model
+ (Instancetype) objectwithkeyvalues: (Nsdictionary *) keyvalues

The company's old project inside with the Mantle,github on the Star exploded table of cow B frame, (but forget almost, 0.0 ... MJ Big God used it in a day, mjextension) here is attached to the South Peak son of the great god of Mantle blog link, the great God's blog is worth learning

The first article on this, are small problems, too young, follow-up should be a lot of similar articles, mainly to enhance their impressions, the Great God forgive me ....

Rookie program Ape's Crawl Pit Diary (i)

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.