Reflection, Dict2Model, Model2Dict, Archive

Related tags

Reflection Reflect
Overview

image

感谢小饭的翻译 中文文档

###Selfless pay, just to make you faster to conquer swift!

.Reflection

.convert dictionary to model

.convert model to dictionary

.convert plist to model

.One key archive




Reflect


### Reflec .iOS 7.0
.Swift 2.0
.Xcode 7
.Reflection is available under the MIT license.




Installation

you can just drag the Reflect files into your own project, without any third-party library.

Structure Details:
.Coding about archiving
.Reflect reflection core package
.Dict2Model convert dictionary to custom object
.Model2Dict convert custom object to dictionary

Tips

This frame already prepares many examples for lazy guys and it’s easy to see the result when u just use the methord Person1.Convert(),Studetn1.Parse(),Book1.Action()
1.Parse-Parse8: convert dictionary to model
2.Convert1-Convert4: convert model to dictionary
3.Archiver1-Archiver3: One key archive




Core theory

  1. If you wanna use all the functions, all your custom model must inherit from Reflect Class.

  2. It’s better to use implicitly optional type for properties. Try not to use strange type like var v1: [string?]? , var v2: [string!]! and this frame has lots of assertion to help you use data type reasonably.

  3. This frame is based on requirement : parse json data into dictionaries then to model. Limitation: reckon without complictated data like Core Data support; without consideration of Struct.





Reflect

Call the properties of object directly can get the reflection for enumerations:

    p1.properties { (name, type, value) -> Void in
        println("\(name),\(type),\(value)")
    }

In addition, you can call class methods without initiate object while the value has no meaning:

    Person.properties { (name, type, _) -> Void in
        println("\(name),\(type)")
    }

The name is the property name of your model; Type is the type of encapsulated ReflectType data; Value is the value of variable; You can also see the detail of properties by seeing the reference of ReflectType encapsulation. For example, the specific data type, if it is basic data type, if it is array, if it is optional, if it is object transferred from OC and if it is custom class.:

var typeName: String!

/**  analysis type from system  */
var typeClass: Any.Type!

var disposition: MirrorDisposition!

var dispositionDesc: String!

/**  whether it is optional  */
var isOptional: Bool = false

/**  whether it is array  */
var isArray: Bool = false

/**  real type: optional + array  */
var realType: RealType = .None

In addition to above, I also add the function of printing like OC so that you can directly print the object. For example, print Book1(book1 class is in Archiver1.swift of the projcet) println(book1):

println(book1)

the result of console would be:

Reflect.Book1 <0x7a09fb10>: 
{
name: tvb
price: 36.6
}

ignore the field and field reflection of the process of analyzing additional features, subclass needs only rewrite the method.

/**  property mapping  */

//The model's property named 'userModel',get value width key 'user_model' from dictionay
func mappingDict() -> [String: String]? {
    return ["userModel":"user_model"]
}
 
 
/**  property ignore */

//Ignore the 'info' property of the model.
func ignorePropertiesForParse() -> [String]? {
    return ["info"]
}

You also can use the method below to complete converting from string to class

let cls = ClassFromString("Reflect.Person")

attention, the string here include the name space




convert dictionary to model

it’s easy to convert dictionary to model, I already did the cascade im not going to repeat the details:

let stu1 = Student1.parse(dict: Student1Dict)
let stus = Student7.parses(arr: Student7DictArr)

If you property type is Bool, you may encounter UndefinedKey, which is due to Swift's own reasons, you just need to implement the following methods manually resolved:

override func setValue(value: AnyObject?, forUndefinedKey key: String) {
    self.isVip = (value as! Int) != 0
}

parse Plist file ,Please don't take the suffix

let author = Author.parsePlist("Author")




convert model to dictionary

it’s easy to convert model to dictionary, I already did the cascade im not going to repeat the details:

let dict = person3.toDict()




One key archive

Archive has done the cascade and easy for using. It also encapsulates the operation of Caches folder, directly save in Caches folder.

Archive: the name of single model could be empty, but the name of array can’t be empty. Back to the position of archiving.

let path1 =  Book2.save(obj: book2, name: nil)
let path2 =  Book3.save(obj: bookArr, name: "book3")

Read data: please use the same key, if save name wich not used as nill, use nil for read data.

let arcBook2 = Book2.read(name: nil)
let arr = Book3.read(name: "book3")

delete data:

Book1.delete(name: nil)

additional function: ignore archive field

/**  ignore archive field  */

