Application of ORM in OBJECTIVE-C: Automatic conversion between entity object and dictionary

Source: Internet
Author: User



http://blog.csdn.net/cooldragon/article/details/18991973



There are many ORM-based frameworks in iOS development, such as Sqlitepersistentobject, where there are different requirements or scenarios in real-world development, and different ways of doing so, sometimes in projects that don't use ORM frameworks, or because of corporate or project group habits or specifications, actual project requirements, or technical requirements. , the full ORM framework is not used, but some of the repetitive, verbose code uses a certain ORM function to improve efficiency.



Based on performance or flexibility considerations, or requirements for complex queries, or project team requirements, database access in a project is generally directly used in SQL or with Fmdb (some product development type another, software architecture design is another topic, from the author N-year interview n multiple iOS developers see the Fmdb accounted for a large majority, There is no shortage of such a famous app), the code uses a dictionary, an array or a custom class (or entity) as the data carrier, Fmdb Fmresultset has a resultdictionary can directly return to the dictionary nsdictionary, and then combined with the following auxiliary class, Able to solve the problem of automatic conversion between entity object and dictionary (nsdictionary), without a key, a key, a property of a property to write their own code, to avoid repeated handwriting chores and spelling errors, greatly improve the development efficiency.





[OBJC]View Plaincopy

//
EntityHelper.h
The prerequisites are: The dictionary key is the same as the word for the entity object property, and the size can be ignored.
//
Created by Longjun on 13-1-28.
Copyright (c) 2013 RL. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Entityhelper:nsobject
Converting a Dictionary object to a solid object
+ (void) dictionarytoentity: (nsdictionary *) dict entity: (nsobject*) entity;
Entity object to Dictionary object
+ (nsdictionary *) entitytodictionary: (ID) entity;
@end







[OBJC]View Plaincopy

//
Entityhelper.m
Arprojectforpad
//
Created by Longjun on 13-1-28.
Copyright (c) 2013 RL. All rights reserved.
//
#import "EntityHelper.h"
#import <objc/runtime.h>
@implementation Entityhelper
#pragma mark-custom Method
+ (void) dictionarytoentity: (nsdictionary *) dict entity: (nsobject*) entity
{
if (dict && entity) {
For (nsstring *keyname in [dict AllKeys]) {
//Build a set method for a property
nsstring *destmethodname = [NSString stringwithformat:@ "set%@:", [KeyName capitalizedstring]]; //capitalizedstring Returns the first uppercase string of each word (the remaining letters of each word are converted to lowercase)
SEL destmethodselector = nsselectorfromstring (destmethodname);
if ([Entity Respondstoselector:destmethodselector]) {
[Entity performselector:destmethodselector withobject:[dict objectforkey:keyname];
}
}//end for
}//end if
}
+ (nsdictionary *) entitytodictionary: (ID) entity
{
Class clazz = [Entity class];
U_int count;
objc_property_t* properties = Class_copypropertylist (Clazz, &count);
nsmutablearray* Propertyarray = [Nsmutablearray arraywithcapacity:count];
nsmutablearray* ValueArray = [Nsmutablearray arraywithcapacity:count];
For (int i = 0; i < count; i++)
{
objc_property_t Prop=properties[i];
Const char* propertyname = Property_getname (prop);
[Propertyarray addobject:[nsstring stringwithcstring:propertyname encoding:nsutf8StringEncoding]  ;
//Const char* AttributeName = property_getattributes (prop);
//NSLog (@ "%@", [NSString Stringwithutf8string:propertyname]);
//NSLog (@ "%@", [NSString Stringwithutf8string:attributename]);
id value = [entity performselector:nsselectorfromstring ([NSString stringwithutf8string:propertyname])];
if (value = =nil)
[ValueArray addobject:[nsnull Null]];
else {
[ValueArray Addobject:value];
}
//NSLog (@ "%@", value);
}
Free (properties);
nsdictionary* returndic = [nsdictionary dictionarywithobjects:valuearray Forkeys:propertyarray];
NSLog (@ "%@", returndic);
return returndic;
}
@end







Example of actual use (logical layer):





[OBJC]View Plaincopy


Business needs to return entity objects
-(userscoinfoentity*) Loadstudyrecord: (userscoinfoquery*) query
{
userscoinfoentity *userscoinfo = nil;
@try {
//  
nsdictionary *resultdict = [self loadstudyrecordfordict:query];
if (!resultdict) return nil;
//Dictionary values are automatically populated to entity object Properties
[Entityhelper dictionarytoentity:resultdict Entity:userscoinfo];
}
@catch (nsexception *exception) {
Nsassert1 (0, @ "exception=%@", Exception. Reason);
}
@finally {
}
return userscoinfo;
}
Business needs to be returned directly to the dictionary
-(nsdictionary*) Loadstudyrecordfordict: (userscoinfoquery*) query
{
if (!query | |!query. UserID | |!query. CourseID | |!query. scoid | |!query.type | |!query. TypeID) {
Nsassert (0, @ "Userscoinfoquery object or attribute cannot be empty");
return Nil;
}
nsdictionary *resultdict = nil;
fmdatabase *db = [fmdatabase databasewithpath:[common sharedinstance]. localmaindb];
@try {
if (![ DB Open]) {
[DB release];
//nslog (@ "DB open fail");
return Nil;
}
fmresultset *s = [db executeQuery:@ "SELECT ...  "];
While ([s next]) {
Resultdict = [s resultdictionary];
Break ;
}
[s close];
if (!resultdict) {
NSString *errmsg = [db lasterrormessage];
//nslog (@ "[db lasterrormessage]=%@", errmsg);
}
}
@catch (nsexception *exception) {
Nsassert1 (0, @ "exception=%@", Exception. Reason);
}
@finally {
[DB Close];
}
return resultdict;
}




Of course, the above code has a certain application scenario, there are certain limitations, such as:
The words of the dictionary key and entity object properties must be the same (size can be ignored), and no external mapping files are used here primarily to simplify the code and project needs.






Application of ORM in OBJECTIVE-C: Automatic conversion between entity object and dictionary


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.