//ignore archive property named 'icon'
func ignoreCodingPropertiesForCoding() -> [String]? {
    return ["icon"]
}
You might also like...
Comments
  • do not check hardcoded for _TtC to _TtCC

    do not check hardcoded for _TtC to _TtCC

    do not check hardcoded for _TtC to _TtCC There could be other types than Class. You could have a _TtCPC Where P is for Protocol You can also have functions in there. So just check for the prefix _T Then I think you always will have a t which stands for target of bundle name. Then continue reading until you hit a number. The number of characters you have read will be the same as the number of number and string groups that will be after that.

    If you have a moment, then later today or tomorrow morning I will add a version of that to https://github.com/evermeer/EVReflection It's almost done. Im now bug fixing plus creating unit tests for it.

    opened by evermeer 2
  • 归档跟解归档会崩

    归档跟解归档会崩

    你好,发现一个bug,归档跟解归档会崩。 例子 SubReflectAClass : Reflect { number : String = "" bClass : SubReflectBClass = SubReflectBClass() }

    SubReflectBClass : Reflect { ID : String = "" name : String = "" } 解归档的时候,bClass里面的属性会显示unable to read data 。 报错是 read memory from 0x6***** failed ( 0 of 8 bytes read ) >

    opened by LamMeya 1
  • When I use it with Swift4.0,it crashed with this message:

    When I use it with Swift4.0,it crashed with this message:

    2017-07-04 14:17:52.193738+0800 Reflect[4302:1322488] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<Reflect.Student2 0x1c02c35d0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key name.' *** First throw call stack: (0x183791858 0x181f68528 0x183791520 0x18424390c 0x10087eb08 0x10088236c 0x10088fee4 0x10087cd24 0x100877c10 0x1008834dc 0x100883570 0x189f9f6bc 0x18a047c0c 0x18a04709c 0x18a046a84 0x18a0465f0 0x18a0464f8 0x189f9ca64 0x186f756e4 0x186f7979c 0x186eec3f8 0x186f11e44 0x18a218500 0x1837383fc 0x183737bf0 0x183735918 0x183654280 0x185165f94 0x18a0030f0 0x100890524 0x182445e40) libc++abi.dylib: terminating with uncaught exception of type NSException

    I

    opened by ceeyang 1
  • Fix broken headings in Markdown files

    Fix broken headings in Markdown files

    GitHub changed the way Markdown headings are parsed, so this change fixes it.

    See bryant1410/readmesfix for more information.

    Tackles bryant1410/readmesfix#1

    opened by bryant1410 0
Owner
时点软件冯成林
成都时点软件开发有限公司 冯成林
时点软件冯成林
Auto reflection tool from JSON to Model, user friendly JSON encoder / decoder, aims to never die

JSONNeverDie is an auto reflection tool from JSON to Model, a user friendly JSON encoder / decoder, aims to never die. Also JSONNeverDie is a very imp

John Lui 454 Oct 30, 2022
ZIP Foundation is a library to create, read and modify ZIP archive files.

ZIP Foundation is a library to create, read and modify ZIP archive files. It is written in Swift and based on Apple's libcompression for high performa

Thomas Zoechling 1.9k Dec 27, 2022
Create xcframework zip archive for Swift binary package.

xczip xczip - create xcframework zip archive for swift binary package. Creates an xcframework archive with a stable checksum that does not change when

Dmitriy Borovikov 0 Jan 8, 2022
Reflection based (Dictionary, CKRecord, NSManagedObject, Realm, JSON and XML) object mapping with extensions for Alamofire and Moya with RxSwift or ReactiveSwift

EVReflection General information At this moment the master branch is tested with Swift 4.2 and 5.0 beta If you want to continue using EVReflection in

Edwin Vermeer 964 Dec 14, 2022
JSONNeverDie - Auto reflection tool from JSON to Model, user friendly JSON encoder / decoder, aims to never die

JSONNeverDie is an auto reflection tool from JSON to Model, a user friendly JSON encoder / decoder, aims to never die. Also JSONNeverDie is a very important part of Pitaya.

John Lui 454 Oct 30, 2022
Reflection based (Dictionary, CKRecord, NSManagedObject, Realm, JSON and XML) object mapping with extensions for Alamofire and Moya with RxSwift or ReactiveSwift

EVReflection General information At this moment the master branch is tested with Swift 4.2 and 5.0 beta If you want to continue using EVReflection in

Edwin Vermeer 964 Dec 14, 2022
Auto reflection tool from JSON to Model, user friendly JSON encoder / decoder, aims to never die

JSONNeverDie is an auto reflection tool from JSON to Model, a user friendly JSON encoder / decoder, aims to never die. Also JSONNeverDie is a very imp

John Lui 454 Oct 30, 2022
Reflection for enumerations in Objective-C.

ReflectableEnum A macro and a set of functions introducing reflection for enumerations in Objective-C. Features: get a string value for an enumeration

Arek Holko 333 Nov 17, 2022
OpenFocusTimer - Pomodoro timer with categories, reflection, history & statistics

OpenFocusTimer Pomodoro timer with categories, reflection, history & statistics.

Cihat Gündüz 18 Dec 13, 2022