Compare commits
5 Commits
master
...
mtlmanaged
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a0425ff397 | ||
|
|
d5d3511d53 | ||
|
|
4af1af680b | ||
|
|
1337b9d240 | ||
|
|
af3f2b0e1a |
2
.gitignore
vendored
2
.gitignore
vendored
@ -17,5 +17,3 @@ profile
|
||||
.idea/
|
||||
# Desktop Servies
|
||||
.DS_Store
|
||||
|
||||
Carthage/Build
|
||||
|
||||
20
.gitmodules
vendored
20
.gitmodules
vendored
@ -1,13 +1,9 @@
|
||||
[submodule "Carthage.checkout/Nimble"]
|
||||
path = Carthage/Checkouts/Nimble
|
||||
url = https://github.com/Quick/Nimble.git
|
||||
[submodule "Carthage.checkout/Quick"]
|
||||
path = Carthage/Checkouts/Quick
|
||||
url = https://github.com/Quick/Quick.git
|
||||
[submodule "Carthage.checkout/xcconfigs"]
|
||||
path = Carthage/Checkouts/xcconfigs
|
||||
[submodule "MantleTests/expecta"]
|
||||
path = MantleTests/expecta
|
||||
url = https://github.com/github/expecta.git
|
||||
[submodule "MantleTests/specta"]
|
||||
path = MantleTests/specta
|
||||
url = https://github.com/github/specta.git
|
||||
[submodule "Configuration"]
|
||||
path = Configuration
|
||||
url = https://github.com/jspahrsummers/xcconfigs.git
|
||||
[submodule "Carthage/Checkouts/Nimble"]
|
||||
url = https://github.com/Quick/Nimble.git
|
||||
[submodule "Carthage/Checkouts/Quick"]
|
||||
url = https://github.com/Quick/Quick.git
|
||||
|
||||
67
.travis.yml
67
.travis.yml
@ -1,70 +1,5 @@
|
||||
language: objective-c
|
||||
xcode_workspace: Mantle.xcworkspace
|
||||
git:
|
||||
submodules: false
|
||||
before_install:
|
||||
- git submodule update --init --recursive
|
||||
script:
|
||||
- set -o pipefail
|
||||
- xcodebuild $XCODE_ACTION
|
||||
-workspace "$TRAVIS_XCODE_WORKSPACE"
|
||||
-scheme "$TRAVIS_XCODE_SCHEME"
|
||||
-sdk "$XCODE_SDK"
|
||||
-destination "$XCODE_DESTINATION"
|
||||
RUN_CLANG_STATIC_ANALYZER=NO
|
||||
| xcpretty
|
||||
matrix:
|
||||
include:
|
||||
# Xcode 8
|
||||
- xcode_scheme: "Mantle Mac"
|
||||
osx_image: xcode8.3
|
||||
env:
|
||||
- XCODE_ACTION=test
|
||||
- XCODE_SDK=macosx
|
||||
- XCODE_DESTINATION="arch=x86_64"
|
||||
- xcode_scheme: "Mantle iOS"
|
||||
osx_image: xcode8.3
|
||||
env:
|
||||
- XCODE_ACTION=test
|
||||
- XCODE_SDK=iphonesimulator
|
||||
- XCODE_DESTINATION="name=iPhone 7"
|
||||
- xcode_scheme: "Mantle-tvOS"
|
||||
osx_image: xcode8.3
|
||||
env:
|
||||
- XCODE_ACTION=test
|
||||
- XCODE_SDK=appletvsimulator
|
||||
- XCODE_DESTINATION="name=Apple TV 1080p"
|
||||
- xcode_scheme: "Mantle-watchOS"
|
||||
osx_image: xcode8.3
|
||||
env:
|
||||
- XCODE_ACTION=build
|
||||
- XCODE_SDK=watchsimulator
|
||||
- XCODE_DESTINATION="name=Apple Watch - 38mm"
|
||||
# Xcode 9
|
||||
- xcode_scheme: "Mantle Mac"
|
||||
osx_image: xcode9
|
||||
env:
|
||||
- XCODE_ACTION=test
|
||||
- XCODE_SDK=macosx
|
||||
- XCODE_DESTINATION="arch=x86_64"
|
||||
- xcode_scheme: "Mantle iOS"
|
||||
osx_image: xcode9
|
||||
env:
|
||||
- XCODE_ACTION=test
|
||||
- XCODE_SDK=iphonesimulator
|
||||
- XCODE_DESTINATION="name=iPhone 7"
|
||||
- xcode_scheme: "Mantle-tvOS"
|
||||
osx_image: xcode9
|
||||
env:
|
||||
- XCODE_ACTION=test
|
||||
- XCODE_SDK=appletvsimulator
|
||||
- XCODE_DESTINATION="name=Apple TV 1080p"
|
||||
- xcode_scheme: "Mantle-watchOS"
|
||||
osx_image: xcode9
|
||||
env:
|
||||
- XCODE_ACTION=build
|
||||
- XCODE_SDK=watchsimulator
|
||||
- XCODE_DESTINATION="name=Apple Watch - 38mm"
|
||||
script: script/cibuild
|
||||
notifications:
|
||||
email: false
|
||||
campfire:
|
||||
|
||||
188
CHANGELOG.md
188
CHANGELOG.md
@ -1,188 +0,0 @@
|
||||
# 2.0
|
||||
|
||||
This release of Mantle contains major breaking changes that we were unable to
|
||||
make after freezing the 1.0 API.
|
||||
|
||||
The changes in 2.0 focus on simplifying concepts and increasing flexibility in
|
||||
the framework.
|
||||
|
||||
For a complete list of the changes made in Mantle 2.0, see [the
|
||||
milestone](https://github.com/Mantle/Mantle/issues?q=milestone%3A2.0+is%3Aclosed).
|
||||
|
||||
**[Breaking changes](#breaking-changes)**
|
||||
|
||||
1. [Explicit JSON key paths](#explicit-json-key-paths)
|
||||
1. [Predefined transformers now part of JSON adapter](#predefined-transformers-now-part-of-json-adapter)
|
||||
1. [Core Data adapter now separate](#core-data-adapter-now-separate)
|
||||
1. [Managed object transformers reversed](#managed-object-transformers-reversed)
|
||||
1. [OS X 10.9 and iOS 8](#os-x-109-and-ios-8)
|
||||
1. [JSON key paths can only traverse objects](#json-key-paths-can-only-traverse-objects)
|
||||
|
||||
**[Additions and improvements](#additions-and-improvements)**
|
||||
|
||||
1. [MTLModel protocol](#mtlmodel-protocol)
|
||||
1. [Error handling for value transformers](#error-handling-for-value-transformers)
|
||||
1. [Storage behaviors for properties](#storage-behaviors-for-properties)
|
||||
1. [Type checking during JSON parsing](#type-checking-during-json-parsing)
|
||||
1. [Mapping multiple JSON fields to a single property](#mapping-multiple-json-fields-to-a-single-property)
|
||||
|
||||
## Breaking changes
|
||||
|
||||
### Explicit JSON key paths
|
||||
|
||||
`+JSONKeyPathsByPropertyKey` will [no
|
||||
longer](https://github.com/Mantle/Mantle/pull/170) infer your property mappings
|
||||
automatically.
|
||||
|
||||
Instead, you must explicitly specify every property that should
|
||||
be mapped, and any properties omitted will not be considered for JSON
|
||||
serialization or deserialization.
|
||||
|
||||
For convenience, you can use `+[NSDictionary mtl_identityPropertyMapWithModel:]`
|
||||
to automatically create a one-to-one mapping that matches the previous default
|
||||
behavior.
|
||||
|
||||
**To update:**
|
||||
|
||||
* Explicitly declare any property mappings in `+JSONKeyPathsByPropertyKey`
|
||||
that were previously implicit.
|
||||
* Optionally use `+[NSDictionary mtl_identityPropertyMapWithModel:]` for an
|
||||
initial property map.
|
||||
|
||||
### Predefined transformers now part of JSON adapter
|
||||
|
||||
The `+mtl_JSONDictionaryTransformerWithModelClass:` and
|
||||
`+mtl_JSONArrayWithModelClass:` methods [have
|
||||
moved](https://github.com/Mantle/Mantle/pull/474) to `MTLJSONAdapter`.
|
||||
|
||||
This allows custom JSON adapter subclasses to substitute their own transformers
|
||||
with additional logic, and moves the transformers closer to their actual point
|
||||
of use.
|
||||
|
||||
**To update:**
|
||||
|
||||
* Replace occurrences of `+[NSValueTransformer
|
||||
mtl_JSONDictionaryTransformerWithModelClass:]` with `+[MTLJSONAdapter
|
||||
dictionaryTransformerWithModelClass:]`
|
||||
* Replace occurrences of `+[NSValueTransformer
|
||||
mtl_JSONArrayTransformerWithModelClass:]` with `+[MTLJSONAdapter
|
||||
arrayTransformerWithModelClass:]`
|
||||
|
||||
### Core Data adapter now separate
|
||||
|
||||
The `MTLManagedObjectAdapter` class, used for converting to and from Core Data
|
||||
objects, has been moved to [its own
|
||||
framework](https://github.com/Mantle/MTLManagedObjectAdapter). This better
|
||||
indicates its “semi-official” status, as it gets less attention than the core
|
||||
Mantle features.
|
||||
|
||||
**To update:**
|
||||
|
||||
* Import the
|
||||
[MTLManagedObjectAdapter](https://github.com/Mantle/MTLManagedObjectAdapter)
|
||||
framework into your project.
|
||||
|
||||
### Managed object transformers reversed
|
||||
|
||||
In addition to being [a separate framework](#core-data-adapter-now-separate),
|
||||
the behavior of `MTLManagedObjectAdapter` has changed as well—specifically, the
|
||||
direction of managed object attribute transformers has been flipped.
|
||||
|
||||
Managed object transformers now convert _from_ managed object attributes _to_
|
||||
model properties in the forward direction. In the reverse direction, they
|
||||
convert from properties to managed object attributes.
|
||||
|
||||
**To update:**
|
||||
|
||||
* Swap the forward and reverse transformation logic of any custom managed
|
||||
object transformers, or use `-mtl_invertedTransformer` to do it
|
||||
automatically.
|
||||
|
||||
### OS X 10.9 and iOS 8
|
||||
|
||||
Mantle now requires OS X 10.9+ or iOS 8+, for the use of Swift and dynamic
|
||||
frameworks.
|
||||
|
||||
**To update:**
|
||||
|
||||
* Increase your project’s deployment target to at least OS X 10.9 or iOS 8.
|
||||
|
||||
### JSON key paths can only traverse objects
|
||||
|
||||
Every element of a JSON key path specified in `+JSONKeyPathsByPropertyKey` [must
|
||||
now refer to an object](https://github.com/Mantle/Mantle/pull/275) (dictionary).
|
||||
|
||||
It was [previously possible](https://github.com/Mantle/Mantle/issues/257) to use
|
||||
an array as a key path element, but this was unintended behavior, and is now
|
||||
explicitly disallowed.
|
||||
|
||||
**To update:**
|
||||
|
||||
* If you were using an array as an element in a key path, change the key path
|
||||
to end at the array, and [update your JSON transformer](https://github.com/Mantle/Mantle/issues/257#issuecomment-36846503)
|
||||
to handle the nested elements instead.
|
||||
|
||||
## Additions and improvements
|
||||
|
||||
### MTLModel protocol
|
||||
|
||||
The [new `<MTLModel>` protocol](https://github.com/Mantle/Mantle/pull/219) represents the basic behaviors expected from any
|
||||
model object, and can be used instead of the `MTLModel` class when inheritance
|
||||
is impossible, or to create more generic APIs.
|
||||
|
||||
For example, `<MTLModel>` conformance can be added to the objects from other
|
||||
persistence frameworks in order to use those objects in conjunction with
|
||||
Mantle’s adapters.
|
||||
|
||||
Accordingly, `MTLJSONAdapter` has been updated to only depend on `<MTLModel>`
|
||||
conformance, and no longer requires a `MTLModel` subclass in order to serialize
|
||||
or deserialize from JSON.
|
||||
|
||||
### Error handling for value transformers
|
||||
|
||||
The [new `<MTLTransformerErrorHandling>`
|
||||
protocol](https://github.com/Mantle/Mantle/pull/153) can be used to add error
|
||||
reporting behaviors to any `NSValueTransformer`.
|
||||
|
||||
`MTLValueTransformer` has been updated to take advantage of the new interface,
|
||||
with the following new methods that provide error information:
|
||||
|
||||
* `+transformerUsingForwardBlock:`
|
||||
* `+transformerUsingReversibleBlock:`
|
||||
* `+transformerUsingForwardBlock:reverseBlock:`
|
||||
|
||||
Similarly, the predefined transformers that Mantle provides now provide error
|
||||
information upon failure as well.
|
||||
|
||||
### Storage behaviors for properties
|
||||
|
||||
The [new `+storageBehaviorForPropertyWithKey:`
|
||||
method](https://github.com/Mantle/Mantle/pull/210) can be used to redefine the
|
||||
default behavior of methods like `-dictionaryValue`, `-isEqual:`,
|
||||
`-description`, and `-copy` all at once.
|
||||
|
||||
Properties which have been omitted from `+propertyKeys` by default will continue
|
||||
to be omitted under the new API, with a default behavior of
|
||||
`MTLPropertyStorageNone`.
|
||||
|
||||
### Type checking during JSON parsing
|
||||
|
||||
`MTLJSONAdapter` now [implicitly
|
||||
validates](https://github.com/Mantle/Mantle/pull/251) the type of values
|
||||
assigned to your `<MTLModel>` objects during JSON parsing.
|
||||
|
||||
This can be prevent errors like an `NSString` being assigned to a `BOOL`
|
||||
property.
|
||||
|
||||
This is only a simple safety check, though, and cannot catch every kind of
|
||||
error! Continue to verify that your types align ahead of time.
|
||||
|
||||
### Mapping multiple JSON fields to a single property
|
||||
|
||||
`MTLJSONAdapter` can now map multiple fields to a single property, and
|
||||
vice-versa. Specify an array of keypaths for the property when implementing
|
||||
`+JSONKeyPathsByPropertyKey` rather than an `NSString`.
|
||||
|
||||
The default behaviour is to set the property to a dictionary of values for the
|
||||
specified keypaths. If you specify a value transformer for the given property
|
||||
key, this transformer will receive an `NSDictionary` of values.
|
||||
@ -1,3 +0,0 @@
|
||||
github "jspahrsummers/xcconfigs" "1ef9763"
|
||||
github "Quick/Quick" ~> 1.1.0
|
||||
github "Quick/Nimble" ~> 7.0.1
|
||||
@ -1,3 +0,0 @@
|
||||
github "Quick/Nimble" "v7.0.1"
|
||||
github "Quick/Quick" "v1.1.0"
|
||||
github "jspahrsummers/xcconfigs" "1ef97639ffbe041da0b1392b2114fa19b922a7a1"
|
||||
1
Carthage/Checkouts/Nimble
vendored
1
Carthage/Checkouts/Nimble
vendored
@ -1 +0,0 @@
|
||||
Subproject commit 39b67002306fda9de4c9fd1290a6295f97edd09e
|
||||
1
Carthage/Checkouts/Quick
vendored
1
Carthage/Checkouts/Quick
vendored
@ -1 +0,0 @@
|
||||
Subproject commit e4fa1e85c0305ba4e0866f25812d3fa398f3a048
|
||||
1
Carthage/Checkouts/xcconfigs
vendored
1
Carthage/Checkouts/xcconfigs
vendored
@ -1 +0,0 @@
|
||||
Subproject commit 1ef97639ffbe041da0b1392b2114fa19b922a7a1
|
||||
1
Configuration
Submodule
1
Configuration
Submodule
@ -0,0 +1 @@
|
||||
Subproject commit 827f7e1b84b19f3783bb02d0506cd939406f7992
|
||||
@ -1,4 +1,4 @@
|
||||
**Copyright (c) GitHub, Inc.**
|
||||
**Copyright (c) 2012 - 2014, GitHub, Inc.**
|
||||
**All rights reserved.**
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -1,142 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0800"
|
||||
version = "2.0">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "NO"
|
||||
buildImplicitDependencies = "NO">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "D042FC3B15F72B23004E8054"
|
||||
BuildableName = "Mantle.framework"
|
||||
BlueprintName = "Mantle-Mac"
|
||||
ReferencedContainer = "container:Mantle.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "NO"
|
||||
buildForProfiling = "NO"
|
||||
buildForArchiving = "NO"
|
||||
buildForAnalyzing = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "1F925EAC195C0D6300ED456B"
|
||||
BuildableName = "Nimble.framework"
|
||||
BlueprintName = "Nimble-macOS"
|
||||
ReferencedContainer = "container:Carthage/Checkouts/Nimble/Nimble.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "NO"
|
||||
buildForProfiling = "NO"
|
||||
buildForArchiving = "NO"
|
||||
buildForAnalyzing = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "DAEB6B8D1943873100289F44"
|
||||
BuildableName = "Quick.framework"
|
||||
BlueprintName = "Quick-macOS"
|
||||
ReferencedContainer = "container:Carthage/Checkouts/Quick/Quick.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "NO"
|
||||
buildForProfiling = "NO"
|
||||
buildForArchiving = "NO"
|
||||
buildForAnalyzing = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "D042FC5315F72B23004E8054"
|
||||
BuildableName = "Mantle-MacTests.xctest"
|
||||
BlueprintName = "Mantle-MacTests"
|
||||
ReferencedContainer = "container:Mantle.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Release"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "D042FC5315F72B23004E8054"
|
||||
BuildableName = "Mantle-MacTests.xctest"
|
||||
BlueprintName = "Mantle-MacTests"
|
||||
ReferencedContainer = "container:Mantle.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "D042FC3B15F72B23004E8054"
|
||||
BuildableName = "Mantle.framework"
|
||||
BlueprintName = "Mantle-Mac"
|
||||
ReferencedContainer = "container:Mantle.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = ""
|
||||
selectedLauncherIdentifier = "Xcode.IDEFoundation.Launcher.PosixSpawn"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugXPCServices = "NO"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "D042FC3B15F72B23004E8054"
|
||||
BuildableName = "Mantle.framework"
|
||||
BlueprintName = "Mantle-Mac"
|
||||
ReferencedContainer = "container:Mantle.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Profile"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "D042FC3B15F72B23004E8054"
|
||||
BuildableName = "Mantle.framework"
|
||||
BlueprintName = "Mantle-Mac"
|
||||
ReferencedContainer = "container:Mantle.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@ -1,141 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0800"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "NO"
|
||||
buildImplicitDependencies = "NO">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "D0E9C35619F6DB38000D427D"
|
||||
BuildableName = "Mantle.framework"
|
||||
BlueprintName = "Mantle-iOS"
|
||||
ReferencedContainer = "container:Mantle.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "NO"
|
||||
buildForProfiling = "NO"
|
||||
buildForArchiving = "NO"
|
||||
buildForAnalyzing = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "1F1A74281940169200FFFC47"
|
||||
BuildableName = "Nimble.framework"
|
||||
BlueprintName = "Nimble-iOS"
|
||||
ReferencedContainer = "container:Carthage/Checkouts/Nimble/Nimble.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "NO"
|
||||
buildForProfiling = "NO"
|
||||
buildForArchiving = "NO"
|
||||
buildForAnalyzing = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "5A5D117B19473F2100F6D13D"
|
||||
BuildableName = "Quick.framework"
|
||||
BlueprintName = "Quick-iOS"
|
||||
ReferencedContainer = "container:Carthage/Checkouts/Quick/Quick.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "NO"
|
||||
buildForProfiling = "NO"
|
||||
buildForArchiving = "NO"
|
||||
buildForAnalyzing = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "D0E9C36019F6DB38000D427D"
|
||||
BuildableName = "Mantle-iOSTests.xctest"
|
||||
BlueprintName = "Mantle-iOSTests"
|
||||
ReferencedContainer = "container:Mantle.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "D0E9C36019F6DB38000D427D"
|
||||
BuildableName = "Mantle-iOSTests.xctest"
|
||||
BlueprintName = "Mantle-iOSTests"
|
||||
ReferencedContainer = "container:Mantle.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "D0E9C35619F6DB38000D427D"
|
||||
BuildableName = "Mantle.framework"
|
||||
BlueprintName = "Mantle-iOS"
|
||||
ReferencedContainer = "container:Mantle.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "D0E9C35619F6DB38000D427D"
|
||||
BuildableName = "Mantle.framework"
|
||||
BlueprintName = "Mantle-iOS"
|
||||
ReferencedContainer = "container:Mantle.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "D0E9C35619F6DB38000D427D"
|
||||
BuildableName = "Mantle.framework"
|
||||
BlueprintName = "Mantle-iOS"
|
||||
ReferencedContainer = "container:Mantle.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@ -1,10 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0800"
|
||||
LastUpgradeVersion = "0510"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "NO"
|
||||
buildImplicitDependencies = "NO">
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
@ -14,61 +14,40 @@
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "CD7C6D881D33ACCC002EC294"
|
||||
BuildableName = "Mantle.framework"
|
||||
BlueprintName = "Mantle-watchOS"
|
||||
BlueprintIdentifier = "D0A56B451804B04900A84EDC"
|
||||
BuildableName = "libMantle-Mac.a"
|
||||
BlueprintName = "Mantle-Mac"
|
||||
ReferencedContainer = "container:Mantle.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
buildConfiguration = "Debug">
|
||||
<Testables>
|
||||
</Testables>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
buildConfiguration = "Debug"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "CD7C6D881D33ACCC002EC294"
|
||||
BuildableName = "Mantle.framework"
|
||||
BlueprintName = "Mantle-watchOS"
|
||||
ReferencedContainer = "container:Mantle.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
buildConfiguration = "Release"
|
||||
debugDocumentVersioning = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "CD7C6D881D33ACCC002EC294"
|
||||
BuildableName = "Mantle.framework"
|
||||
BlueprintName = "Mantle-watchOS"
|
||||
ReferencedContainer = "container:Mantle.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
83
Mantle.xcodeproj/xcshareddata/xcschemes/Mantle-iOS.xcscheme
Normal file
83
Mantle.xcodeproj/xcshareddata/xcschemes/Mantle-iOS.xcscheme
Normal file
@ -0,0 +1,83 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0510"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "D042FC7815F72BC7004E8054"
|
||||
BuildableName = "libMantle-iOS.a"
|
||||
BlueprintName = "Mantle-iOS"
|
||||
ReferencedContainer = "container:Mantle.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "NO"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "D042FC8615F72BC7004E8054"
|
||||
BuildableName = "Mantle-iOS Tests.octest"
|
||||
BlueprintName = "Mantle-iOS Tests"
|
||||
ReferencedContainer = "container:Mantle.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
buildConfiguration = "Debug">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "D042FC8615F72BC7004E8054"
|
||||
BuildableName = "Mantle-iOS Tests.octest"
|
||||
BlueprintName = "Mantle-iOS Tests"
|
||||
ReferencedContainer = "container:Mantle.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
buildConfiguration = "Debug"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
allowLocationSimulation = "YES">
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
buildConfiguration = "Profile"
|
||||
debugDocumentVersioning = "YES">
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@ -1,141 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0800"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "NO"
|
||||
buildImplicitDependencies = "NO">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "CDEEABA71D33FC5100240A4B"
|
||||
BuildableName = "Mantle.framework"
|
||||
BlueprintName = "Mantle-tvOS"
|
||||
ReferencedContainer = "container:Mantle.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "NO"
|
||||
buildForProfiling = "NO"
|
||||
buildForArchiving = "NO"
|
||||
buildForAnalyzing = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "1F5DF1541BDCA0CE00C3A531"
|
||||
BuildableName = "Nimble.framework"
|
||||
BlueprintName = "Nimble-tvOS"
|
||||
ReferencedContainer = "container:Carthage/Checkouts/Nimble/Nimble.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "NO"
|
||||
buildForProfiling = "NO"
|
||||
buildForArchiving = "NO"
|
||||
buildForAnalyzing = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "1F118CD41BDCA4AB005013A2"
|
||||
BuildableName = "Quick.framework"
|
||||
BlueprintName = "Quick-tvOS"
|
||||
ReferencedContainer = "container:Carthage/Checkouts/Quick/Quick.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "NO"
|
||||
buildForProfiling = "NO"
|
||||
buildForArchiving = "NO"
|
||||
buildForAnalyzing = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "CDEEABD31D33FC7900240A4B"
|
||||
BuildableName = "Mantle-tvOSTests.xctest"
|
||||
BlueprintName = "Mantle-tvOSTests"
|
||||
ReferencedContainer = "container:Mantle.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "CDEEABD31D33FC7900240A4B"
|
||||
BuildableName = "Mantle-tvOSTests.xctest"
|
||||
BlueprintName = "Mantle-tvOSTests"
|
||||
ReferencedContainer = "container:Mantle.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "CDEEABA71D33FC5100240A4B"
|
||||
BuildableName = "Mantle.framework"
|
||||
BlueprintName = "Mantle-tvOS"
|
||||
ReferencedContainer = "container:Mantle.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "CDEEABA71D33FC5100240A4B"
|
||||
BuildableName = "Mantle.framework"
|
||||
BlueprintName = "Mantle-tvOS"
|
||||
ReferencedContainer = "container:Mantle.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "CDEEABA71D33FC5100240A4B"
|
||||
BuildableName = "Mantle.framework"
|
||||
BlueprintName = "Mantle-tvOS"
|
||||
ReferencedContainer = "container:Mantle.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
83
Mantle.xcodeproj/xcshareddata/xcschemes/Mantle.xcscheme
Normal file
83
Mantle.xcodeproj/xcshareddata/xcschemes/Mantle.xcscheme
Normal file
@ -0,0 +1,83 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "0510"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "D042FC3B15F72B23004E8054"
|
||||
BuildableName = "Mantle.framework"
|
||||
BlueprintName = "Mantle"
|
||||
ReferencedContainer = "container:Mantle.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "NO"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "D042FC5315F72B23004E8054"
|
||||
BuildableName = "Mantle Tests.octest"
|
||||
BlueprintName = "Mantle Tests"
|
||||
ReferencedContainer = "container:Mantle.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
buildConfiguration = "Debug">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "D042FC5315F72B23004E8054"
|
||||
BuildableName = "Mantle Tests.octest"
|
||||
BlueprintName = "Mantle Tests"
|
||||
ReferencedContainer = "container:Mantle.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
buildConfiguration = "Debug"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
allowLocationSimulation = "YES">
|
||||
<AdditionalOptions>
|
||||
</AdditionalOptions>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
buildConfiguration = "Profile"
|
||||
debugDocumentVersioning = "YES">
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
4
Mantle.xcworkspace/contents.xcworkspacedata
generated
4
Mantle.xcworkspace/contents.xcworkspacedata
generated
@ -5,9 +5,9 @@
|
||||
location = "group:Mantle.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Carthage/Checkouts/Quick/Quick.xcodeproj">
|
||||
location = "group:MantleTests/expecta/Expecta.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Carthage/Checkouts/Nimble/Nimble.xcodeproj">
|
||||
location = "group:MantleTests/specta/Specta.xcodeproj">
|
||||
</FileRef>
|
||||
</Workspace>
|
||||
|
||||
@ -9,263 +9,226 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
@protocol MTLModel;
|
||||
@protocol MTLTransformerErrorHandling;
|
||||
|
||||
/// A MTLModel object that supports being parsed from and serialized to JSON.
|
||||
// A MTLModel object that supports being parsed from and serialized to JSON.
|
||||
@protocol MTLJSONSerializing <MTLModel>
|
||||
@required
|
||||
|
||||
/// Specifies how to map property keys to different key paths in JSON.
|
||||
///
|
||||
/// Subclasses overriding this method should combine their values with those of
|
||||
/// `super`.
|
||||
///
|
||||
/// Values in the dictionary can either be key paths in the JSON representation
|
||||
/// of the receiver or an array of such key paths. If an array is used, the
|
||||
/// deserialized value will be a dictionary containing all of the keys in the
|
||||
/// array.
|
||||
///
|
||||
/// Any keys omitted will not participate in JSON serialization.
|
||||
///
|
||||
/// Examples
|
||||
///
|
||||
/// + (NSDictionary *)JSONKeyPathsByPropertyKey {
|
||||
/// return @{
|
||||
/// @"name": @"POI.name",
|
||||
/// @"point": @[ @"latitude", @"longitude" ],
|
||||
/// @"starred": @"starred"
|
||||
/// };
|
||||
/// }
|
||||
///
|
||||
/// This will map the `starred` property to `JSONDictionary[@"starred"]`, `name`
|
||||
/// to `JSONDictionary[@"POI"][@"name"]` and `point` to a dictionary equivalent
|
||||
/// to:
|
||||
///
|
||||
/// @{
|
||||
/// @"latitude": JSONDictionary[@"latitude"],
|
||||
/// @"longitude": JSONDictionary[@"longitude"]
|
||||
/// }
|
||||
///
|
||||
/// Returns a dictionary mapping property keys to one or multiple JSON key paths
|
||||
/// (as strings or arrays of strings).
|
||||
// Specifies how to map property keys to different key paths in JSON.
|
||||
//
|
||||
// Subclasses overriding this method should combine their values with those of
|
||||
// `super`.
|
||||
//
|
||||
// Values in the dictionary can either be key paths in the JSON representation
|
||||
// of the receiver or an array of such key paths. If an array is used, the
|
||||
// deserialized value will be a dictionary containing all of the keys in the
|
||||
// array.
|
||||
//
|
||||
// Any keys omitted will not participate in JSON serialization.
|
||||
//
|
||||
// Examples
|
||||
//
|
||||
// + (NSDictionary *)JSONKeyPathsByPropertyKey {
|
||||
// return @{
|
||||
// @"name": @"POI.name",
|
||||
// @"point": @[ @"latitude", @"longitude" ],
|
||||
// @"starred": @"starred"
|
||||
// };
|
||||
// }
|
||||
//
|
||||
// This will map the `starred` property to `JSONDictionary[@"starred"]`, `name`
|
||||
// to `JSONDictionary[@"POI"][@"name"]` and `point` to a dictionary equivalent
|
||||
// to:
|
||||
//
|
||||
// @{
|
||||
// @"latitude": JSONDictionary[@"latitude"],
|
||||
// @"longitude": JSONDictionary[@"longitude"]
|
||||
// }
|
||||
//
|
||||
// Returns a dictionary mapping property keys to one or multiple JSON key paths
|
||||
// (as strings or arrays of strings).
|
||||
+ (NSDictionary *)JSONKeyPathsByPropertyKey;
|
||||
|
||||
@optional
|
||||
|
||||
/// Specifies how to convert a JSON value to the given property key. If
|
||||
/// reversible, the transformer will also be used to convert the property value
|
||||
/// back to JSON.
|
||||
///
|
||||
/// If the receiver implements a `+<key>JSONTransformer` method, MTLJSONAdapter
|
||||
/// will use the result of that method instead.
|
||||
///
|
||||
/// Returns a value transformer, or nil if no transformation should be performed.
|
||||
// Specifies how to convert a JSON value to the given property key. If
|
||||
// reversible, the transformer will also be used to convert the property value
|
||||
// back to JSON.
|
||||
//
|
||||
// If the receiver implements a `-<key>JSONTransformer` method, MTLJSONAdapter
|
||||
// will use the result of that method instead.
|
||||
//
|
||||
// Returns a value transformer, or nil if no transformation should be performed.
|
||||
+ (NSValueTransformer *)JSONTransformerForKey:(NSString *)key;
|
||||
|
||||
/// Overridden to parse the receiver as a different class, based on information
|
||||
/// in the provided dictionary.
|
||||
///
|
||||
/// This is mostly useful for class clusters, where the abstract base class would
|
||||
/// be passed into -[MTLJSONAdapter initWithJSONDictionary:modelClass:], but
|
||||
/// a subclass should be instantiated instead.
|
||||
///
|
||||
/// JSONDictionary - The JSON dictionary that will be parsed.
|
||||
///
|
||||
/// Returns the class that should be parsed (which may be the receiver), or nil
|
||||
/// to abort parsing (e.g., if the data is invalid).
|
||||
// Overridden to parse the receiver as a different class, based on information
|
||||
// in the provided dictionary.
|
||||
//
|
||||
// This is mostly useful for class clusters, where the abstract base class would
|
||||
// be passed into -[MTLJSONAdapter initWithJSONDictionary:modelClass:], but
|
||||
// a subclass should be instantiated instead.
|
||||
//
|
||||
// JSONDictionary - The JSON dictionary that will be parsed.
|
||||
//
|
||||
// Returns the class that should be parsed (which may be the receiver), or nil
|
||||
// to abort parsing (e.g., if the data is invalid).
|
||||
+ (Class)classForParsingJSONDictionary:(NSDictionary *)JSONDictionary;
|
||||
|
||||
@end
|
||||
|
||||
/// The domain for errors originating from MTLJSONAdapter.
|
||||
// The domain for errors originating from MTLJSONAdapter.
|
||||
extern NSString * const MTLJSONAdapterErrorDomain;
|
||||
|
||||
/// +classForParsingJSONDictionary: returned nil for the given dictionary.
|
||||
// +classForParsingJSONDictionary: returned nil for the given dictionary.
|
||||
extern const NSInteger MTLJSONAdapterErrorNoClassFound;
|
||||
|
||||
/// The provided JSONDictionary is not valid.
|
||||
// The provided JSONDictionary is not valid.
|
||||
extern const NSInteger MTLJSONAdapterErrorInvalidJSONDictionary;
|
||||
|
||||
/// The model's implementation of +JSONKeyPathsByPropertyKey included a key which
|
||||
/// does not actually exist in +propertyKeys.
|
||||
// The model's implementation of +JSONKeyPathsByPropertyKey included a key which
|
||||
// does not actually exist in +propertyKeys.
|
||||
extern const NSInteger MTLJSONAdapterErrorInvalidJSONMapping;
|
||||
|
||||
/// An exception was thrown and caught.
|
||||
extern const NSInteger MTLJSONAdapterErrorExceptionThrown;
|
||||
|
||||
/// Associated with the NSException that was caught.
|
||||
extern NSString * const MTLJSONAdapterThrownExceptionErrorKey;
|
||||
|
||||
/// Converts a MTLModel object to and from a JSON dictionary.
|
||||
// Converts a MTLModel object to and from a JSON dictionary.
|
||||
@interface MTLJSONAdapter : NSObject
|
||||
|
||||
/// Attempts to parse a JSON dictionary into a model object.
|
||||
///
|
||||
/// modelClass - The MTLModel subclass to attempt to parse from the JSON.
|
||||
/// This class must conform to <MTLJSONSerializing>. This
|
||||
/// argument must not be nil.
|
||||
/// JSONDictionary - A dictionary representing JSON data. This should match the
|
||||
/// format returned by NSJSONSerialization. If this argument is
|
||||
/// nil, the method returns nil.
|
||||
/// error - If not NULL, this may be set to an error that occurs during
|
||||
/// parsing or initializing an instance of `modelClass`.
|
||||
///
|
||||
/// Returns an instance of `modelClass` upon success, or nil if a parsing error
|
||||
/// occurred.
|
||||
// Attempts to parse a JSON dictionary into a model object.
|
||||
//
|
||||
// modelClass - The MTLModel subclass to attempt to parse from the JSON.
|
||||
// This class must conform to <MTLJSONSerializing>. This
|
||||
// argument must not be nil.
|
||||
// JSONDictionary - A dictionary representing JSON data. This should match the
|
||||
// format returned by NSJSONSerialization. If this argument is
|
||||
// nil, the method returns nil.
|
||||
// error - If not NULL, this may be set to an error that occurs during
|
||||
// parsing or initializing an instance of `modelClass`.
|
||||
//
|
||||
// Returns an instance of `modelClass` upon success, or nil if a parsing error
|
||||
// occurred.
|
||||
+ (id)modelOfClass:(Class)modelClass fromJSONDictionary:(NSDictionary *)JSONDictionary error:(NSError **)error;
|
||||
|
||||
/// Attempts to parse an array of JSON dictionary objects into a model objects
|
||||
/// of a specific class.
|
||||
///
|
||||
/// modelClass - The MTLModel subclass to attempt to parse from the JSON. This
|
||||
/// class must conform to <MTLJSONSerializing>. This argument must
|
||||
/// not be nil.
|
||||
/// JSONArray - A array of dictionaries representing JSON data. This should
|
||||
/// match the format returned by NSJSONSerialization. If this
|
||||
/// argument is nil, the method returns nil.
|
||||
/// error - If not NULL, this may be set to an error that occurs during
|
||||
/// parsing or initializing an any of the instances of
|
||||
/// `modelClass`.
|
||||
///
|
||||
/// Returns an array of `modelClass` instances upon success, or nil if a parsing
|
||||
/// error occurred.
|
||||
// Attempts to parse an array of JSON dictionary objects into a model objects
|
||||
// of a specific class.
|
||||
//
|
||||
// modelClass - The MTLModel subclass to attempt to parse from the JSON. This
|
||||
// class must conform to <MTLJSONSerializing>. This argument must
|
||||
// not be nil.
|
||||
// JSONArray - A array of dictionaries representing JSON data. This should
|
||||
// match the format returned by NSJSONSerialization. If this
|
||||
// argument is nil, the method returns nil.
|
||||
// error - If not NULL, this may be set to an error that occurs during
|
||||
// parsing or initializing an any of the instances of
|
||||
// `modelClass`.
|
||||
//
|
||||
// Returns an array of `modelClass` instances upon success, or nil if a parsing
|
||||
// error occurred.
|
||||
+ (NSArray *)modelsOfClass:(Class)modelClass fromJSONArray:(NSArray *)JSONArray error:(NSError **)error;
|
||||
|
||||
/// Converts a model into a JSON representation.
|
||||
///
|
||||
/// model - The model to use for JSON serialization. This argument must not be
|
||||
/// nil.
|
||||
/// error - If not NULL, this may be set to an error that occurs during
|
||||
/// serializing.
|
||||
///
|
||||
/// Returns a JSON dictionary, or nil if a serialization error occurred.
|
||||
// Converts a model into a JSON representation.
|
||||
//
|
||||
// model - The model to use for JSON serialization. This argument must not be
|
||||
// nil.
|
||||
// error - If not NULL, this may be set to an error that occurs during
|
||||
// serializing.
|
||||
//
|
||||
// Returns a JSON dictionary, or nil if a serialization error occurred.
|
||||
+ (NSDictionary *)JSONDictionaryFromModel:(id<MTLJSONSerializing>)model error:(NSError **)error;
|
||||
|
||||
/// Converts a array of models into a JSON representation.
|
||||
///
|
||||
/// models - The array of models to use for JSON serialization. This argument
|
||||
/// must not be nil.
|
||||
/// error - If not NULL, this may be set to an error that occurs during
|
||||
/// serializing.
|
||||
///
|
||||
/// Returns a JSON array, or nil if a serialization error occurred for any
|
||||
/// model.
|
||||
// Converts a array of models into a JSON representation.
|
||||
//
|
||||
// models - The array of models to use for JSON serialization. This argument
|
||||
// must not be nil.
|
||||
// error - If not NULL, this may be set to an error that occurs during
|
||||
// serializing.
|
||||
//
|
||||
// Returns a JSON array, or nil if a serialization error occurred for any
|
||||
// model.
|
||||
+ (NSArray *)JSONArrayFromModels:(NSArray *)models error:(NSError **)error;
|
||||
|
||||
/// Initializes the receiver with a given model class.
|
||||
///
|
||||
/// modelClass - The MTLModel subclass to attempt to parse from the JSON and
|
||||
/// back. This class must conform to <MTLJSONSerializing>. This
|
||||
/// argument must not be nil.
|
||||
///
|
||||
/// Returns an initialized adapter.
|
||||
// Initializes the receiver with a given model class.
|
||||
//
|
||||
// modelClass - The MTLModel subclass to attempt to parse from the JSON and
|
||||
// back. This class must conform to <MTLJSONSerializing>. This
|
||||
// argument must not be nil.
|
||||
//
|
||||
// Returns an initialized adapter.
|
||||
- (id)initWithModelClass:(Class)modelClass;
|
||||
|
||||
/// Deserializes a model from a JSON dictionary.
|
||||
///
|
||||
/// The adapter will call -validate: on the model and consider it an error if the
|
||||
/// validation fails.
|
||||
///
|
||||
/// JSONDictionary - A dictionary representing JSON data. This should match the
|
||||
/// format returned by NSJSONSerialization. This argument must
|
||||
/// not be nil.
|
||||
/// error - If not NULL, this may be set to an error that occurs during
|
||||
/// deserializing or validation.
|
||||
///
|
||||
/// Returns a model object, or nil if a deserialization error occurred or the
|
||||
/// model did not validate successfully.
|
||||
// Deserializes a model from a JSON dictionary.
|
||||
//
|
||||
// JSONDictionary - A dictionary representing JSON data. This should match the
|
||||
// format returned by NSJSONSerialization. This argument must
|
||||
// not be nil.
|
||||
// error - If not NULL, this may be set to an error that occurs during
|
||||
// deserializing.
|
||||
//
|
||||
// Returns a model object, or nil if a deserialization error occurred.
|
||||
- (id)modelFromJSONDictionary:(NSDictionary *)JSONDictionary error:(NSError **)error;
|
||||
|
||||
/// Serializes a model into JSON.
|
||||
///
|
||||
/// model - The model to use for JSON serialization. This argument must not be
|
||||
/// nil.
|
||||
/// error - If not NULL, this may be set to an error that occurs during
|
||||
/// serializing.
|
||||
///
|
||||
/// Returns a model object, or nil if a serialization error occurred.
|
||||
// Serializes a model into JSON.
|
||||
//
|
||||
// model - The model to use for JSON serialization. This argument must not be
|
||||
// nil.
|
||||
// error - If not NULL, this may be set to an error that occurs during
|
||||
// serializing.
|
||||
//
|
||||
// Returns a model object, or nil if a serialization error occurred.
|
||||
- (NSDictionary *)JSONDictionaryFromModel:(id<MTLJSONSerializing>)model error:(NSError **)error;
|
||||
|
||||
/// Filters the property keys used to serialize a given model.
|
||||
///
|
||||
/// propertyKeys - The property keys for which `model` provides a mapping.
|
||||
/// model - The model being serialized.
|
||||
///
|
||||
/// Subclasses may override this method to determine which property keys should
|
||||
/// be used when serializing `model`. For instance, this method can be used to
|
||||
/// create more efficient updates of server-side resources.
|
||||
///
|
||||
/// The default implementation simply returns `propertyKeys`.
|
||||
///
|
||||
/// Returns a subset of propertyKeys that should be serialized for a given
|
||||
/// model.
|
||||
// Filters the property keys used to serialize a given model.
|
||||
//
|
||||
// propertyKeys - The property keys for which `model` provides a mapping.
|
||||
// model - The model being serialized.
|
||||
//
|
||||
// Subclasses may override this method to determine which property keys should
|
||||
// be used when serializing `model`. For instance, this method can be used to
|
||||
// create more efficient updates of server-side resources.
|
||||
//
|
||||
// The default implementation simply returns `propertyKeys`.
|
||||
//
|
||||
// Returns a subset of propertyKeys that should be serialized for a given
|
||||
// model.
|
||||
- (NSSet *)serializablePropertyKeys:(NSSet *)propertyKeys forModel:(id<MTLJSONSerializing>)model;
|
||||
|
||||
/// An optional value transformer that should be used for properties of the given
|
||||
/// class.
|
||||
///
|
||||
/// A value transformer returned by the model's +JSONTransformerForKey: method
|
||||
/// is given precedence over the one returned by this method.
|
||||
///
|
||||
/// The default implementation invokes `+<class>JSONTransformer` on the
|
||||
/// receiver if it's implemented. It supports NSURL conversion through
|
||||
/// +NSURLJSONTransformer.
|
||||
///
|
||||
/// modelClass - The class of the property to serialize. This property must not be
|
||||
/// nil.
|
||||
///
|
||||
/// Returns a value transformer or nil if no transformation should be used.
|
||||
+ (NSValueTransformer *)transformerForModelPropertiesOfClass:(Class)modelClass;
|
||||
// An optional value transformer that should be used for properties of the given
|
||||
// class.
|
||||
//
|
||||
// A value transformer returned by the model's +JSONTransformerForKey: method
|
||||
// is given precedence over the one returned by this method.
|
||||
//
|
||||
// The default implementation invokes `+<class>JSONTransformer` on the
|
||||
// receiver if it's implemented. It supports NSURL conversion through
|
||||
// +NSURLJSONTransformer.
|
||||
//
|
||||
// class - The class of the property to serialize. This property must not be
|
||||
// nil.
|
||||
//
|
||||
// Returns a value transformer or nil if no transformation should be used.
|
||||
+ (NSValueTransformer *)transformerForModelPropertiesOfClass:(Class)class;
|
||||
|
||||
/// A value transformer that should be used for a properties of the given
|
||||
/// primitive type.
|
||||
///
|
||||
/// If `objCType` matches @encode(id), the value transformer returned by
|
||||
/// +transformerForModelPropertiesOfClass: is used instead.
|
||||
///
|
||||
/// The default implementation transforms properties that match @encode(BOOL)
|
||||
/// using the MTLBooleanValueTransformerName transformer.
|
||||
///
|
||||
/// objCType - The type encoding for the value of this property. This is the type
|
||||
/// as it would be returned by the @encode() directive.
|
||||
///
|
||||
/// Returns a value transformer or nil if no transformation should be used.
|
||||
// A value transformer that should be used for a properties of the given
|
||||
// primitive type.
|
||||
//
|
||||
// If `objCType` matches @encode(id), the value transformer returned by
|
||||
// +transformerForModelPropertiesOfClass: is used instead.
|
||||
//
|
||||
// The default implementation transforms properties that match @encode(BOOL)
|
||||
// using the MTLBooleanValueTransformerName transformer.
|
||||
//
|
||||
// objCType - The type encoding for the value of this property. This is the type
|
||||
// as it would be returned by the @encode() directive.
|
||||
//
|
||||
// Returns a value transformer or nil if no transformation should be used.
|
||||
+ (NSValueTransformer *)transformerForModelPropertiesOfObjCType:(const char *)objCType;
|
||||
|
||||
@end
|
||||
|
||||
@interface MTLJSONAdapter (ValueTransformers)
|
||||
|
||||
/// Creates a reversible transformer to convert a JSON dictionary into a MTLModel
|
||||
/// object, and vice-versa.
|
||||
///
|
||||
/// modelClass - The MTLModel subclass to attempt to parse from the JSON. This
|
||||
/// class must conform to <MTLJSONSerializing>. This argument must
|
||||
/// not be nil.
|
||||
///
|
||||
/// Returns a reversible transformer which uses the class of the receiver for
|
||||
/// transforming values back and forth.
|
||||
+ (NSValueTransformer<MTLTransformerErrorHandling> *)dictionaryTransformerWithModelClass:(Class)modelClass;
|
||||
|
||||
/// Creates a reversible transformer to convert an array of JSON dictionaries
|
||||
/// into an array of MTLModel objects, and vice-versa.
|
||||
///
|
||||
/// modelClass - The MTLModel subclass to attempt to parse from each JSON
|
||||
/// dictionary. This class must conform to <MTLJSONSerializing>.
|
||||
/// This argument must not be nil.
|
||||
///
|
||||
/// Returns a reversible transformer which uses the class of the receiver for
|
||||
/// transforming array elements back and forth.
|
||||
+ (NSValueTransformer<MTLTransformerErrorHandling> *)arrayTransformerWithModelClass:(Class)modelClass;
|
||||
|
||||
/// This value transformer is used by MTLJSONAdapter to automatically convert
|
||||
/// NSURL properties to JSON strings and vice versa.
|
||||
// This value transformer is used by MTLJSONAdapter to automatically convert
|
||||
// NSURL properties to JSON strings and vice versa.
|
||||
+ (NSValueTransformer *)NSURLJSONTransformer;
|
||||
|
||||
/// This value transformer is used by MTLJSONAdapter to automatically convert
|
||||
/// NSUUID properties to JSON strings and vice versa.
|
||||
+ (NSValueTransformer *)NSUUIDJSONTransformer;
|
||||
|
||||
@end
|
||||
|
||||
@class MTLModel;
|
||||
@ -274,14 +237,14 @@ extern NSString * const MTLJSONAdapterThrownExceptionErrorKey;
|
||||
|
||||
@property (nonatomic, strong, readonly) id<MTLJSONSerializing> model __attribute__((unavailable("Replaced by -modelFromJSONDictionary:error:")));
|
||||
|
||||
+ (NSArray *)JSONArrayFromModels:(NSArray *)models __attribute__((deprecated("Replaced by +JSONArrayFromModels:error:"))) NS_SWIFT_UNAVAILABLE("Replaced by +JSONArrayFromModels:error:");
|
||||
+ (NSArray *)JSONArrayFromModels:(NSArray *)models __attribute__((deprecated("Replaced by +JSONArrayFromModels:error:")));
|
||||
|
||||
+ (NSDictionary *)JSONDictionaryFromModel:(MTLModel<MTLJSONSerializing> *)model __attribute__((deprecated("Replaced by +JSONDictionaryFromModel:error:"))) NS_SWIFT_UNAVAILABLE("Replaced by +JSONDictionaryFromModel:error:");
|
||||
+ (NSDictionary *)JSONDictionaryFromModel:(MTLModel<MTLJSONSerializing> *)model __attribute__((deprecated("Replaced by +JSONDictionaryFromModel:error:")));
|
||||
|
||||
- (NSDictionary *)JSONDictionary __attribute__((unavailable("Replaced by -JSONDictionaryFromModel:error:"))) NS_SWIFT_UNAVAILABLE("Replaced by -JSONDictionaryFromModel:error:");
|
||||
- (NSDictionary *)JSONDictionary __attribute__((unavailable("Replaced by -JSONDictionaryFromModel:error:")));
|
||||
- (NSString *)JSONKeyPathForPropertyKey:(NSString *)key __attribute__((unavailable("Replaced by -serializablePropertyKeys:forModel:")));
|
||||
- (id)initWithJSONDictionary:(NSDictionary *)JSONDictionary modelClass:(Class)modelClass error:(NSError **)error __attribute__((unavailable("Replaced by -initWithModelClass:")));
|
||||
- (id)initWithModel:(id<MTLJSONSerializing>)model __attribute__((unavailable("Replaced by -initWithModelClass:"))) NS_SWIFT_UNAVAILABLE("Replaced by -initWithModelClass:");
|
||||
- (NSDictionary *)serializeToJSONDictionary:(NSError **)error __attribute__((unavailable("Replaced by -JSONDictionaryFromModel:error:"))) NS_SWIFT_UNAVAILABLE("Replaced by -JSONDictionaryFromModel:error:");
|
||||
- (id)initWithModel:(id<MTLJSONSerializing>)model __attribute__((unavailable("Replaced by -initWithModelClass:")));
|
||||
- (NSDictionary *)serializeToJSONDictionary:(NSError **)error __attribute__((unavailable("Replaced by -JSONDictionaryFromModel:error:")));
|
||||
|
||||
@end
|
||||
|
||||
@ -10,14 +10,13 @@
|
||||
|
||||
#import "NSDictionary+MTLJSONKeyPath.h"
|
||||
|
||||
#import <Mantle/EXTRuntimeExtensions.h>
|
||||
#import <Mantle/EXTScope.h>
|
||||
#import "EXTRuntimeExtensions.h"
|
||||
#import "EXTScope.h"
|
||||
#import "MTLJSONAdapter.h"
|
||||
#import "MTLModel.h"
|
||||
#import "MTLTransformerErrorHandling.h"
|
||||
#import "MTLReflection.h"
|
||||
#import "NSValueTransformer+MTLPredefinedTransformerAdditions.h"
|
||||
#import "MTLValueTransformer.h"
|
||||
|
||||
NSString * const MTLJSONAdapterErrorDomain = @"MTLJSONAdapterErrorDomain";
|
||||
const NSInteger MTLJSONAdapterErrorNoClassFound = 2;
|
||||
@ -28,7 +27,7 @@ const NSInteger MTLJSONAdapterErrorInvalidJSONMapping = 4;
|
||||
const NSInteger MTLJSONAdapterErrorExceptionThrown = 1;
|
||||
|
||||
// Associated with the NSException that was caught.
|
||||
NSString * const MTLJSONAdapterThrownExceptionErrorKey = @"MTLJSONAdapterThrownException";
|
||||
static NSString * const MTLJSONAdapterThrownExceptionErrorKey = @"MTLJSONAdapterThrownException";
|
||||
|
||||
@interface MTLJSONAdapter ()
|
||||
|
||||
@ -294,7 +293,7 @@ NSString * const MTLJSONAdapterThrownExceptionErrorKey = @"MTLJSONAdapterThrownE
|
||||
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
|
||||
|
||||
for (NSString *keyPath in JSONKeyPaths) {
|
||||
BOOL success = NO;
|
||||
BOOL success;
|
||||
id value = [JSONDictionary mtl_valueForJSONKeyPath:keyPath success:&success error:error];
|
||||
|
||||
if (!success) return nil;
|
||||
@ -304,7 +303,7 @@ NSString * const MTLJSONAdapterThrownExceptionErrorKey = @"MTLJSONAdapterThrownE
|
||||
|
||||
value = dictionary;
|
||||
} else {
|
||||
BOOL success = NO;
|
||||
BOOL success;
|
||||
value = [JSONDictionary mtl_valueForJSONKeyPath:JSONKeyPaths success:&success error:error];
|
||||
|
||||
if (!success) return nil;
|
||||
@ -343,8 +342,7 @@ NSString * const MTLJSONAdapterThrownExceptionErrorKey = @"MTLJSONAdapterThrownE
|
||||
#else
|
||||
if (error != NULL) {
|
||||
NSDictionary *userInfo = @{
|
||||
NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Caught exception parsing JSON key path \"%@\" for model class: %@", JSONKeyPaths, self.modelClass],
|
||||
NSLocalizedRecoverySuggestionErrorKey: ex.description,
|
||||
NSLocalizedDescriptionKey: ex.description,
|
||||
NSLocalizedFailureReasonErrorKey: ex.reason,
|
||||
MTLJSONAdapterThrownExceptionErrorKey: ex
|
||||
};
|
||||
@ -357,9 +355,7 @@ NSString * const MTLJSONAdapterThrownExceptionErrorKey = @"MTLJSONAdapterThrownE
|
||||
}
|
||||
}
|
||||
|
||||
id model = [self.modelClass modelWithDictionary:dictionaryValue error:error];
|
||||
|
||||
return [model validate:error] ? model : nil;
|
||||
return [self.modelClass modelWithDictionary:dictionaryValue error:error];
|
||||
}
|
||||
|
||||
+ (NSDictionary *)valueTransformersForModelClass:(Class)modelClass {
|
||||
@ -371,22 +367,20 @@ NSString * const MTLJSONAdapterThrownExceptionErrorKey = @"MTLJSONAdapterThrownE
|
||||
for (NSString *key in [modelClass propertyKeys]) {
|
||||
SEL selector = MTLSelectorWithKeyPattern(key, "JSONTransformer");
|
||||
if ([modelClass respondsToSelector:selector]) {
|
||||
IMP imp = [modelClass methodForSelector:selector];
|
||||
NSValueTransformer * (*function)(id, SEL) = (__typeof__(function))imp;
|
||||
NSValueTransformer *transformer = function(modelClass, selector);
|
||||
|
||||
if (transformer != nil) result[key] = transformer;
|
||||
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[modelClass methodSignatureForSelector:selector]];
|
||||
invocation.target = modelClass;
|
||||
invocation.selector = selector;
|
||||
[invocation invoke];
|
||||
|
||||
__unsafe_unretained id transformer = nil;
|
||||
[invocation getReturnValue:&transformer];
|
||||
result[key] = transformer;
|
||||
continue;
|
||||
}
|
||||
|
||||
if ([modelClass respondsToSelector:@selector(JSONTransformerForKey:)]) {
|
||||
NSValueTransformer *transformer = [modelClass JSONTransformerForKey:key];
|
||||
|
||||
if (transformer != nil) {
|
||||
result[key] = transformer;
|
||||
continue;
|
||||
}
|
||||
result[key] = [modelClass JSONTransformerForKey:key];
|
||||
continue;
|
||||
}
|
||||
|
||||
objc_property_t property = class_getProperty(modelClass, key.UTF8String);
|
||||
@ -407,13 +401,7 @@ NSString * const MTLJSONAdapterThrownExceptionErrorKey = @"MTLJSONAdapterThrownE
|
||||
transformer = [self transformerForModelPropertiesOfClass:propertyClass];
|
||||
}
|
||||
|
||||
|
||||
// For user-defined MTLModel, try parse it with dictionaryTransformer.
|
||||
if (nil == transformer && [propertyClass conformsToProtocol:@protocol(MTLJSONSerializing)]) {
|
||||
transformer = [self dictionaryTransformerWithModelClass:propertyClass];
|
||||
}
|
||||
|
||||
if (transformer == nil) transformer = [NSValueTransformer mtl_validatingTransformerForClass:propertyClass ?: NSObject.class];
|
||||
if (transformer == nil) transformer = [NSValueTransformer mtl_validatingTransformerForClass:NSObject.class];
|
||||
} else {
|
||||
transformer = [self transformerForModelPropertiesOfObjCType:attributes->type] ?: [NSValueTransformer mtl_validatingTransformerForClass:NSValue.class];
|
||||
}
|
||||
@ -433,7 +421,7 @@ NSString * const MTLJSONAdapterThrownExceptionErrorKey = @"MTLJSONAdapterThrownE
|
||||
|
||||
if (result != nil) return result;
|
||||
|
||||
result = [[self.class alloc] initWithModelClass:modelClass];
|
||||
result = [[MTLJSONAdapter alloc] initWithModelClass:modelClass];
|
||||
|
||||
if (result != nil) {
|
||||
[self.JSONAdaptersByModelClass setObject:result forKey:modelClass];
|
||||
@ -452,11 +440,14 @@ NSString * const MTLJSONAdapterThrownExceptionErrorKey = @"MTLJSONAdapterThrownE
|
||||
|
||||
SEL selector = MTLSelectorWithKeyPattern(NSStringFromClass(modelClass), "JSONTransformer");
|
||||
if (![self respondsToSelector:selector]) return nil;
|
||||
|
||||
IMP imp = [self methodForSelector:selector];
|
||||
NSValueTransformer * (*function)(id, SEL) = (__typeof__(function))imp;
|
||||
NSValueTransformer *result = function(self, selector);
|
||||
|
||||
|
||||
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:selector]];
|
||||
invocation.target = self;
|
||||
invocation.selector = selector;
|
||||
[invocation invoke];
|
||||
|
||||
__unsafe_unretained id result = nil;
|
||||
[invocation getReturnValue:&result];
|
||||
return result;
|
||||
}
|
||||
|
||||
@ -474,180 +465,10 @@ NSString * const MTLJSONAdapterThrownExceptionErrorKey = @"MTLJSONAdapterThrownE
|
||||
|
||||
@implementation MTLJSONAdapter (ValueTransformers)
|
||||
|
||||
+ (NSValueTransformer<MTLTransformerErrorHandling> *)dictionaryTransformerWithModelClass:(Class)modelClass {
|
||||
NSParameterAssert([modelClass conformsToProtocol:@protocol(MTLModel)]);
|
||||
NSParameterAssert([modelClass conformsToProtocol:@protocol(MTLJSONSerializing)]);
|
||||
__block MTLJSONAdapter *adapter;
|
||||
|
||||
return [MTLValueTransformer
|
||||
transformerUsingForwardBlock:^ id (id JSONDictionary, BOOL *success, NSError **error) {
|
||||
if (JSONDictionary == nil) return nil;
|
||||
|
||||
if (![JSONDictionary isKindOfClass:NSDictionary.class]) {
|
||||
if (error != NULL) {
|
||||
NSDictionary *userInfo = @{
|
||||
NSLocalizedDescriptionKey: NSLocalizedString(@"Could not convert JSON dictionary to model object", @""),
|
||||
NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:NSLocalizedString(@"Expected an NSDictionary, got: %@", @""), JSONDictionary],
|
||||
MTLTransformerErrorHandlingInputValueErrorKey : JSONDictionary
|
||||
};
|
||||
|
||||
*error = [NSError errorWithDomain:MTLTransformerErrorHandlingErrorDomain code:MTLTransformerErrorHandlingErrorInvalidInput userInfo:userInfo];
|
||||
}
|
||||
*success = NO;
|
||||
return nil;
|
||||
}
|
||||
|
||||
if (!adapter) {
|
||||
adapter = [[self alloc] initWithModelClass:modelClass];
|
||||
}
|
||||
id model = [adapter modelFromJSONDictionary:JSONDictionary error:error];
|
||||
if (model == nil) {
|
||||
*success = NO;
|
||||
}
|
||||
|
||||
return model;
|
||||
}
|
||||
reverseBlock:^ NSDictionary * (id model, BOOL *success, NSError **error) {
|
||||
if (model == nil) return nil;
|
||||
|
||||
if (![model conformsToProtocol:@protocol(MTLModel)] || ![model conformsToProtocol:@protocol(MTLJSONSerializing)]) {
|
||||
if (error != NULL) {
|
||||
NSDictionary *userInfo = @{
|
||||
NSLocalizedDescriptionKey: NSLocalizedString(@"Could not convert model object to JSON dictionary", @""),
|
||||
NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:NSLocalizedString(@"Expected a MTLModel object conforming to <MTLJSONSerializing>, got: %@.", @""), model],
|
||||
MTLTransformerErrorHandlingInputValueErrorKey : model
|
||||
};
|
||||
|
||||
*error = [NSError errorWithDomain:MTLTransformerErrorHandlingErrorDomain code:MTLTransformerErrorHandlingErrorInvalidInput userInfo:userInfo];
|
||||
}
|
||||
*success = NO;
|
||||
return nil;
|
||||
}
|
||||
|
||||
if (!adapter) {
|
||||
adapter = [[self alloc] initWithModelClass:modelClass];
|
||||
}
|
||||
NSDictionary *result = [adapter JSONDictionaryFromModel:model error:error];
|
||||
if (result == nil) {
|
||||
*success = NO;
|
||||
}
|
||||
|
||||
return result;
|
||||
}];
|
||||
}
|
||||
|
||||
+ (NSValueTransformer<MTLTransformerErrorHandling> *)arrayTransformerWithModelClass:(Class)modelClass {
|
||||
id<MTLTransformerErrorHandling> dictionaryTransformer = [self dictionaryTransformerWithModelClass:modelClass];
|
||||
|
||||
return [MTLValueTransformer
|
||||
transformerUsingForwardBlock:^ id (NSArray *dictionaries, BOOL *success, NSError **error) {
|
||||
if (dictionaries == nil) return nil;
|
||||
|
||||
if (![dictionaries isKindOfClass:NSArray.class]) {
|
||||
if (error != NULL) {
|
||||
NSDictionary *userInfo = @{
|
||||
NSLocalizedDescriptionKey: NSLocalizedString(@"Could not convert JSON array to model array", @""),
|
||||
NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:NSLocalizedString(@"Expected an NSArray, got: %@.", @""), dictionaries],
|
||||
MTLTransformerErrorHandlingInputValueErrorKey : dictionaries
|
||||
};
|
||||
|
||||
*error = [NSError errorWithDomain:MTLTransformerErrorHandlingErrorDomain code:MTLTransformerErrorHandlingErrorInvalidInput userInfo:userInfo];
|
||||
}
|
||||
*success = NO;
|
||||
return nil;
|
||||
}
|
||||
|
||||
NSMutableArray *models = [NSMutableArray arrayWithCapacity:dictionaries.count];
|
||||
for (id JSONDictionary in dictionaries) {
|
||||
if (JSONDictionary == NSNull.null) {
|
||||
[models addObject:NSNull.null];
|
||||
continue;
|
||||
}
|
||||
|
||||
if (![JSONDictionary isKindOfClass:NSDictionary.class]) {
|
||||
if (error != NULL) {
|
||||
NSDictionary *userInfo = @{
|
||||
NSLocalizedDescriptionKey: NSLocalizedString(@"Could not convert JSON array to model array", @""),
|
||||
NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:NSLocalizedString(@"Expected an NSDictionary or an NSNull, got: %@.", @""), JSONDictionary],
|
||||
MTLTransformerErrorHandlingInputValueErrorKey : JSONDictionary
|
||||
};
|
||||
|
||||
*error = [NSError errorWithDomain:MTLTransformerErrorHandlingErrorDomain code:MTLTransformerErrorHandlingErrorInvalidInput userInfo:userInfo];
|
||||
}
|
||||
*success = NO;
|
||||
return nil;
|
||||
}
|
||||
|
||||
id model = [dictionaryTransformer transformedValue:JSONDictionary success:success error:error];
|
||||
|
||||
if (*success == NO) return nil;
|
||||
|
||||
if (model == nil) continue;
|
||||
|
||||
[models addObject:model];
|
||||
}
|
||||
|
||||
return models;
|
||||
}
|
||||
reverseBlock:^ id (NSArray *models, BOOL *success, NSError **error) {
|
||||
if (models == nil) return nil;
|
||||
|
||||
if (![models isKindOfClass:NSArray.class]) {
|
||||
if (error != NULL) {
|
||||
NSDictionary *userInfo = @{
|
||||
NSLocalizedDescriptionKey: NSLocalizedString(@"Could not convert model array to JSON array", @""),
|
||||
NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:NSLocalizedString(@"Expected an NSArray, got: %@.", @""), models],
|
||||
MTLTransformerErrorHandlingInputValueErrorKey : models
|
||||
};
|
||||
|
||||
*error = [NSError errorWithDomain:MTLTransformerErrorHandlingErrorDomain code:MTLTransformerErrorHandlingErrorInvalidInput userInfo:userInfo];
|
||||
}
|
||||
*success = NO;
|
||||
return nil;
|
||||
}
|
||||
|
||||
NSMutableArray *dictionaries = [NSMutableArray arrayWithCapacity:models.count];
|
||||
for (id model in models) {
|
||||
if (model == NSNull.null) {
|
||||
[dictionaries addObject:NSNull.null];
|
||||
continue;
|
||||
}
|
||||
|
||||
if (![model isKindOfClass:MTLModel.class]) {
|
||||
if (error != NULL) {
|
||||
NSDictionary *userInfo = @{
|
||||
NSLocalizedDescriptionKey: NSLocalizedString(@"Could not convert JSON array to model array", @""),
|
||||
NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:NSLocalizedString(@"Expected a MTLModel or an NSNull, got: %@.", @""), model],
|
||||
MTLTransformerErrorHandlingInputValueErrorKey : model
|
||||
};
|
||||
|
||||
*error = [NSError errorWithDomain:MTLTransformerErrorHandlingErrorDomain code:MTLTransformerErrorHandlingErrorInvalidInput userInfo:userInfo];
|
||||
}
|
||||
*success = NO;
|
||||
return nil;
|
||||
}
|
||||
|
||||
NSDictionary *dict = [dictionaryTransformer reverseTransformedValue:model success:success error:error];
|
||||
|
||||
if (*success == NO) return nil;
|
||||
|
||||
if (dict == nil) continue;
|
||||
|
||||
[dictionaries addObject:dict];
|
||||
}
|
||||
|
||||
return dictionaries;
|
||||
}];
|
||||
}
|
||||
|
||||
+ (NSValueTransformer *)NSURLJSONTransformer {
|
||||
return [NSValueTransformer valueTransformerForName:MTLURLValueTransformerName];
|
||||
}
|
||||
|
||||
+ (NSValueTransformer *)NSUUIDJSONTransformer {
|
||||
return [NSValueTransformer valueTransformerForName:MTLUUIDValueTransformerName];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation MTLJSONAdapter (Deprecated)
|
||||
|
||||
17
Mantle/MTLManagedObject.h
Normal file
17
Mantle/MTLManagedObject.h
Normal file
@ -0,0 +1,17 @@
|
||||
//
|
||||
// MTLManagedObject.h
|
||||
// Mantle
|
||||
//
|
||||
// Created by Robert Böhnke on 17/05/14.
|
||||
// Copyright (c) 2014 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <CoreData/CoreData.h>
|
||||
|
||||
#import "MTLModel.h"
|
||||
|
||||
@interface MTLManagedObject : NSManagedObject <MTLModel>
|
||||
|
||||
+ (NSEntityDescription *)entityDescription;
|
||||
|
||||
@end
|
||||
76
Mantle/MTLManagedObject.m
Normal file
76
Mantle/MTLManagedObject.m
Normal file
@ -0,0 +1,76 @@
|
||||
//
|
||||
// MTLManagedObject.m
|
||||
// Mantle
|
||||
//
|
||||
// Created by Robert Böhnke on 17/05/14.
|
||||
// Copyright (c) 2014 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import "MTLValidateAndSetValue.h"
|
||||
|
||||
#import "MTLManagedObject.h"
|
||||
|
||||
@implementation MTLManagedObject
|
||||
|
||||
#pragma mark Lifecycle
|
||||
|
||||
+ (instancetype)modelWithDictionary:(NSDictionary *)dictionaryValue error:(NSError **)error {
|
||||
return [[self alloc] initWithDictionary:dictionaryValue error:error];
|
||||
}
|
||||
|
||||
- (instancetype)initWithDictionary:(NSDictionary *)dictionaryValue error:(NSError **)error {
|
||||
NSEntityDescription *entityDescription = self.class.entityDescription;
|
||||
|
||||
NSAssert([entityDescription.managedObjectClassName isEqualToString:NSStringFromClass(self.class)], @"+entityDescription must match class %@, got %@.", self.class, entityDescription.managedObjectClassName);
|
||||
|
||||
self = [super initWithEntity:entityDescription insertIntoManagedObjectContext:nil];
|
||||
if (self == nil) return self;
|
||||
|
||||
for (NSString *key in dictionaryValue) {
|
||||
// Mark this as being autoreleased, because validateValue may return
|
||||
// a new object to be stored in this variable (and we don't want ARC to
|
||||
// double-free or leak the old or new values).
|
||||
__autoreleasing id value = [dictionaryValue objectForKey:key];
|
||||
|
||||
if ([value isEqual:NSNull.null]) value = nil;
|
||||
|
||||
BOOL success = MTLValidateAndSetValue(self, key, value, YES, error);
|
||||
if (!success) return nil;
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
#pragma mark MTLManagedObject
|
||||
|
||||
+ (NSEntityDescription *)entityDescription {
|
||||
return nil;
|
||||
}
|
||||
|
||||
#pragma mark MTLModel
|
||||
|
||||
+ (NSSet *)propertyKeys {
|
||||
NSMutableSet *propertyKeys = [NSMutableSet set];
|
||||
|
||||
for (NSPropertyDescription *description in self.entityDescription.properties) {
|
||||
[propertyKeys addObject:description.name];
|
||||
}
|
||||
|
||||
return propertyKeys;
|
||||
}
|
||||
|
||||
- (NSDictionary *)dictionaryValue {
|
||||
return [self dictionaryWithValuesForKeys:self.class.propertyKeys.allObjects];
|
||||
}
|
||||
|
||||
- (void)mergeValueForKey:(NSString *)key fromModel:(id<MTLModel>)model {
|
||||
[self setValue:[(id)model valueForKey:key] forKey:key];
|
||||
}
|
||||
|
||||
#pragma mark NSCopying
|
||||
|
||||
- (id)copyWithZone:(NSZone *)zone {
|
||||
return [[self.class allocWithZone:zone] initWithDictionary:self.dictionaryValue error:NULL];
|
||||
}
|
||||
|
||||
@end
|
||||
252
Mantle/MTLManagedObjectAdapter.h
Normal file
252
Mantle/MTLManagedObjectAdapter.h
Normal file
@ -0,0 +1,252 @@
|
||||
//
|
||||
// MTLManagedObjectAdapter.h
|
||||
// Mantle
|
||||
//
|
||||
// Created by Justin Spahr-Summers on 2013-03-29.
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <CoreData/CoreData.h>
|
||||
|
||||
@protocol MTLModel;
|
||||
|
||||
// A MTLModel object that supports being serialized to and from Core Data as an
|
||||
// NSManagedObject.
|
||||
@protocol MTLManagedObjectSerializing <MTLModel>
|
||||
@required
|
||||
|
||||
// The name of the Core Data entity that the receiver serializes to and
|
||||
// deserializes from.
|
||||
//
|
||||
// This method must not return nil.
|
||||
+ (NSString *)managedObjectEntityName;
|
||||
|
||||
// Specifies how to map property keys to different keys on the receiver's
|
||||
// +managedObjectEntity.
|
||||
//
|
||||
// Entity attributes will be mapped to and from the receiver's properties using
|
||||
// +entityAttributeTransformerForKey:. Entity relationships will be mapped to
|
||||
// and from MTLModel objects using +relationshipModelClassesByPropertyKey.
|
||||
// Fetched properties are not supported.
|
||||
//
|
||||
// Subclasses overriding this method should combine their values with those of
|
||||
// `super`.
|
||||
//
|
||||
// Any keys omitted will not participate in managed object serialization.
|
||||
//
|
||||
// Returns a dictionary mapping property keys to entity keys (as strings) or
|
||||
// NSNull values.
|
||||
+ (NSDictionary *)managedObjectKeysByPropertyKey;
|
||||
|
||||
@optional
|
||||
|
||||
// Specifies a set of property keys used by the adapter to check for an already
|
||||
// existing managed object when converting the MTLModel to its related
|
||||
// NSManagedObject.
|
||||
//
|
||||
// The adapter will first map any keys provided by this method to the correct
|
||||
// keys in managedObjectKeysByPropertyKey.
|
||||
//
|
||||
// The adapter will then perform a fetch request in the provided context for a
|
||||
// managed object that matches the MTLModel's managedObjectEntityName and has
|
||||
// equal values set for the property keys on the MTLModel.
|
||||
//
|
||||
// The managed object returned by the fetch request will then be set with all
|
||||
// values from the MTLModel that the managed object is being converted from.
|
||||
//
|
||||
// If a property value of our MTLModel is yet another MTLModel which needs to be
|
||||
// converted to a managed object, the class for that MTLModel can also implement
|
||||
// this method to perform its own uniqing.
|
||||
//
|
||||
// For example:
|
||||
// 1. An MTLModel subclass has id_number = 10.
|
||||
// 2. An NSManagedObject accessible to the adapter's context has idnumber = 10.
|
||||
// 3. managedObjectKeysByPropertyKey returns @{@"id_number" : @"idnumber"}
|
||||
// 4. propertyKeysForManagedObjectUniquing returns
|
||||
// [NSSet setWithObject:@"id_number"];
|
||||
// 5. Then our fetch request may return this managed object (or another managed
|
||||
// object with idnumber = 10).
|
||||
//
|
||||
// NOTE: If multiple managed objects follow the same uniquing criteria only one
|
||||
// of them will be set with our MTLModel's values.
|
||||
+ (NSSet *)propertyKeysForManagedObjectUniquing;
|
||||
|
||||
// Specifies how to convert the given property key to a managed object
|
||||
// attribute. If reversible, the transformer will also be used to convert the
|
||||
// managed object attribute back to the property.
|
||||
//
|
||||
// If the receiver implements a `-<key>EntityAttributeTransformer` method,
|
||||
// MTLManagedObjectAdapter will use the result of that method instead.
|
||||
//
|
||||
// Returns a value transformer, or nil if no transformation should be performed.
|
||||
+ (NSValueTransformer *)entityAttributeTransformerForKey:(NSString *)key;
|
||||
|
||||
// Specifies the MTLModel subclasses that should be deserialized to the
|
||||
// receiver's property keys when a property key corresponds to an entity
|
||||
// relationship.
|
||||
//
|
||||
// In other words, the dictionary returned by this method is used to decode
|
||||
// managed object relationships into MTLModels (or NSArrays or NSSets thereof)
|
||||
// set on the receiver.
|
||||
//
|
||||
// If a property key is omitted from the returned dictionary, but present in
|
||||
// +managedObjectKeysByPropertyKey, and the receiver's +managedObjectEntity has
|
||||
// a relationship at the corresponding key, an exception will be thrown during
|
||||
// deserialization.
|
||||
//
|
||||
// Subclasses overriding this method should combine their values with those of
|
||||
// `super`.
|
||||
//
|
||||
// Returns a dictionary mapping property keys to the Class objects that should
|
||||
// be used.
|
||||
+ (NSDictionary *)relationshipModelClassesByPropertyKey;
|
||||
|
||||
// Overridden to deserialize a different class instead of the receiver, based on
|
||||
// information in the provided object.
|
||||
//
|
||||
// This is mostly useful for class clusters, where the abstract base class would
|
||||
// be passed into +[MTLManagedObjectAdapter
|
||||
// modelOfClass:fromManagedObject:error:], but a subclass should be instantiated
|
||||
// instead.
|
||||
//
|
||||
// managedObject - The object that will be deserialized.
|
||||
//
|
||||
// Returns the class that should be instantiated (which may be the receiver), or
|
||||
// nil to abort parsing (e.g., if the data is invalid).
|
||||
+ (Class)classForDeserializingManagedObject:(NSManagedObject *)managedObject;
|
||||
|
||||
// Overriden when merging the value of the given key on the receiver with the
|
||||
// value of the same key from the given `NSManagedObject` requires custom
|
||||
// handling.
|
||||
//
|
||||
// By default, this method is not implemented, and precedence will be given to
|
||||
// the value of the receiving model implicitly.
|
||||
//
|
||||
// When implemented, this method is called when an existing `NSManagedObject`
|
||||
// is found for the receiving model, before updating the `NSManagedObject`'s
|
||||
// properties.
|
||||
//
|
||||
// When implementing, you should use `+managedObjectKeysByPropertyKey` to map
|
||||
// the given `key` to the appropriate `NSManagedObject` property.
|
||||
- (void)mergeValueForKey:(NSString *)key fromManagedObject:(NSManagedObject *)managedObject;
|
||||
|
||||
// Overriden when merging values on the receiver with the given
|
||||
// `NSManagedObject` requires custom handling.
|
||||
//
|
||||
// By default, this method is not implemented, and precedence will be given to
|
||||
// the values of the receiving model implicitly.
|
||||
//
|
||||
// When implemented, this method is called when an existing `NSManagedObject`
|
||||
// is found for the receiving model, before updating the `NSManagedObject`'s
|
||||
// properties.
|
||||
//
|
||||
// When implementing, you should use `+managedObjectKeysByPropertyKey` to map
|
||||
// the given `key` to the appropriate `NSManagedObject` property.
|
||||
//
|
||||
// If you have also implemented `mergeValueForKey:fromManagedObject:` you have
|
||||
// to make sure to call `mergeValueForKey:fromManagedObject:` from this method
|
||||
// when appropriate.
|
||||
- (void)mergeValuesForKeysFromManagedObject:(NSManagedObject *)managedObject;
|
||||
|
||||
@end
|
||||
|
||||
// The domain for errors originating from MTLManagedObjectAdapter.
|
||||
extern NSString * const MTLManagedObjectAdapterErrorDomain;
|
||||
|
||||
// +classForDeserializingManagedObject: returned nil for the given object.
|
||||
extern const NSInteger MTLManagedObjectAdapterErrorNoClassFound;
|
||||
|
||||
// An NSManagedObject failed to initialize.
|
||||
extern const NSInteger MTLManagedObjectAdapterErrorInitializationFailed;
|
||||
|
||||
// The managed object key specified by +managedObjectKeysByPropertyKey does not
|
||||
// exist in the NSEntityDescription.
|
||||
extern const NSInteger MTLManagedObjectAdapterErrorInvalidManagedObjectKey;
|
||||
|
||||
// The managed object property specified has a type that isn't supported by
|
||||
// MTLManagedObjectAdapter.
|
||||
extern const NSInteger MTLManagedObjectAdapterErrorUnsupportedManagedObjectPropertyType;
|
||||
|
||||
// The fetch request to find an existing managed object based on
|
||||
// `+propertyKeysForManagedObjectUniquing` failed.
|
||||
extern const NSInteger MTLManagedObjectAdapterErrorUniqueFetchRequestFailed;
|
||||
|
||||
// A MTLModel property cannot be serialized to or deserialized from an
|
||||
// NSManagedObject relationship.
|
||||
//
|
||||
// For a to-one relationship, this means that the property does not contain
|
||||
// a MTLModel, or the MTLModel does not conform to <MTLManagedObjectSerializing>.
|
||||
//
|
||||
// For a to-many relationship, this means that the property does not contain an
|
||||
// NSArray or NSSet of MTLModel<MTLManagedObjectSerializing> instances.
|
||||
extern const NSInteger MTLManagedObjectAdapterErrorUnsupportedRelationshipClass;
|
||||
|
||||
// The model's implementation of +managedObjectKeysByPropertyKey included a key
|
||||
// which does not actually exist in +propertyKeys.
|
||||
extern const NSInteger MTLManagedObjectAdapterErrorInvalidManagedObjectMapping;
|
||||
|
||||
// Converts a MTLModel object to and from an NSManagedObject.
|
||||
@interface MTLManagedObjectAdapter : NSObject
|
||||
|
||||
// Attempts to deserialize an NSManagedObject into a MTLModel object.
|
||||
//
|
||||
// modelClass - The MTLModel subclass to return. This class must conform to
|
||||
// <MTLManagedObjectSerializing>. This argument must not be nil.
|
||||
// managedObject - The managed object to deserialize. If this argument is nil,
|
||||
// the method returns nil.
|
||||
// error - If not NULL, this may be set to an error that occurs during
|
||||
// deserialization or initializing an instance of `modelClass`.
|
||||
//
|
||||
// Returns an instance of `modelClass` upon success, or nil if an error
|
||||
// occurred.
|
||||
+ (id)modelOfClass:(Class)modelClass fromManagedObject:(NSManagedObject *)managedObject error:(NSError **)error;
|
||||
|
||||
// Serializes a MTLModel into an NSManagedObject.
|
||||
//
|
||||
// model - The model object to serialize. This argument must not be nil.
|
||||
// context - The context into which to insert the created managed object. This
|
||||
// argument must not be nil.
|
||||
// error - If not NULL, this may be set to an error that occurs during
|
||||
// serialization or insertion.
|
||||
+ (id)managedObjectFromModel:(id<MTLManagedObjectSerializing>)model insertingIntoContext:(NSManagedObjectContext *)context error:(NSError **)error;
|
||||
|
||||
// An optional value transformer that should be used for properties of the given
|
||||
// class.
|
||||
//
|
||||
// A value transformer returned by the model's
|
||||
// +entityAttributeTransformerForKey: method is given precedence over the one
|
||||
// returned by this method.
|
||||
//
|
||||
// The default implementation invokes `+<class>EntityAttributeTransformer` on
|
||||
// the receiver if it's implemented. It supports NSURL conversion through
|
||||
// -NSURLEntityAttributeTransformer.
|
||||
//
|
||||
// class - The class of the property to serialize. This property must not be
|
||||
// nil.
|
||||
//
|
||||
// Returns a value transformer or nil if no transformation should be used.
|
||||
+ (NSValueTransformer *)transformerForModelPropertiesOfClass:(Class)class;
|
||||
|
||||
// A value transformer that should be used for a properties of the given
|
||||
// primitive type.
|
||||
//
|
||||
// If `objCType` matches @encode(id), the value transformer returned by
|
||||
// +transformerForModelPropertiesOfClass: is used instead.
|
||||
//
|
||||
// The default implementation simply returns nil.
|
||||
//
|
||||
// objCType - The type encoding for the value of this property. This is the type
|
||||
// as it would be returned by the @encode() directive.
|
||||
//
|
||||
// Returns a value transformer or nil if no transformation should be used.
|
||||
+ (NSValueTransformer *)transformerForModelPropertiesOfObjCType:(const char *)objCType;
|
||||
|
||||
@end
|
||||
|
||||
@interface MTLManagedObjectAdapter (ValueTransformers)
|
||||
|
||||
// This value transformer is used by MTLManagedObjectAdapter to automatically
|
||||
// convert NSURL properties to strings and vice versa.
|
||||
+ (NSValueTransformer *)NSURLEntityAttributeTransformer;
|
||||
|
||||
@end
|
||||
776
Mantle/MTLManagedObjectAdapter.m
Normal file
776
Mantle/MTLManagedObjectAdapter.m
Normal file
@ -0,0 +1,776 @@
|
||||
//
|
||||
// MTLManagedObjectAdapter.m
|
||||
// Mantle
|
||||
//
|
||||
// Created by Justin Spahr-Summers on 2013-03-29.
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <objc/runtime.h>
|
||||
|
||||
#import "EXTScope.h"
|
||||
#import "EXTRuntimeExtensions.h"
|
||||
#import "MTLManagedObjectAdapter.h"
|
||||
#import "MTLModel.h"
|
||||
#import "MTLTransformerErrorHandling.h"
|
||||
#import "MTLReflection.h"
|
||||
#import "NSArray+MTLManipulationAdditions.h"
|
||||
#import "NSValueTransformer+MTLPredefinedTransformerAdditions.h"
|
||||
|
||||
NSString * const MTLManagedObjectAdapterErrorDomain = @"MTLManagedObjectAdapterErrorDomain";
|
||||
const NSInteger MTLManagedObjectAdapterErrorNoClassFound = 2;
|
||||
const NSInteger MTLManagedObjectAdapterErrorInitializationFailed = 3;
|
||||
const NSInteger MTLManagedObjectAdapterErrorInvalidManagedObjectKey = 4;
|
||||
const NSInteger MTLManagedObjectAdapterErrorUnsupportedManagedObjectPropertyType = 5;
|
||||
const NSInteger MTLManagedObjectAdapterErrorUnsupportedRelationshipClass = 6;
|
||||
const NSInteger MTLManagedObjectAdapterErrorUniqueFetchRequestFailed = 7;
|
||||
const NSInteger MTLManagedObjectAdapterErrorInvalidManagedObjectMapping = 8;
|
||||
|
||||
// Performs the given block in the context's queue, if it has one.
|
||||
static id performInContext(NSManagedObjectContext *context, id (^block)(void)) {
|
||||
if (context.concurrencyType == NSConfinementConcurrencyType) {
|
||||
return block();
|
||||
}
|
||||
|
||||
__block id result = nil;
|
||||
[context performBlockAndWait:^{
|
||||
result = block();
|
||||
}];
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@interface MTLManagedObjectAdapter ()
|
||||
|
||||
// The MTLModel subclass being serialized or deserialized.
|
||||
@property (nonatomic, strong, readonly) Class modelClass;
|
||||
|
||||
// A cached copy of the return value of +managedObjectKeysByPropertyKey.
|
||||
@property (nonatomic, copy, readonly) NSDictionary *managedObjectKeysByPropertyKey;
|
||||
|
||||
// A cached copy of the return value of +relationshipModelClassesByPropertyKey.
|
||||
@property (nonatomic, copy, readonly) NSDictionary *relationshipModelClassesByPropertyKey;
|
||||
|
||||
// A cache of the return value of -valueTransformersForModelClass:
|
||||
@property (nonatomic, copy, readonly) NSDictionary *valueTransformersByPropertyKey;
|
||||
|
||||
// Collect all value transformers needed for a given class.
|
||||
//
|
||||
// modelClass - The MTLModel for which to collect the transformers.
|
||||
// This class must conform to <MTLManagedObjectSerializing>. This
|
||||
// argument must not be nil.
|
||||
//
|
||||
// Returns a dictionary with the properties of modelClass that need
|
||||
// transformation as keys and the value transformers as values.
|
||||
- (NSDictionary *)valueTransformersForModelClass:(Class)class;
|
||||
|
||||
// Initializes the receiver to serialize or deserialize a MTLModel of the given
|
||||
// class.
|
||||
- (id)initWithModelClass:(Class)modelClass;
|
||||
|
||||
// Invoked from +modelOfClass:fromManagedObject:processedObjects:error: after
|
||||
// the receiver's properties have been initialized.
|
||||
- (id)modelFromManagedObject:(NSManagedObject *)managedObject processedObjects:(CFMutableDictionaryRef)processedObjects error:(NSError **)error;
|
||||
|
||||
// Performs the actual work of deserialization. This method is also invoked when
|
||||
// processing relationships, to create a new adapter (if needed) to handle them.
|
||||
//
|
||||
// `processedObjects` is a dictionary mapping NSManagedObjects to the MTLModels
|
||||
// that have been created so far. It should remain alive for the full process
|
||||
// of deserializing the top-level managed object.
|
||||
+ (id)modelOfClass:(Class)modelClass fromManagedObject:(NSManagedObject *)managedObject processedObjects:(CFMutableDictionaryRef)processedObjects error:(NSError **)error;
|
||||
|
||||
// Invoked from
|
||||
// +managedObjectFromModel:insertingIntoContext:processedObjects:error: after
|
||||
// the receiver's properties have been initialized.
|
||||
- (id)managedObjectFromModel:(id<MTLManagedObjectSerializing>)model insertingIntoContext:(NSManagedObjectContext *)context processedObjects:(CFMutableDictionaryRef)processedObjects error:(NSError **)error;
|
||||
|
||||
// Performs the actual work of serialization. This method is also invoked when
|
||||
// processing relationships, to create a new adapter (if needed) to handle them.
|
||||
//
|
||||
// `processedObjects` is a dictionary mapping MTLModels to the NSManagedObjects
|
||||
// that have been created so far. It should remain alive for the full process
|
||||
// of serializing the top-level MTLModel.
|
||||
+ (id)managedObjectFromModel:(id<MTLManagedObjectSerializing>)model insertingIntoContext:(NSManagedObjectContext *)context processedObjects:(CFMutableDictionaryRef)processedObjects error:(NSError **)error;
|
||||
|
||||
// Looks at propertyKeysForManagedObjectUniquing and forms an NSPredicate
|
||||
// using the uniquing keys and the provided model.
|
||||
//
|
||||
// model - The model to create a uniquing predicate for.
|
||||
// success - If not NULL, this may be set to indicate if the transformation was
|
||||
// successful.
|
||||
// error - If not NULL, this may be set to an error that occurs during
|
||||
// transforming the value.
|
||||
//
|
||||
// Returns a predicate, or nil if no predicate is needed or if an error
|
||||
// occurred. Clients should inspect the success parameter to decide how to
|
||||
// proceed with the result.
|
||||
- (NSPredicate *)uniquingPredicateForModel:(id<MTLManagedObjectSerializing>)model success:(BOOL *)success error:(NSError **)error;
|
||||
|
||||
@end
|
||||
|
||||
@implementation MTLManagedObjectAdapter
|
||||
|
||||
#pragma mark Lifecycle
|
||||
|
||||
- (id)init {
|
||||
NSAssert(NO, @"%@ should not be initialized using -init", self.class);
|
||||
return nil;
|
||||
}
|
||||
|
||||
- (id)initWithModelClass:(Class)modelClass {
|
||||
NSParameterAssert(modelClass != nil);
|
||||
|
||||
self = [super init];
|
||||
if (self == nil) return nil;
|
||||
|
||||
_modelClass = modelClass;
|
||||
_managedObjectKeysByPropertyKey = [[modelClass managedObjectKeysByPropertyKey] copy];
|
||||
_valueTransformersByPropertyKey = [self valueTransformersForModelClass:modelClass];
|
||||
|
||||
if ([modelClass respondsToSelector:@selector(relationshipModelClassesByPropertyKey)]) {
|
||||
_relationshipModelClassesByPropertyKey = [[modelClass relationshipModelClassesByPropertyKey] copy];
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
#pragma mark Serialization
|
||||
|
||||
- (id)modelFromManagedObject:(NSManagedObject *)managedObject processedObjects:(CFMutableDictionaryRef)processedObjects error:(NSError **)error {
|
||||
NSParameterAssert(managedObject != nil);
|
||||
NSParameterAssert(processedObjects != nil);
|
||||
|
||||
NSEntityDescription *entity = managedObject.entity;
|
||||
NSAssert(entity != nil, @"%@ returned a nil +entity", managedObject);
|
||||
|
||||
NSManagedObjectContext *context = managedObject.managedObjectContext;
|
||||
|
||||
NSDictionary *managedObjectProperties = entity.propertiesByName;
|
||||
NSObject<MTLModel> *model = [[self.modelClass alloc] init];
|
||||
|
||||
// Pre-emptively consider this object processed, so that we don't get into
|
||||
// any cycles when processing its relationships.
|
||||
CFDictionaryAddValue(processedObjects, (__bridge void *)managedObject, (__bridge void *)model);
|
||||
|
||||
BOOL (^setValueForKey)(NSString *, id) = ^(NSString *key, id value) {
|
||||
// Mark this as being autoreleased, because validateValue may return
|
||||
// a new object to be stored in this variable (and we don't want ARC to
|
||||
// double-free or leak the old or new values).
|
||||
__autoreleasing id replaceableValue = value;
|
||||
if (![model validateValue:&replaceableValue forKey:key error:error]) return NO;
|
||||
|
||||
[model setValue:replaceableValue forKey:key];
|
||||
return YES;
|
||||
};
|
||||
|
||||
for (NSString *propertyKey in [self.modelClass propertyKeys]) {
|
||||
NSString *managedObjectKey = self.managedObjectKeysByPropertyKey[propertyKey];
|
||||
if (managedObjectKey == nil) continue;
|
||||
|
||||
BOOL (^deserializeAttribute)(NSAttributeDescription *) = ^(NSAttributeDescription *attributeDescription) {
|
||||
id value = performInContext(context, ^{
|
||||
return [managedObject valueForKey:managedObjectKey];
|
||||
});
|
||||
|
||||
NSValueTransformer *transformer = self.valueTransformersByPropertyKey[propertyKey];
|
||||
if ([transformer respondsToSelector:@selector(transformedValue:success:error:)]) {
|
||||
id<MTLTransformerErrorHandling> errorHandlingTransformer = (id)transformer;
|
||||
|
||||
BOOL success = YES;
|
||||
value = [errorHandlingTransformer transformedValue:value success:&success error:error];
|
||||
|
||||
if (!success) return NO;
|
||||
} else if (transformer != nil) {
|
||||
value = [transformer transformedValue:value];
|
||||
}
|
||||
|
||||
return setValueForKey(propertyKey, value);
|
||||
};
|
||||
|
||||
BOOL (^deserializeRelationship)(NSRelationshipDescription *) = ^(NSRelationshipDescription *relationshipDescription) {
|
||||
Class nestedClass = self.relationshipModelClassesByPropertyKey[propertyKey];
|
||||
if (nestedClass == nil) {
|
||||
[NSException raise:NSInvalidArgumentException format:@"No class specified for decoding relationship at key \"%@\" in managed object %@", managedObjectKey, managedObject];
|
||||
}
|
||||
|
||||
if ([relationshipDescription isToMany]) {
|
||||
id models = performInContext(context, ^ id {
|
||||
id relationshipCollection = [managedObject valueForKey:managedObjectKey];
|
||||
NSMutableArray *models = [NSMutableArray arrayWithCapacity:[relationshipCollection count]];
|
||||
|
||||
for (NSManagedObject *nestedObject in relationshipCollection) {
|
||||
id<MTLManagedObjectSerializing> model = [self.class modelOfClass:nestedClass fromManagedObject:nestedObject processedObjects:processedObjects error:error];
|
||||
if (model == nil) return nil;
|
||||
|
||||
[models addObject:model];
|
||||
}
|
||||
|
||||
return models;
|
||||
});
|
||||
|
||||
if (models == nil) return NO;
|
||||
if (![relationshipDescription isOrdered]) models = [NSSet setWithArray:models];
|
||||
|
||||
return setValueForKey(propertyKey, models);
|
||||
} else {
|
||||
NSManagedObject *nestedObject = performInContext(context, ^{
|
||||
return [managedObject valueForKey:managedObjectKey];
|
||||
});
|
||||
|
||||
if (nestedObject == nil) return YES;
|
||||
|
||||
id<MTLManagedObjectSerializing> model = [self.class modelOfClass:nestedClass fromManagedObject:nestedObject processedObjects:processedObjects error:error];
|
||||
if (model == nil) return NO;
|
||||
|
||||
return setValueForKey(propertyKey, model);
|
||||
}
|
||||
};
|
||||
|
||||
BOOL (^deserializeProperty)(NSPropertyDescription *) = ^(NSPropertyDescription *propertyDescription) {
|
||||
if (propertyDescription == nil) {
|
||||
if (error != NULL) {
|
||||
NSString *failureReason = [NSString stringWithFormat:NSLocalizedString(@"No property by name \"%@\" exists on the entity.", @""), managedObjectKey];
|
||||
|
||||
NSDictionary *userInfo = @{
|
||||
NSLocalizedDescriptionKey: NSLocalizedString(@"Could not deserialize managed object", @""),
|
||||
NSLocalizedFailureReasonErrorKey: failureReason,
|
||||
};
|
||||
|
||||
*error = [NSError errorWithDomain:MTLManagedObjectAdapterErrorDomain code:MTLManagedObjectAdapterErrorInvalidManagedObjectKey userInfo:userInfo];
|
||||
}
|
||||
|
||||
return NO;
|
||||
}
|
||||
|
||||
// Jump through some hoops to avoid referencing classes directly.
|
||||
NSString *propertyClassName = NSStringFromClass(propertyDescription.class);
|
||||
if ([propertyClassName isEqual:@"NSAttributeDescription"]) {
|
||||
return deserializeAttribute((id)propertyDescription);
|
||||
} else if ([propertyClassName isEqual:@"NSRelationshipDescription"]) {
|
||||
return deserializeRelationship((id)propertyDescription);
|
||||
} else {
|
||||
if (error != NULL) {
|
||||
NSString *failureReason = [NSString stringWithFormat:NSLocalizedString(@"Property descriptions of class %@ are unsupported.", @""), propertyClassName];
|
||||
|
||||
NSDictionary *userInfo = @{
|
||||
NSLocalizedDescriptionKey: NSLocalizedString(@"Could not deserialize managed object", @""),
|
||||
NSLocalizedFailureReasonErrorKey: failureReason,
|
||||
};
|
||||
|
||||
*error = [NSError errorWithDomain:MTLManagedObjectAdapterErrorDomain code:MTLManagedObjectAdapterErrorUnsupportedManagedObjectPropertyType userInfo:userInfo];
|
||||
}
|
||||
|
||||
return NO;
|
||||
}
|
||||
};
|
||||
|
||||
if (!deserializeProperty(managedObjectProperties[managedObjectKey])) return nil;
|
||||
}
|
||||
|
||||
return model;
|
||||
}
|
||||
|
||||
+ (id)modelOfClass:(Class)modelClass fromManagedObject:(NSManagedObject *)managedObject error:(NSError **)error {
|
||||
NSSet *propertyKeys = [modelClass propertyKeys];
|
||||
|
||||
for (NSString *mappedPropertyKey in [modelClass managedObjectKeysByPropertyKey]) {
|
||||
if ([propertyKeys containsObject:mappedPropertyKey]) continue;
|
||||
|
||||
if (error != NULL) {
|
||||
NSDictionary *userInfo = @{
|
||||
NSLocalizedDescriptionKey: NSLocalizedString(@"Invalid entity attribute mapping", nil),
|
||||
NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:NSLocalizedString(@"%1$@ could not be parsed because its entity attribute mapping contains illegal property keys.", nil), modelClass]
|
||||
};
|
||||
|
||||
*error = [NSError errorWithDomain:MTLManagedObjectAdapterErrorDomain code:MTLManagedObjectAdapterErrorInvalidManagedObjectMapping userInfo:userInfo];
|
||||
}
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
CFMutableDictionaryRef processedObjects = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
|
||||
if (processedObjects == NULL) return nil;
|
||||
|
||||
@onExit {
|
||||
CFRelease(processedObjects);
|
||||
};
|
||||
|
||||
return [self modelOfClass:modelClass fromManagedObject:managedObject processedObjects:processedObjects error:error];
|
||||
}
|
||||
|
||||
+ (id)modelOfClass:(Class)modelClass fromManagedObject:(NSManagedObject *)managedObject processedObjects:(CFMutableDictionaryRef)processedObjects error:(NSError **)error {
|
||||
NSParameterAssert(modelClass != nil);
|
||||
NSParameterAssert(processedObjects != nil);
|
||||
|
||||
if (managedObject == nil) return nil;
|
||||
|
||||
const void *existingModel = CFDictionaryGetValue(processedObjects, (__bridge void *)managedObject);
|
||||
if (existingModel != NULL) {
|
||||
return (__bridge id)existingModel;
|
||||
}
|
||||
|
||||
if ([modelClass respondsToSelector:@selector(classForDeserializingManagedObject:)]) {
|
||||
modelClass = [modelClass classForDeserializingManagedObject:managedObject];
|
||||
if (modelClass == nil) {
|
||||
if (error != NULL) {
|
||||
NSDictionary *userInfo = @{
|
||||
NSLocalizedDescriptionKey: NSLocalizedString(@"Could not deserialize managed object", @""),
|
||||
NSLocalizedFailureReasonErrorKey: NSLocalizedString(@"No model class could be found to deserialize the object.", @"")
|
||||
};
|
||||
|
||||
*error = [NSError errorWithDomain:MTLManagedObjectAdapterErrorDomain code:MTLManagedObjectAdapterErrorNoClassFound userInfo:userInfo];
|
||||
}
|
||||
|
||||
return nil;
|
||||
}
|
||||
}
|
||||
|
||||
MTLManagedObjectAdapter *adapter = [[self alloc] initWithModelClass:modelClass];
|
||||
return [adapter modelFromManagedObject:managedObject processedObjects:processedObjects error:error];
|
||||
}
|
||||
|
||||
- (id)managedObjectFromModel:(id<MTLManagedObjectSerializing>)model insertingIntoContext:(NSManagedObjectContext *)context processedObjects:(CFMutableDictionaryRef)processedObjects error:(NSError **)error {
|
||||
NSParameterAssert(model != nil);
|
||||
NSParameterAssert(context != nil);
|
||||
NSParameterAssert(processedObjects != nil);
|
||||
|
||||
NSString *entityName = [model.class managedObjectEntityName];
|
||||
NSAssert(entityName != nil, @"%@ returned a nil +managedObjectEntityName", model.class);
|
||||
|
||||
Class entityDescriptionClass = NSClassFromString(@"NSEntityDescription");
|
||||
NSAssert(entityDescriptionClass != nil, @"CoreData.framework must be linked to use MTLManagedObjectAdapter");
|
||||
|
||||
Class fetchRequestClass = NSClassFromString(@"NSFetchRequest");
|
||||
NSAssert(fetchRequestClass != nil, @"CoreData.framework must be linked to use MTLManagedObjectAdapter");
|
||||
|
||||
// If a uniquing predicate is provided, perform a fetch request to guarantee a unique managed object.
|
||||
__block NSManagedObject *managedObject = nil;
|
||||
BOOL success = YES;
|
||||
NSPredicate *uniquingPredicate = [self uniquingPredicateForModel:model success:&success error:error];
|
||||
|
||||
if (!success) return nil;
|
||||
|
||||
if (uniquingPredicate != nil) {
|
||||
__block NSError *fetchRequestError = nil;
|
||||
__block BOOL encountedError = NO;
|
||||
managedObject = performInContext(context, ^ id {
|
||||
NSFetchRequest *fetchRequest = [[fetchRequestClass alloc] init];
|
||||
fetchRequest.entity = [entityDescriptionClass entityForName:entityName inManagedObjectContext:context];
|
||||
fetchRequest.predicate = uniquingPredicate;
|
||||
fetchRequest.returnsObjectsAsFaults = NO;
|
||||
fetchRequest.fetchLimit = 1;
|
||||
|
||||
NSArray *results = [context executeFetchRequest:fetchRequest error:&fetchRequestError];
|
||||
|
||||
if (results == nil) {
|
||||
encountedError = YES;
|
||||
if (error != NULL) {
|
||||
NSString *failureReason = [NSString stringWithFormat:NSLocalizedString(@"Failed to fetch a managed object for uniqing predicate \"%@\".", @""), uniquingPredicate];
|
||||
|
||||
NSDictionary *userInfo = @{
|
||||
NSLocalizedDescriptionKey: NSLocalizedString(@"Could not serialize managed object", @""),
|
||||
NSLocalizedFailureReasonErrorKey: failureReason,
|
||||
};
|
||||
|
||||
fetchRequestError = [NSError errorWithDomain:MTLManagedObjectAdapterErrorDomain code:MTLManagedObjectAdapterErrorUniqueFetchRequestFailed userInfo:userInfo];
|
||||
}
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
return results.mtl_firstObject;
|
||||
});
|
||||
|
||||
if (encountedError && error != NULL) {
|
||||
*error = fetchRequestError;
|
||||
return nil;
|
||||
}
|
||||
}
|
||||
|
||||
if (managedObject == nil) {
|
||||
managedObject = [entityDescriptionClass insertNewObjectForEntityForName:entityName inManagedObjectContext:context];
|
||||
} else {
|
||||
// Our CoreData store already has data for this model, we need to merge
|
||||
[self mergeValuesOfModel:model forKeysFromManagedObject:managedObject];
|
||||
}
|
||||
|
||||
if (managedObject == nil) {
|
||||
if (error != NULL) {
|
||||
NSString *failureReason = [NSString stringWithFormat:NSLocalizedString(@"Failed to initialize a managed object from entity named \"%@\".", @""), entityName];
|
||||
|
||||
NSDictionary *userInfo = @{
|
||||
NSLocalizedDescriptionKey: NSLocalizedString(@"Could not serialize managed object", @""),
|
||||
NSLocalizedFailureReasonErrorKey: failureReason,
|
||||
};
|
||||
|
||||
*error = [NSError errorWithDomain:MTLManagedObjectAdapterErrorDomain code:MTLManagedObjectAdapterErrorInitializationFailed userInfo:userInfo];
|
||||
}
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
// Assign all errors to this variable to work around a memory problem.
|
||||
//
|
||||
// See https://github.com/github/Mantle/pull/120 for more context.
|
||||
__block NSError *tmpError;
|
||||
|
||||
// Pre-emptively consider this object processed, so that we don't get into
|
||||
// any cycles when processing its relationships.
|
||||
CFDictionaryAddValue(processedObjects, (__bridge void *)model, (__bridge void *)managedObject);
|
||||
|
||||
NSDictionary *dictionaryValue = model.dictionaryValue;
|
||||
NSDictionary *managedObjectProperties = managedObject.entity.propertiesByName;
|
||||
|
||||
[dictionaryValue enumerateKeysAndObjectsUsingBlock:^(NSString *propertyKey, id value, BOOL *stop) {
|
||||
NSString *managedObjectKey = self.managedObjectKeysByPropertyKey[propertyKey];
|
||||
if (managedObjectKey == nil) return;
|
||||
if ([value isEqual:NSNull.null]) value = nil;
|
||||
|
||||
BOOL (^serializeAttribute)(NSAttributeDescription *) = ^(NSAttributeDescription *attributeDescription) {
|
||||
// Mark this as being autoreleased, because validateValue may return
|
||||
// a new object to be stored in this variable (and we don't want ARC to
|
||||
// double-free or leak the old or new values).
|
||||
__autoreleasing id transformedValue = value;
|
||||
|
||||
NSValueTransformer *transformer = self.valueTransformersByPropertyKey[propertyKey];
|
||||
if ([transformer.class allowsReverseTransformation]) {
|
||||
if ([transformer respondsToSelector:@selector(reverseTransformedValue:success:error:)]) {
|
||||
id<MTLTransformerErrorHandling> errorHandlingTransformer = (id)transformer;
|
||||
|
||||
BOOL success = YES;
|
||||
transformedValue = [errorHandlingTransformer reverseTransformedValue:value success:&success error:error];
|
||||
|
||||
if (!success) return NO;
|
||||
} else {
|
||||
transformedValue = [transformer reverseTransformedValue:transformedValue];
|
||||
}
|
||||
}
|
||||
|
||||
if (![managedObject validateValue:&transformedValue forKey:managedObjectKey error:&tmpError]) return NO;
|
||||
[managedObject setValue:transformedValue forKey:managedObjectKey];
|
||||
|
||||
return YES;
|
||||
};
|
||||
|
||||
NSManagedObject * (^objectForRelationshipFromModel)(id) = ^ id (id model) {
|
||||
if (![model conformsToProtocol:@protocol(MTLManagedObjectSerializing)]) {
|
||||
NSString *failureReason = [NSString stringWithFormat:NSLocalizedString(@"Property of class %@ cannot be encoded into an NSManagedObject.", @""), [model class]];
|
||||
|
||||
NSDictionary *userInfo = @{
|
||||
NSLocalizedDescriptionKey: NSLocalizedString(@"Could not serialize managed object", @""),
|
||||
NSLocalizedFailureReasonErrorKey: failureReason
|
||||
};
|
||||
|
||||
tmpError = [NSError errorWithDomain:MTLManagedObjectAdapterErrorDomain code:MTLManagedObjectAdapterErrorUnsupportedRelationshipClass userInfo:userInfo];
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
return [self.class managedObjectFromModel:model insertingIntoContext:context processedObjects:processedObjects error:&tmpError];
|
||||
};
|
||||
|
||||
BOOL (^serializeRelationship)(NSRelationshipDescription *) = ^(NSRelationshipDescription *relationshipDescription) {
|
||||
if (value == nil) return YES;
|
||||
|
||||
if ([relationshipDescription isToMany]) {
|
||||
if (![value conformsToProtocol:@protocol(NSFastEnumeration)]) {
|
||||
NSString *failureReason = [NSString stringWithFormat:NSLocalizedString(@"Property of class %@ cannot be encoded into a to-many relationship.", @""), [value class]];
|
||||
|
||||
NSDictionary *userInfo = @{
|
||||
NSLocalizedDescriptionKey: NSLocalizedString(@"Could not serialize managed object", @""),
|
||||
NSLocalizedFailureReasonErrorKey: failureReason
|
||||
};
|
||||
|
||||
tmpError = [NSError errorWithDomain:MTLManagedObjectAdapterErrorDomain code:MTLManagedObjectAdapterErrorUnsupportedRelationshipClass userInfo:userInfo];
|
||||
|
||||
return NO;
|
||||
}
|
||||
|
||||
id relationshipCollection;
|
||||
if ([relationshipDescription isOrdered]) {
|
||||
relationshipCollection = [NSMutableOrderedSet orderedSet];
|
||||
} else {
|
||||
relationshipCollection = [NSMutableSet set];
|
||||
}
|
||||
|
||||
for (id<MTLModel> model in value) {
|
||||
NSManagedObject *nestedObject = objectForRelationshipFromModel(model);
|
||||
if (nestedObject == nil) return NO;
|
||||
|
||||
[relationshipCollection addObject:nestedObject];
|
||||
}
|
||||
|
||||
[managedObject setValue:relationshipCollection forKey:managedObjectKey];
|
||||
} else {
|
||||
NSManagedObject *nestedObject = objectForRelationshipFromModel(value);
|
||||
if (nestedObject == nil) return NO;
|
||||
|
||||
[managedObject setValue:nestedObject forKey:managedObjectKey];
|
||||
}
|
||||
|
||||
return YES;
|
||||
};
|
||||
|
||||
BOOL (^serializeProperty)(NSPropertyDescription *) = ^(NSPropertyDescription *propertyDescription) {
|
||||
if (propertyDescription == nil) {
|
||||
NSString *failureReason = [NSString stringWithFormat:NSLocalizedString(@"No property by name \"%@\" exists on the entity.", @""), managedObjectKey];
|
||||
|
||||
NSDictionary *userInfo = @{
|
||||
NSLocalizedDescriptionKey: NSLocalizedString(@"Could not serialize managed object", @""),
|
||||
NSLocalizedFailureReasonErrorKey: failureReason
|
||||
};
|
||||
|
||||
tmpError = [NSError errorWithDomain:MTLManagedObjectAdapterErrorDomain code:MTLManagedObjectAdapterErrorInvalidManagedObjectKey userInfo:userInfo];
|
||||
|
||||
return NO;
|
||||
}
|
||||
|
||||
// Jump through some hoops to avoid referencing classes directly.
|
||||
NSString *propertyClassName = NSStringFromClass(propertyDescription.class);
|
||||
if ([propertyClassName isEqual:@"NSAttributeDescription"]) {
|
||||
return serializeAttribute((id)propertyDescription);
|
||||
} else if ([propertyClassName isEqual:@"NSRelationshipDescription"]) {
|
||||
return serializeRelationship((id)propertyDescription);
|
||||
} else {
|
||||
NSString *failureReason = [NSString stringWithFormat:NSLocalizedString(@"Property descriptions of class %@ are unsupported.", @""), propertyClassName];
|
||||
|
||||
NSDictionary *userInfo = @{
|
||||
NSLocalizedDescriptionKey: NSLocalizedString(@"Could not serialize managed object", @""),
|
||||
NSLocalizedFailureReasonErrorKey: failureReason
|
||||
};
|
||||
|
||||
tmpError = [NSError errorWithDomain:MTLManagedObjectAdapterErrorDomain code:MTLManagedObjectAdapterErrorUnsupportedManagedObjectPropertyType userInfo:userInfo];
|
||||
|
||||
return NO;
|
||||
}
|
||||
};
|
||||
|
||||
if (!serializeProperty(managedObjectProperties[managedObjectKey])) {
|
||||
performInContext(context, ^ id {
|
||||
[context deleteObject:managedObject];
|
||||
return nil;
|
||||
});
|
||||
|
||||
managedObject = nil;
|
||||
*stop = YES;
|
||||
}
|
||||
}];
|
||||
|
||||
if (managedObject != nil && ![managedObject validateForInsert:&tmpError]) {
|
||||
managedObject = performInContext(context, ^ id {
|
||||
[context deleteObject:managedObject];
|
||||
return nil;
|
||||
});
|
||||
}
|
||||
|
||||
if (error != NULL) {
|
||||
*error = tmpError;
|
||||
}
|
||||
|
||||
return managedObject;
|
||||
}
|
||||
|
||||
+ (id)managedObjectFromModel:(id<MTLManagedObjectSerializing>)model insertingIntoContext:(NSManagedObjectContext *)context error:(NSError **)error {
|
||||
CFDictionaryKeyCallBacks keyCallbacks = kCFTypeDictionaryKeyCallBacks;
|
||||
|
||||
// Compare MTLModel keys using pointer equality, not -isEqual:.
|
||||
keyCallbacks.equal = NULL;
|
||||
|
||||
CFMutableDictionaryRef processedObjects = CFDictionaryCreateMutable(NULL, 0, &keyCallbacks, &kCFTypeDictionaryValueCallBacks);
|
||||
if (processedObjects == NULL) return nil;
|
||||
|
||||
@onExit {
|
||||
CFRelease(processedObjects);
|
||||
};
|
||||
|
||||
return [self managedObjectFromModel:model insertingIntoContext:context processedObjects:processedObjects error:error];
|
||||
}
|
||||
|
||||
+ (id)managedObjectFromModel:(id<MTLManagedObjectSerializing>)model insertingIntoContext:(NSManagedObjectContext *)context processedObjects:(CFMutableDictionaryRef)processedObjects error:(NSError **)error {
|
||||
NSParameterAssert(model != nil);
|
||||
NSParameterAssert(context != nil);
|
||||
NSParameterAssert(processedObjects != nil);
|
||||
|
||||
const void *existingManagedObject = CFDictionaryGetValue(processedObjects, (__bridge void *)model);
|
||||
if (existingManagedObject != NULL) {
|
||||
return (__bridge id)existingManagedObject;
|
||||
}
|
||||
|
||||
MTLManagedObjectAdapter *adapter = [[self alloc] initWithModelClass:model.class];
|
||||
return [adapter managedObjectFromModel:model insertingIntoContext:context processedObjects:processedObjects error:error];
|
||||
}
|
||||
|
||||
- (NSValueTransformer *)entityAttributeTransformerForKey:(NSString *)key {
|
||||
NSParameterAssert(key != nil);
|
||||
|
||||
SEL selector = MTLSelectorWithKeyPattern(key, "EntityAttributeTransformer");
|
||||
if ([self.modelClass respondsToSelector:selector]) {
|
||||
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[self.modelClass methodSignatureForSelector:selector]];
|
||||
invocation.target = self.modelClass;
|
||||
invocation.selector = selector;
|
||||
[invocation invoke];
|
||||
|
||||
__unsafe_unretained id result = nil;
|
||||
[invocation getReturnValue:&result];
|
||||
return result;
|
||||
}
|
||||
|
||||
if ([self.modelClass respondsToSelector:@selector(entityAttributeTransformerForKey:)]) {
|
||||
return [self.modelClass entityAttributeTransformerForKey:key];
|
||||
}
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
- (NSString *)managedObjectKeyForKey:(NSString *)key {
|
||||
NSParameterAssert(key != nil);
|
||||
|
||||
id managedObjectKey = self.managedObjectKeysByPropertyKey[key];
|
||||
if ([managedObjectKey isEqual:NSNull.null]) return nil;
|
||||
|
||||
if (managedObjectKey == nil) {
|
||||
return key;
|
||||
} else {
|
||||
return managedObjectKey;
|
||||
}
|
||||
}
|
||||
|
||||
- (void)mergeValueOfModel:(MTLModel<MTLManagedObjectSerializing> *)model forKey:(NSString *)key fromManagedObject:(NSManagedObject *)managedObject {
|
||||
[model mergeValueForKey:key fromManagedObject:managedObject];
|
||||
}
|
||||
|
||||
- (void)mergeValuesOfModel:(MTLModel<MTLManagedObjectSerializing> *)model forKeysFromManagedObject:(NSManagedObject *)managedObject {
|
||||
if ([model respondsToSelector:@selector(mergeValuesForKeysFromManagedObject:)]) {
|
||||
[model mergeValuesForKeysFromManagedObject:managedObject];
|
||||
} else if ([model respondsToSelector:@selector(mergeValueForKey:fromManagedObject:)]) {
|
||||
[[model.class managedObjectKeysByPropertyKey] enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *managedObjectKey, BOOL *stop) {
|
||||
[self mergeValueOfModel:model forKey:key fromManagedObject:managedObject];
|
||||
}];
|
||||
}
|
||||
}
|
||||
|
||||
- (NSPredicate *)uniquingPredicateForModel:(NSObject<MTLManagedObjectSerializing> *)model success:(BOOL *)success error:(NSError **)error {
|
||||
if (![self.modelClass respondsToSelector:@selector(propertyKeysForManagedObjectUniquing)]) return nil;
|
||||
|
||||
NSSet *propertyKeys = [self.modelClass propertyKeysForManagedObjectUniquing];
|
||||
|
||||
if (propertyKeys == nil) return nil;
|
||||
|
||||
NSAssert(propertyKeys.count > 0, @"+propertyKeysForManagedObjectUniquing must not be empty.");
|
||||
|
||||
NSMutableArray *subpredicates = [NSMutableArray array];
|
||||
for (NSString *propertyKey in propertyKeys) {
|
||||
NSString *managedObjectKey = self.managedObjectKeysByPropertyKey[propertyKey];
|
||||
|
||||
NSAssert(managedObjectKey != nil, @"%@ must map to a managed object key.", propertyKey);
|
||||
|
||||
id value = [model valueForKeyPath:propertyKey];
|
||||
|
||||
NSValueTransformer *transformer = self.valueTransformersByPropertyKey[propertyKey];
|
||||
if ([transformer.class allowsReverseTransformation]) {
|
||||
if ([transformer respondsToSelector:@selector(transformedValue:success:error:)]) {
|
||||
id<MTLTransformerErrorHandling> errorHandlingTransformer = (id)transformer;
|
||||
|
||||
BOOL innerSuccess = YES;
|
||||
value = [errorHandlingTransformer reverseTransformedValue:value success:&innerSuccess error:error];
|
||||
|
||||
if (!innerSuccess) {
|
||||
if (success != NULL) *success = NO;
|
||||
return nil;
|
||||
}
|
||||
} else {
|
||||
value = [transformer reverseTransformedValue:value];
|
||||
}
|
||||
}
|
||||
|
||||
NSPredicate *subpredicate = [NSPredicate predicateWithFormat:@"%K == %@", managedObjectKey, value];
|
||||
[subpredicates addObject:subpredicate];
|
||||
}
|
||||
|
||||
if (success != NULL) *success = YES;
|
||||
return [NSCompoundPredicate andPredicateWithSubpredicates:subpredicates];
|
||||
}
|
||||
|
||||
- (NSDictionary *)valueTransformersForModelClass:(Class)modelClass {
|
||||
NSParameterAssert(modelClass != nil);
|
||||
NSParameterAssert([modelClass isSubclassOfClass:MTLModel.class]);
|
||||
NSParameterAssert([modelClass conformsToProtocol:@protocol(MTLManagedObjectSerializing)]);
|
||||
|
||||
NSMutableDictionary *result = [NSMutableDictionary dictionary];
|
||||
|
||||
for (NSString *key in [modelClass propertyKeys]) {
|
||||
SEL selector = MTLSelectorWithKeyPattern(key, "EntityAttributeTransformer");
|
||||
if ([self.modelClass respondsToSelector:selector]) {
|
||||
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[self.modelClass methodSignatureForSelector:selector]];
|
||||
invocation.target = self.modelClass;
|
||||
invocation.selector = selector;
|
||||
[invocation invoke];
|
||||
|
||||
__unsafe_unretained id transformer = nil;
|
||||
[invocation getReturnValue:&transformer];
|
||||
result[key] = transformer;
|
||||
continue;
|
||||
}
|
||||
|
||||
if ([self.modelClass respondsToSelector:@selector(entityAttributeTransformerForKey:)]) {
|
||||
result[key] = [self.modelClass entityAttributeTransformerForKey:key];
|
||||
continue;
|
||||
}
|
||||
|
||||
objc_property_t property = class_getProperty(modelClass, key.UTF8String);
|
||||
|
||||
if (property == NULL) continue;
|
||||
|
||||
mtl_propertyAttributes *attributes = mtl_copyPropertyAttributes(property);
|
||||
@onExit {
|
||||
free(attributes);
|
||||
};
|
||||
|
||||
NSValueTransformer *transformer = nil;
|
||||
|
||||
if (attributes->objectClass != nil) {
|
||||
transformer = [self.class transformerForModelPropertiesOfClass:attributes->objectClass];
|
||||
}
|
||||
|
||||
if (transformer == nil && attributes->type != NULL) {
|
||||
transformer = [self.class transformerForModelPropertiesOfObjCType:attributes->type];
|
||||
}
|
||||
|
||||
if (transformer != nil) result[key] = transformer;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
+ (NSValueTransformer *)transformerForModelPropertiesOfClass:(Class)class {
|
||||
NSParameterAssert(class != nil);
|
||||
|
||||
SEL selector = MTLSelectorWithKeyPattern(NSStringFromClass(class), "EntityAttributeTransformer");
|
||||
if (![self respondsToSelector:selector]) return nil;
|
||||
|
||||
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:selector]];
|
||||
invocation.target = self;
|
||||
invocation.selector = selector;
|
||||
[invocation invoke];
|
||||
|
||||
__unsafe_unretained id result = nil;
|
||||
[invocation getReturnValue:&result];
|
||||
return result;
|
||||
}
|
||||
|
||||
+ (NSValueTransformer *)transformerForModelPropertiesOfObjCType:(const char *)objCType {
|
||||
NSParameterAssert(objCType != NULL);
|
||||
|
||||
return nil;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation MTLManagedObjectAdapter (ValueTransformers)
|
||||
|
||||
+ (NSValueTransformer *)NSURLEntityAttributeTransformer {
|
||||
return [NSValueTransformer valueTransformerForName:MTLURLValueTransformerName];
|
||||
}
|
||||
|
||||
@end
|
||||
@ -8,121 +8,121 @@
|
||||
|
||||
#import "MTLModel.h"
|
||||
|
||||
/// Defines how a MTLModel property key should be encoded into an archive.
|
||||
///
|
||||
/// MTLModelEncodingBehaviorExcluded - The property should never be encoded.
|
||||
/// MTLModelEncodingBehaviorUnconditional - The property should always be
|
||||
/// encoded.
|
||||
/// MTLModelEncodingBehaviorConditional - The object should be encoded only
|
||||
/// if unconditionally encoded elsewhere.
|
||||
/// This should only be used for object
|
||||
/// properties.
|
||||
// Defines how a MTLModel property key should be encoded into an archive.
|
||||
//
|
||||
// MTLModelEncodingBehaviorExcluded - The property should never be encoded.
|
||||
// MTLModelEncodingBehaviorUnconditional - The property should always be
|
||||
// encoded.
|
||||
// MTLModelEncodingBehaviorConditional - The object should be encoded only
|
||||
// if unconditionally encoded elsewhere.
|
||||
// This should only be used for object
|
||||
// properties.
|
||||
typedef enum : NSUInteger {
|
||||
MTLModelEncodingBehaviorExcluded = 0,
|
||||
MTLModelEncodingBehaviorUnconditional,
|
||||
MTLModelEncodingBehaviorConditional,
|
||||
} MTLModelEncodingBehavior;
|
||||
|
||||
/// Implements default archiving and unarchiving behaviors for MTLModel.
|
||||
// Implements default archiving and unarchiving behaviors for MTLModel.
|
||||
@interface MTLModel (NSCoding) <NSCoding>
|
||||
|
||||
/// Initializes the receiver from an archive.
|
||||
///
|
||||
/// This will decode the original +modelVersion of the archived object, then
|
||||
/// invoke -decodeValueForKey:withCoder:modelVersion: for each of the receiver's
|
||||
/// +propertyKeys.
|
||||
///
|
||||
/// Returns an initialized model object, or nil if a decoding error occurred.
|
||||
// Initializes the receiver from an archive.
|
||||
//
|
||||
// This will decode the original +modelVersion of the archived object, then
|
||||
// invoke -decodeValueForKey:withCoder:modelVersion: for each of the receiver's
|
||||
// +propertyKeys.
|
||||
//
|
||||
// Returns an initialized model object, or nil if a decoding error occurred.
|
||||
- (id)initWithCoder:(NSCoder *)coder;
|
||||
|
||||
/// Archives the receiver using the given coder.
|
||||
///
|
||||
/// This will encode the receiver's +modelVersion, then the receiver's properties
|
||||
/// according to the behaviors specified in +encodingBehaviorsByPropertyKey.
|
||||
// Archives the receiver using the given coder.
|
||||
//
|
||||
// This will encode the receiver's +modelVersion, then the receiver's properties
|
||||
// according to the behaviors specified in +encodingBehaviorsByPropertyKey.
|
||||
- (void)encodeWithCoder:(NSCoder *)coder;
|
||||
|
||||
/// Determines how the +propertyKeys of the class are encoded into an archive.
|
||||
/// The values of this dictionary should be boxed MTLModelEncodingBehavior
|
||||
/// values.
|
||||
///
|
||||
/// Any keys not present in the dictionary will be excluded from the archive.
|
||||
///
|
||||
/// Subclasses overriding this method should combine their values with those of
|
||||
/// `super`.
|
||||
///
|
||||
/// Returns a dictionary mapping the receiver's +propertyKeys to default encoding
|
||||
/// behaviors. If a property is an object with `weak` semantics, the default
|
||||
/// behavior is MTLModelEncodingBehaviorConditional; otherwise, the default is
|
||||
/// MTLModelEncodingBehaviorUnconditional.
|
||||
// Determines how the +propertyKeys of the class are encoded into an archive.
|
||||
// The values of this dictionary should be boxed MTLModelEncodingBehavior
|
||||
// values.
|
||||
//
|
||||
// Any keys not present in the dictionary will be excluded from the archive.
|
||||
//
|
||||
// Subclasses overriding this method should combine their values with those of
|
||||
// `super`.
|
||||
//
|
||||
// Returns a dictionary mapping the receiver's +propertyKeys to default encoding
|
||||
// behaviors. If a property is an object with `weak` semantics, the default
|
||||
// behavior is MTLModelEncodingBehaviorConditional; otherwise, the default is
|
||||
// MTLModelEncodingBehaviorUnconditional.
|
||||
+ (NSDictionary *)encodingBehaviorsByPropertyKey;
|
||||
|
||||
/// Determines the classes that are allowed to be decoded for each of the
|
||||
/// receiver's properties when using <NSSecureCoding>. The values of this
|
||||
/// dictionary should be NSArrays of Class objects.
|
||||
///
|
||||
/// If any encodable keys (as determined by +encodingBehaviorsByPropertyKey) are
|
||||
/// not present in the dictionary, an exception will be thrown during secure
|
||||
/// encoding or decoding.
|
||||
///
|
||||
/// Subclasses overriding this method should combine their values with those of
|
||||
/// `super`.
|
||||
///
|
||||
/// Returns a dictionary mapping the receiver's encodable keys (as determined by
|
||||
/// +encodingBehaviorsByPropertyKey) to default allowed classes, based on the
|
||||
/// type that each property is declared as. If type of an encodable property
|
||||
/// cannot be determined (e.g., it is declared as `id`), it will be omitted from
|
||||
/// the dictionary, and subclasses must provide a valid value to prevent an
|
||||
/// exception being thrown during encoding/decoding.
|
||||
// Determines the classes that are allowed to be decoded for each of the
|
||||
// receiver's properties when using <NSSecureCoding>. The values of this
|
||||
// dictionary should be NSArrays of Class objects.
|
||||
//
|
||||
// If any encodable keys (as determined by +encodingBehaviorsByPropertyKey) are
|
||||
// not present in the dictionary, an exception will be thrown during secure
|
||||
// encoding or decoding.
|
||||
//
|
||||
// Subclasses overriding this method should combine their values with those of
|
||||
// `super`.
|
||||
//
|
||||
// Returns a dictionary mapping the receiver's encodable keys (as determined by
|
||||
// +encodingBehaviorsByPropertyKey) to default allowed classes, based on the
|
||||
// type that each property is declared as. If type of an encodable property
|
||||
// cannot be determined (e.g., it is declared as `id`), it will be omitted from
|
||||
// the dictionary, and subclasses must provide a valid value to prevent an
|
||||
// exception being thrown during encoding/decoding.
|
||||
+ (NSDictionary *)allowedSecureCodingClassesByPropertyKey;
|
||||
|
||||
/// Decodes the value of the given property key from an archive.
|
||||
///
|
||||
/// By default, this method looks for a `-decode<Key>WithCoder:modelVersion:`
|
||||
/// method on the receiver, and invokes it if found.
|
||||
///
|
||||
/// If the custom method is not implemented and `coder` does not require secure
|
||||
/// coding, `-[NSCoder decodeObjectForKey:]` will be invoked with the given
|
||||
/// `key`.
|
||||
///
|
||||
/// If the custom method is not implemented and `coder` requires secure coding,
|
||||
/// `-[NSCoder decodeObjectOfClasses:forKey:]` will be invoked with the
|
||||
/// information from +allowedSecureCodingClassesByPropertyKey and the given `key`. The
|
||||
/// receiver must conform to <NSSecureCoding> for this to work correctly.
|
||||
///
|
||||
/// key - The property key to decode the value for. This argument cannot
|
||||
/// be nil.
|
||||
/// coder - The NSCoder representing the archive being decoded. This
|
||||
/// argument cannot be nil.
|
||||
/// modelVersion - The version of the original model object that was encoded.
|
||||
///
|
||||
/// Returns the decoded and boxed value, or nil if the key was not present.
|
||||
// Decodes the value of the given property key from an archive.
|
||||
//
|
||||
// By default, this method looks for a `-decode<Key>WithCoder:modelVersion:`
|
||||
// method on the receiver, and invokes it if found.
|
||||
//
|
||||
// If the custom method is not implemented and `coder` does not require secure
|
||||
// coding, `-[NSCoder decodeObjectForKey:]` will be invoked with the given
|
||||
// `key`.
|
||||
//
|
||||
// If the custom method is not implemented and `coder` requires secure coding,
|
||||
// `-[NSCoder decodeObjectOfClasses:forKey:]` will be invoked with the
|
||||
// information from +allowedSecureCodingClassesByPropertyKey and the given `key`. The
|
||||
// receiver must conform to <NSSecureCoding> for this to work correctly.
|
||||
//
|
||||
// key - The property key to decode the value for. This argument cannot
|
||||
// be nil.
|
||||
// coder - The NSCoder representing the archive being decoded. This
|
||||
// argument cannot be nil.
|
||||
// modelVersion - The version of the original model object that was encoded.
|
||||
//
|
||||
// Returns the decoded and boxed value, or nil if the key was not present.
|
||||
- (id)decodeValueForKey:(NSString *)key withCoder:(NSCoder *)coder modelVersion:(NSUInteger)modelVersion;
|
||||
|
||||
/// The version of this MTLModel subclass.
|
||||
///
|
||||
/// This version number is saved in archives so that later model changes can be
|
||||
/// made backwards-compatible with old versions.
|
||||
///
|
||||
/// Subclasses should override this method to return a higher version number
|
||||
/// whenever a breaking change is made to the model.
|
||||
///
|
||||
/// Returns 0.
|
||||
// The version of this MTLModel subclass.
|
||||
//
|
||||
// This version number is saved in archives so that later model changes can be
|
||||
// made backwards-compatible with old versions.
|
||||
//
|
||||
// Subclasses should override this method to return a higher version number
|
||||
// whenever a breaking change is made to the model.
|
||||
//
|
||||
// Returns 0.
|
||||
+ (NSUInteger)modelVersion;
|
||||
|
||||
@end
|
||||
|
||||
/// This method must be overridden to support archives created by older versions
|
||||
/// of Mantle (before the `MTLModel+NSCoding` interface existed).
|
||||
// This method must be overridden to support archives created by older versions
|
||||
// of Mantle (before the `MTLModel+NSCoding` interface existed).
|
||||
@interface MTLModel (OldArchiveSupport)
|
||||
|
||||
/// Converts an archived external representation to a dictionary suitable for
|
||||
/// passing to -initWithDictionary:.
|
||||
///
|
||||
/// externalRepresentation - The decoded external representation of the receiver.
|
||||
/// fromVersion - The model version at the time the external
|
||||
/// representation was encoded.
|
||||
///
|
||||
/// Returns nil by default, indicating that conversion failed.
|
||||
// Converts an archived external representation to a dictionary suitable for
|
||||
// passing to -initWithDictionary:.
|
||||
//
|
||||
// externalRepresentation - The decoded external representation of the receiver.
|
||||
// fromVersion - The model version at the time the external
|
||||
// representation was encoded.
|
||||
//
|
||||
// Returns nil by default, indicating that conversion failed.
|
||||
+ (NSDictionary *)dictionaryValueFromArchivedExternalRepresentation:(NSDictionary *)externalRepresentation version:(NSUInteger)fromVersion;
|
||||
|
||||
@end
|
||||
|
||||
@ -7,8 +7,8 @@
|
||||
//
|
||||
|
||||
#import "MTLModel+NSCoding.h"
|
||||
#import <Mantle/EXTRuntimeExtensions.h>
|
||||
#import <Mantle/EXTScope.h>
|
||||
#import "EXTRuntimeExtensions.h"
|
||||
#import "EXTScope.h"
|
||||
#import "MTLReflection.h"
|
||||
|
||||
// Used in archives to store the modelVersion of the archived instance.
|
||||
@ -128,10 +128,15 @@ static void verifyAllowedClassesByPropertyKey(Class modelClass) {
|
||||
|
||||
SEL selector = MTLSelectorWithCapitalizedKeyPattern("decode", key, "WithCoder:modelVersion:");
|
||||
if ([self respondsToSelector:selector]) {
|
||||
IMP imp = [self methodForSelector:selector];
|
||||
id (*function)(id, SEL, NSCoder *, NSUInteger) = (__typeof__(function))imp;
|
||||
id result = function(self, selector, coder, modelVersion);
|
||||
|
||||
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:selector]];
|
||||
invocation.target = self;
|
||||
invocation.selector = selector;
|
||||
[invocation setArgument:&coder atIndex:2];
|
||||
[invocation setArgument:&modelVersion atIndex:3];
|
||||
[invocation invoke];
|
||||
|
||||
__unsafe_unretained id result = nil;
|
||||
[invocation getReturnValue:&result];
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
@ -8,172 +8,160 @@
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
/// Defines a property's storage behavior, which affects how it will be copied,
|
||||
/// compared, and persisted.
|
||||
///
|
||||
/// MTLPropertyStorageNone - This property is not included in -description,
|
||||
/// -hash, or anything else.
|
||||
/// MTLPropertyStorageTransitory - This property is included in one-off
|
||||
/// operations like -copy and -dictionaryValue but
|
||||
/// does not affect -isEqual: or -hash.
|
||||
/// It may disappear at any time.
|
||||
/// MTLPropertyStoragePermanent - The property is included in serialization
|
||||
/// (like `NSCoding`) and equality, since it can
|
||||
/// be expected to stick around.
|
||||
// Defines a property's storage behavior, which affects how it will be copied,
|
||||
// compared, and persisted.
|
||||
//
|
||||
// MTLPropertyStorageNone - This property is not included in -description,
|
||||
// -hash, or anything else.
|
||||
// MTLPropertyStorageTransitory - This property is included in one-off
|
||||
// operations like -copy and -dictionaryValue but
|
||||
// does not affect -isEqual: or -hash.
|
||||
// It may disappear at any time.
|
||||
// MTLPropertyStoragePermanent - The property is included in serialization
|
||||
// (like `NSCoding`) and equality, since it can
|
||||
// be expected to stick around.
|
||||
typedef enum : NSUInteger {
|
||||
MTLPropertyStorageNone,
|
||||
MTLPropertyStorageTransitory,
|
||||
MTLPropertyStoragePermanent,
|
||||
} MTLPropertyStorage;
|
||||
|
||||
/// This protocol defines the minimal interface that classes need to implement to
|
||||
/// interact with Mantle adapters.
|
||||
///
|
||||
/// It is intended for scenarios where inheriting from MTLModel is not feasible.
|
||||
/// However, clients are encouraged to subclass the MTLModel class if they can.
|
||||
///
|
||||
/// Clients that wish to implement their own adapters should target classes
|
||||
/// conforming to this protocol rather than subclasses of MTLModel to ensure
|
||||
/// maximum compatibility.
|
||||
// This protocol defines the minimal interface that classes need to implement to
|
||||
// interact with Mantle adapters.
|
||||
//
|
||||
// It is intended for scenarios where inheriting from MTLModel is not feasible.
|
||||
// However, clients are encouraged to subclass the MTLModel class if they can.
|
||||
//
|
||||
// Clients that wish to implement their own adapters should target classes
|
||||
// conforming to this protocol rather than subclasses of MTLModel to ensure
|
||||
// maximum compatibility.
|
||||
@protocol MTLModel <NSObject, NSCopying>
|
||||
|
||||
/// Initializes a new instance of the receiver using key-value coding, setting
|
||||
/// the keys and values in the given dictionary.
|
||||
///
|
||||
/// dictionaryValue - Property keys and values to set on the instance. Any NSNull
|
||||
/// values will be converted to nil before being used. KVC
|
||||
/// validation methods will automatically be invoked for all of
|
||||
/// the properties given.
|
||||
/// error - If not NULL, this may be set to any error that occurs
|
||||
/// (like a KVC validation error).
|
||||
///
|
||||
/// Returns an initialized model object, or nil if validation failed.
|
||||
// Initializes a new instance of the receiver using key-value coding, setting
|
||||
// the keys and values in the given dictionary.
|
||||
//
|
||||
// dictionaryValue - Property keys and values to set on the instance. Any NSNull
|
||||
// values will be converted to nil before being used. KVC
|
||||
// validation methods will automatically be invoked for all of
|
||||
// the properties given.
|
||||
// error - If not NULL, this may be set to any error that occurs
|
||||
// (like a KVC validation error).
|
||||
//
|
||||
// Returns an initialized model object, or nil if validation failed.
|
||||
+ (instancetype)modelWithDictionary:(NSDictionary *)dictionaryValue error:(NSError **)error;
|
||||
|
||||
/// A dictionary representing the properties of the receiver.
|
||||
///
|
||||
/// Combines the values corresponding to all +propertyKeys into a dictionary,
|
||||
/// with any nil values represented by NSNull.
|
||||
///
|
||||
/// This property must never be nil.
|
||||
// A dictionary representing the properties of the receiver.
|
||||
//
|
||||
// Combines the values corresponding to all +propertyKeys into a dictionary,
|
||||
// with any nil values represented by NSNull.
|
||||
//
|
||||
// This property must never be nil.
|
||||
@property (nonatomic, copy, readonly) NSDictionary *dictionaryValue;
|
||||
|
||||
/// Initializes the receiver using key-value coding, setting the keys and values
|
||||
/// in the given dictionary.
|
||||
///
|
||||
/// Subclass implementations may override this method, calling the super
|
||||
/// implementation, in order to perform further processing and initialization
|
||||
/// after deserialization.
|
||||
///
|
||||
/// dictionaryValue - Property keys and values to set on the receiver. Any NSNull
|
||||
/// values will be converted to nil before being used. KVC
|
||||
/// validation methods will automatically be invoked for all of
|
||||
/// the properties given. If nil, this method is equivalent to
|
||||
/// -init.
|
||||
/// error - If not NULL, this may be set to any error that occurs
|
||||
/// (like a KVC validation error).
|
||||
///
|
||||
/// Returns an initialized model object, or nil if validation failed.
|
||||
// Initializes the receiver using key-value coding, setting the keys and values
|
||||
// in the given dictionary.
|
||||
//
|
||||
// dictionaryValue - Property keys and values to set on the receiver. Any NSNull
|
||||
// values will be converted to nil before being used. KVC
|
||||
// validation methods will automatically be invoked for all of
|
||||
// the properties given. If nil, this method is equivalent to
|
||||
// -init.
|
||||
// error - If not NULL, this may be set to any error that occurs
|
||||
// (like a KVC validation error).
|
||||
//
|
||||
// Returns an initialized model object, or nil if validation failed.
|
||||
- (instancetype)initWithDictionary:(NSDictionary *)dictionaryValue error:(NSError **)error;
|
||||
|
||||
/// Merges the value of the given key on the receiver with the value of the same
|
||||
/// key from the given model object, giving precedence to the other model object.
|
||||
// Merges the value of the given key on the receiver with the value of the same
|
||||
// key from the given model object, giving precedence to the other model object.
|
||||
- (void)mergeValueForKey:(NSString *)key fromModel:(id<MTLModel>)model;
|
||||
|
||||
/// Returns the keys for all @property declarations, except for `readonly`
|
||||
/// properties without ivars, or properties on MTLModel itself.
|
||||
// Returns the keys for all @property declarations, except for `readonly`
|
||||
// properties without ivars, or properties on MTLModel itself.
|
||||
+ (NSSet *)propertyKeys;
|
||||
|
||||
/// Validates the model.
|
||||
///
|
||||
/// error - If not NULL, this may be set to any error that occurs during
|
||||
/// validation
|
||||
///
|
||||
/// Returns YES if the model is valid, or NO if the validation failed.
|
||||
- (BOOL)validate:(NSError **)error;
|
||||
|
||||
@end
|
||||
|
||||
/// An abstract base class for model objects, using reflection to provide
|
||||
/// sensible default behaviors.
|
||||
///
|
||||
/// The default implementations of <NSCopying>, -hash, and -isEqual: make use of
|
||||
/// the +propertyKeys method.
|
||||
// An abstract base class for model objects, using reflection to provide
|
||||
// sensible default behaviors.
|
||||
//
|
||||
// The default implementations of <NSCopying>, -hash, and -isEqual: make use of
|
||||
// the +propertyKeys method.
|
||||
@interface MTLModel : NSObject <MTLModel>
|
||||
|
||||
/// Initializes the receiver using key-value coding, setting the keys and values
|
||||
/// in the given dictionary.
|
||||
///
|
||||
/// dictionaryValue - Property keys and values to set on the receiver. Any NSNull
|
||||
/// values will be converted to nil before being used. KVC
|
||||
/// validation methods will automatically be invoked for all of
|
||||
/// the properties given. If nil, this method is equivalent to
|
||||
/// -init.
|
||||
/// error - If not NULL, this may be set to any error that occurs
|
||||
/// (like a KVC validation error).
|
||||
///
|
||||
/// Returns an initialized model object, or nil if validation failed.
|
||||
// Initializes the receiver using key-value coding, setting the keys and values
|
||||
// in the given dictionary.
|
||||
//
|
||||
// dictionaryValue - Property keys and values to set on the receiver. Any NSNull
|
||||
// values will be converted to nil before being used. KVC
|
||||
// validation methods will automatically be invoked for all of
|
||||
// the properties given. If nil, this method is equivalent to
|
||||
// -init.
|
||||
// error - If not NULL, this may be set to any error that occurs
|
||||
// (like a KVC validation error).
|
||||
//
|
||||
// Returns an initialized model object, or nil if validation failed.
|
||||
- (instancetype)initWithDictionary:(NSDictionary *)dictionaryValue error:(NSError **)error;
|
||||
|
||||
/// Initializes the receiver with default values.
|
||||
///
|
||||
/// This is the designated initializer for this class.
|
||||
// Initializes the receiver with default values.
|
||||
//
|
||||
// This is the designated initializer for this class.
|
||||
- (instancetype)init;
|
||||
|
||||
/// By default, this method looks for a `-merge<Key>FromModel:` method on the
|
||||
/// receiver, and invokes it if found. If not found, and `model` is not nil, the
|
||||
/// value for the given key is taken from `model`.
|
||||
// By default, this method looks for a `-merge<Key>FromModel:` method on the
|
||||
// receiver, and invokes it if found. If not found, and `model` is not nil, the
|
||||
// value for the given key is taken from `model`.
|
||||
- (void)mergeValueForKey:(NSString *)key fromModel:(id<MTLModel>)model;
|
||||
|
||||
/// Merges the values of the given model object into the receiver, using
|
||||
/// -mergeValueForKey:fromModel: for each key in +propertyKeys.
|
||||
///
|
||||
/// `model` must be an instance of the receiver's class or a subclass thereof.
|
||||
// Merges the values of the given model object into the receiver, using
|
||||
// -mergeValueForKey:fromModel: for each key in +propertyKeys.
|
||||
//
|
||||
// `model` must be an instance of the receiver's class or a subclass thereof.
|
||||
- (void)mergeValuesForKeysFromModel:(id<MTLModel>)model;
|
||||
|
||||
/// The storage behavior of a given key.
|
||||
///
|
||||
/// The default implementation returns MTLPropertyStorageNone for properties that
|
||||
/// are readonly and not backed by an instance variable and
|
||||
/// MTLPropertyStoragePermanent otherwise.
|
||||
///
|
||||
/// Subclasses can use this method to prevent MTLModel from resolving circular
|
||||
/// references by returning MTLPropertyStorageTransitory.
|
||||
///
|
||||
/// Returns the storage behavior for a given key on the receiver.
|
||||
// The storage behavior of a given key.
|
||||
//
|
||||
// The default implementation returns MTLPropertyStorageNone for properties that
|
||||
// are readonly and not backed by an instance variable and
|
||||
// MTLPropertyStoragePermanent otherwise.
|
||||
//
|
||||
// Subclasses can use this method to prevent MTLModel from resolving circular
|
||||
// references by returning MTLPropertyStorageTransitory.
|
||||
//
|
||||
// Returns the storage behavior for a given key on the receiver.
|
||||
+ (MTLPropertyStorage)storageBehaviorForPropertyWithKey:(NSString *)propertyKey;
|
||||
|
||||
/// Compares the receiver with another object for equality.
|
||||
///
|
||||
/// The default implementation is equivalent to comparing all properties of both
|
||||
/// models for which +storageBehaviorForPropertyWithKey: returns
|
||||
/// MTLPropertyStoragePermanent.
|
||||
///
|
||||
/// Returns YES if the two models are considered equal, NO otherwise.
|
||||
// Compares the receiver with another object for equality.
|
||||
//
|
||||
// The default implementation is equivalent to comparing all properties of both
|
||||
// models for which +storageBehaviorForPropertyWithKey: returns
|
||||
// MTLPropertyStoragePermanent.
|
||||
//
|
||||
// Returns YES if the two models are considered equal, NO otherwise.
|
||||
- (BOOL)isEqual:(id)object;
|
||||
|
||||
/// A string that describes the contents of the receiver.
|
||||
///
|
||||
/// The default implementation is based on the receiver's class and all its
|
||||
/// properties for which +storageBehaviorForPropertyWithKey: returns
|
||||
/// MTLPropertyStoragePermanent.
|
||||
// A string that describes the contents of the receiver.
|
||||
//
|
||||
// The default implementation is based on the receiver's class and all its
|
||||
// properties for which +storageBehaviorForPropertyWithKey: returns
|
||||
// MTLPropertyStoragePermanent.
|
||||
- (NSString *)description;
|
||||
|
||||
@end
|
||||
|
||||
/// Implements validation logic for MTLModel.
|
||||
// Implements validation logic for MTLModel.
|
||||
@interface MTLModel (Validation)
|
||||
|
||||
/// Validates the model.
|
||||
///
|
||||
/// The default implementation simply invokes -validateValue:forKey:error: with
|
||||
/// all +propertyKeys and their current value. If -validateValue:forKey:error:
|
||||
/// returns a new value, the property is set to that new value.
|
||||
///
|
||||
/// error - If not NULL, this may be set to any error that occurs during
|
||||
/// validation
|
||||
///
|
||||
/// Returns YES if the model is valid, or NO if the validation failed.
|
||||
// Validates the model.
|
||||
//
|
||||
// The default implementation simply invokes -validateValue:forKey:error: with
|
||||
// all +propertyKeys and their current value. If -validateValue:forKey:error:
|
||||
// returns a new value, the property is set to that new value.
|
||||
//
|
||||
// error - If not NULL, this may be set to any error that occurs during
|
||||
// validation
|
||||
//
|
||||
// Returns YES if the model is valid, or NO if the validation failed.
|
||||
- (BOOL)validate:(NSError **)error;
|
||||
|
||||
@end
|
||||
|
||||
@ -8,9 +8,10 @@
|
||||
|
||||
#import "NSError+MTLModelException.h"
|
||||
#import "MTLModel.h"
|
||||
#import <Mantle/EXTRuntimeExtensions.h>
|
||||
#import <Mantle/EXTScope.h>
|
||||
#import "EXTRuntimeExtensions.h"
|
||||
#import "EXTScope.h"
|
||||
#import "MTLReflection.h"
|
||||
#import "MTLValidateAndSetValue.h"
|
||||
#import <objc/runtime.h>
|
||||
|
||||
// Used to cache the reflection performed in +propertyKeys.
|
||||
@ -24,50 +25,6 @@ static void *MTLModelCachedTransitoryPropertyKeysKey = &MTLModelCachedTransitory
|
||||
// property keys.
|
||||
static void *MTLModelCachedPermanentPropertyKeysKey = &MTLModelCachedPermanentPropertyKeysKey;
|
||||
|
||||
// Validates a value for an object and sets it if necessary.
|
||||
//
|
||||
// obj - The object for which the value is being validated. This value
|
||||
// must not be nil.
|
||||
// key - The name of one of `obj`s properties. This value must not be
|
||||
// nil.
|
||||
// value - The new value for the property identified by `key`.
|
||||
// forceUpdate - If set to `YES`, the value is being updated even if validating
|
||||
// it did not change it.
|
||||
// error - If not NULL, this may be set to any error that occurs during
|
||||
// validation
|
||||
//
|
||||
// Returns YES if `value` could be validated and set, or NO if an error
|
||||
// occurred.
|
||||
static BOOL MTLValidateAndSetValue(id obj, NSString *key, id value, BOOL forceUpdate, NSError **error) {
|
||||
// Mark this as being autoreleased, because validateValue may return
|
||||
// a new object to be stored in this variable (and we don't want ARC to
|
||||
// double-free or leak the old or new values).
|
||||
__autoreleasing id validatedValue = value;
|
||||
|
||||
@try {
|
||||
if (![obj validateValue:&validatedValue forKey:key error:error]) return NO;
|
||||
|
||||
if (forceUpdate || value != validatedValue) {
|
||||
[obj setValue:validatedValue forKey:key];
|
||||
}
|
||||
|
||||
return YES;
|
||||
} @catch (NSException *ex) {
|
||||
NSLog(@"*** Caught exception setting key \"%@\" : %@", key, ex);
|
||||
|
||||
// Fail fast in Debug builds.
|
||||
#if DEBUG
|
||||
@throw ex;
|
||||
#else
|
||||
if (error != NULL) {
|
||||
*error = [NSError mtl_modelErrorWithException:ex];
|
||||
}
|
||||
|
||||
return NO;
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
@interface MTLModel ()
|
||||
|
||||
// Inspects all properties of returned by +propertyKeys using
|
||||
@ -230,19 +187,9 @@ static BOOL MTLValidateAndSetValue(id obj, NSString *key, id value, BOOL forceUp
|
||||
@onExit {
|
||||
free(attributes);
|
||||
};
|
||||
|
||||
BOOL hasGetter = [self instancesRespondToSelector:attributes->getter];
|
||||
BOOL hasSetter = [self instancesRespondToSelector:attributes->setter];
|
||||
if (!attributes->dynamic && attributes->ivar == NULL && !hasGetter && !hasSetter) {
|
||||
|
||||
if (attributes->readonly && attributes->ivar == NULL) {
|
||||
return MTLPropertyStorageNone;
|
||||
} else if (attributes->readonly && attributes->ivar == NULL) {
|
||||
if ([self isEqual:MTLModel.class]) {
|
||||
return MTLPropertyStorageNone;
|
||||
} else {
|
||||
// Check superclass in case the subclass redeclares a property that
|
||||
// falls through
|
||||
return [self.superclass storageBehaviorForPropertyWithKey:propertyKey];
|
||||
}
|
||||
} else {
|
||||
return MTLPropertyStoragePermanent;
|
||||
}
|
||||
@ -262,9 +209,12 @@ static BOOL MTLValidateAndSetValue(id obj, NSString *key, id value, BOOL forceUp
|
||||
return;
|
||||
}
|
||||
|
||||
IMP imp = [self methodForSelector:selector];
|
||||
void (*function)(id, SEL, id<MTLModel>) = (__typeof__(function))imp;
|
||||
function(self, selector, model);
|
||||
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:selector]];
|
||||
invocation.target = self;
|
||||
invocation.selector = selector;
|
||||
|
||||
[invocation setArgument:&model atIndex:2];
|
||||
[invocation invoke];
|
||||
}
|
||||
|
||||
- (void)mergeValuesForKeysFromModel:(id<MTLModel>)model {
|
||||
@ -293,9 +243,7 @@ static BOOL MTLValidateAndSetValue(id obj, NSString *key, id value, BOOL forceUp
|
||||
#pragma mark NSCopying
|
||||
|
||||
- (instancetype)copyWithZone:(NSZone *)zone {
|
||||
MTLModel *copy = [[self.class allocWithZone:zone] init];
|
||||
[copy setValuesForKeysWithDictionary:self.dictionaryValue];
|
||||
return copy;
|
||||
return [[self.class allocWithZone:zone] initWithDictionary:self.dictionaryValue error:NULL];
|
||||
}
|
||||
|
||||
#pragma mark NSObject
|
||||
|
||||
@ -8,24 +8,24 @@
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
/// Creates a selector from a key and a constant string.
|
||||
///
|
||||
/// key - The key to insert into the generated selector. This key should be in
|
||||
/// its natural case.
|
||||
/// suffix - A string to append to the key as part of the selector.
|
||||
///
|
||||
/// Returns a selector, or NULL if the input strings cannot form a valid
|
||||
/// selector.
|
||||
// Creates a selector from a key and a constant string.
|
||||
//
|
||||
// key - The key to insert into the generated selector. This key should be in
|
||||
// its natural case.
|
||||
// suffix - A string to append to the key as part of the selector.
|
||||
//
|
||||
// Returns a selector, or NULL if the input strings cannot form a valid
|
||||
// selector.
|
||||
SEL MTLSelectorWithKeyPattern(NSString *key, const char *suffix) __attribute__((pure, nonnull(1, 2)));
|
||||
|
||||
/// Creates a selector from a key and a constant prefix and suffix.
|
||||
///
|
||||
/// prefix - A string to prepend to the key as part of the selector.
|
||||
/// key - The key to insert into the generated selector. This key should be in
|
||||
/// its natural case, and will have its first letter capitalized when
|
||||
/// inserted.
|
||||
/// suffix - A string to append to the key as part of the selector.
|
||||
///
|
||||
/// Returns a selector, or NULL if the input strings cannot form a valid
|
||||
/// selector.
|
||||
// Creates a selector from a key and a constant prefix and suffix.
|
||||
//
|
||||
// prefix - A string to prepend to the key as part of the selector.
|
||||
// key - The key to insert into the generated selector. This key should be in
|
||||
// its natural case, and will have its first letter capitalized when
|
||||
// inserted.
|
||||
// suffix - A string to append to the key as part of the selector.
|
||||
//
|
||||
// Returns a selector, or NULL if the input strings cannot form a valid
|
||||
// selector.
|
||||
SEL MTLSelectorWithCapitalizedKeyPattern(const char *prefix, NSString *key, const char *suffix) __attribute__((pure, nonnull(1, 2, 3)));
|
||||
|
||||
@ -8,59 +8,59 @@
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
/// The domain for errors originating from the MTLTransformerErrorHandling
|
||||
/// protocol.
|
||||
///
|
||||
/// Transformers conforming to this protocol are expected to use this error
|
||||
/// domain if the transformation fails.
|
||||
// The domain for errors originating from the MTLTransformerErrorHandling
|
||||
// protocol.
|
||||
//
|
||||
// Transformers conforming to this protocol are expected to use this error
|
||||
// domain if the transformation fails.
|
||||
extern NSString * const MTLTransformerErrorHandlingErrorDomain;
|
||||
|
||||
/// Used to indicate that the input value was illegal.
|
||||
///
|
||||
/// Transformers conforming to this protocol are expected to use this error code
|
||||
/// if the transformation fails due to an invalid input value.
|
||||
// Used to indicate that the input value was illegal.
|
||||
//
|
||||
// Transformers conforming to this protocol are expected to use this error code
|
||||
// if the transformation fails due to an invalid input value.
|
||||
extern const NSInteger MTLTransformerErrorHandlingErrorInvalidInput;
|
||||
|
||||
/// Associated with the invalid input value.
|
||||
///
|
||||
/// Transformers conforming to this protocol are expected to associate this key
|
||||
/// with the invalid input in the userInfo dictionary.
|
||||
// Associated with the invalid input value.
|
||||
//
|
||||
// Transformers conforming to this protocol are expected to associate this key
|
||||
// with the invalid input in the userInfo dictionary.
|
||||
extern NSString * const MTLTransformerErrorHandlingInputValueErrorKey;
|
||||
|
||||
/// This protocol can be implemented by NSValueTransformer subclasses to
|
||||
/// communicate errors that occur during transformation.
|
||||
// This protocol can be implemented by NSValueTransformer subclasses to
|
||||
// communicate errors that occur during transformation.
|
||||
@protocol MTLTransformerErrorHandling <NSObject>
|
||||
@required
|
||||
|
||||
/// Transforms a value, returning any error that occurred during transformation.
|
||||
///
|
||||
/// value - The value to transform.
|
||||
/// success - If not NULL, this will be set to a boolean indicating whether the
|
||||
/// transformation was successful.
|
||||
/// error - If not NULL, this may be set to an error that occurs during
|
||||
/// transforming the value.
|
||||
///
|
||||
/// Returns the result of the transformation which may be nil. Clients should
|
||||
/// inspect the success parameter to decide how to proceed with the result.
|
||||
// Transforms a value, returning any error that occurred during transformation.
|
||||
//
|
||||
// value - The value to transform.
|
||||
// success - If not NULL, this will be set to a boolean indicating whether the
|
||||
// transformation was successful.
|
||||
// error - If not NULL, this may be set to an error that occurs during
|
||||
// transforming the value.
|
||||
//
|
||||
// Returns the result of the transformation which may be nil. Clients should
|
||||
// inspect the success parameter to decide how to proceed with the result.
|
||||
- (id)transformedValue:(id)value success:(BOOL *)success error:(NSError **)error;
|
||||
|
||||
@optional
|
||||
|
||||
/// Reverse-transforms a value, returning any error that occurred during
|
||||
/// transformation.
|
||||
///
|
||||
/// Transformers conforming to this protocol are expected to implemented this
|
||||
/// method if they support reverse transformation.
|
||||
///
|
||||
/// value - The value to transform.
|
||||
/// success - If not NULL, this will be set to a boolean indicating whether the
|
||||
/// transformation was successful.
|
||||
/// error - If not NULL, this may be set to an error that occurs during
|
||||
/// transforming the value.
|
||||
///
|
||||
/// Returns the result of the reverse transformation which may be nil. Clients
|
||||
/// should inspect the success parameter to decide how to proceed with the
|
||||
/// result.
|
||||
// Reverse-transforms a value, returning any error that occurred during
|
||||
// transformation.
|
||||
//
|
||||
// Transformers conforming to this protocol are expected to implemented this
|
||||
// method if they support reverse transformation.
|
||||
//
|
||||
// value - The value to transform.
|
||||
// success - If not NULL, this will be set to a boolean indicating whether the
|
||||
// transformation was successful.
|
||||
// error - If not NULL, this may be set to an error that occurs during
|
||||
// transforming the value.
|
||||
//
|
||||
// Returns the result of the reverse transformation which may be nil. Clients
|
||||
// should inspect the success parameter to decide how to proceed with the
|
||||
// result.
|
||||
- (id)reverseTransformedValue:(id)value success:(BOOL *)success error:(NSError **)error;
|
||||
|
||||
@end
|
||||
|
||||
25
Mantle/MTLValidateAndSetValue.h
Normal file
25
Mantle/MTLValidateAndSetValue.h
Normal file
@ -0,0 +1,25 @@
|
||||
//
|
||||
// MTLValidateAndSetValue.h
|
||||
// Mantle
|
||||
//
|
||||
// Created by Robert Böhnke on 27/05/14.
|
||||
// Copyright (c) 2014 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
// Validates a value for an object and sets it if necessary.
|
||||
//
|
||||
// obj - The object for which the value is being validated. This value
|
||||
// must not be nil.
|
||||
// key - The name of one of `obj`s properties. This value must not be
|
||||
// nil.
|
||||
// value - The new value for the property identified by `key`.
|
||||
// forceUpdate - If set to `YES`, the value is being updated even if validating
|
||||
// it did not change it.
|
||||
// error - If not NULL, this may be set to any error that occurs during
|
||||
// validation
|
||||
//
|
||||
// Returns YES if `value` could be validated and set, or NO if an error
|
||||
// occurred.
|
||||
BOOL MTLValidateAndSetValue(id obj, NSString *key, id value, BOOL forceUpdate, NSError **error);
|
||||
39
Mantle/MTLValidateAndSetValue.m
Normal file
39
Mantle/MTLValidateAndSetValue.m
Normal file
@ -0,0 +1,39 @@
|
||||
//
|
||||
// MTLValidateAndSetValue.m
|
||||
// Mantle
|
||||
//
|
||||
// Created by Robert Böhnke on 27/05/14.
|
||||
// Copyright (c) 2014 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import "MTLValidateAndSetValue.h"
|
||||
|
||||
BOOL MTLValidateAndSetValue(id obj, NSString *key, id value, BOOL forceUpdate, NSError **error) {
|
||||
// Mark this as being autoreleased, because validateValue may return
|
||||
// a new object to be stored in this variable (and we don't want ARC to
|
||||
// double-free or leak the old or new values).
|
||||
__autoreleasing id validatedValue = value;
|
||||
|
||||
@try {
|
||||
if (![obj validateValue:&validatedValue forKey:key error:error]) return NO;
|
||||
|
||||
if (forceUpdate || value != validatedValue) {
|
||||
[obj setValue:validatedValue forKey:key];
|
||||
}
|
||||
|
||||
return YES;
|
||||
} @catch (NSException *ex) {
|
||||
NSLog(@"*** Caught exception setting key \"%@\" : %@", key, ex);
|
||||
|
||||
// Fail fast in Debug builds.
|
||||
#if DEBUG
|
||||
@throw ex;
|
||||
#else
|
||||
if (error != NULL) {
|
||||
*error = [NSError mtl_modelErrorWithException:ex];
|
||||
}
|
||||
|
||||
return NO;
|
||||
#endif
|
||||
}
|
||||
}
|
||||
@ -10,33 +10,33 @@
|
||||
|
||||
#import "MTLTransformerErrorHandling.h"
|
||||
|
||||
/// A block that represents a transformation.
|
||||
///
|
||||
/// value - The value to transform.
|
||||
/// success - The block must set this parameter to indicate whether the
|
||||
/// transformation was successful.
|
||||
/// MTLValueTransformer will always call this block with *success
|
||||
/// initialized to YES.
|
||||
/// error - If not NULL, this may be set to an error that occurs during
|
||||
/// transforming the value.
|
||||
///
|
||||
/// Returns the result of the transformation, which may be nil.
|
||||
// A block that represents a transformation.
|
||||
//
|
||||
// value - The value to transform.
|
||||
// success - The block must set this parameter to indicate whether the
|
||||
// transformation was successful.
|
||||
// MTLValueTransformer will always call this block with *success
|
||||
// initialized to YES.
|
||||
// error - If not NULL, this may be set to an error that occurs during
|
||||
// transforming the value.
|
||||
//
|
||||
// Returns the result of the transformation, which may be nil.
|
||||
typedef id (^MTLValueTransformerBlock)(id value, BOOL *success, NSError **error);
|
||||
|
||||
///
|
||||
/// A value transformer supporting block-based transformation.
|
||||
///
|
||||
//
|
||||
// A value transformer supporting block-based transformation.
|
||||
//
|
||||
@interface MTLValueTransformer : NSValueTransformer <MTLTransformerErrorHandling>
|
||||
|
||||
/// Returns a transformer which transforms values using the given block. Reverse
|
||||
/// transformations will not be allowed.
|
||||
// Returns a transformer which transforms values using the given block. Reverse
|
||||
// transformations will not be allowed.
|
||||
+ (instancetype)transformerUsingForwardBlock:(MTLValueTransformerBlock)transformation;
|
||||
|
||||
/// Returns a transformer which transforms values using the given block, for
|
||||
/// forward or reverse transformations.
|
||||
// Returns a transformer which transforms values using the given block, for
|
||||
// forward or reverse transformations.
|
||||
+ (instancetype)transformerUsingReversibleBlock:(MTLValueTransformerBlock)transformation;
|
||||
|
||||
/// Returns a transformer which transforms values using the given blocks.
|
||||
// Returns a transformer which transforms values using the given blocks.
|
||||
+ (instancetype)transformerUsingForwardBlock:(MTLValueTransformerBlock)forwardTransformation reverseBlock:(MTLValueTransformerBlock)reverseTransformation;
|
||||
|
||||
@end
|
||||
|
||||
@ -3,15 +3,17 @@
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>en</string>
|
||||
<string>English</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>$(EXECUTABLE_NAME)</string>
|
||||
<string>${EXECUTABLE_NAME}</string>
|
||||
<key>CFBundleIconFile</key>
|
||||
<string></string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<string>com.github.${PRODUCT_NAME:rfc1034identifier}</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>$(PRODUCT_NAME)</string>
|
||||
<string>${PRODUCT_NAME}</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>FMWK</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
@ -19,7 +21,9 @@
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>$(CURRENT_PROJECT_VERSION)</string>
|
||||
<string>1</string>
|
||||
<key>NSHumanReadableCopyright</key>
|
||||
<string>Copyright © 2012 GitHub. All rights reserved.</string>
|
||||
<key>NSPrincipalClass</key>
|
||||
<string></string>
|
||||
</dict>
|
||||
7
Mantle/Mantle-Prefix.pch
Normal file
7
Mantle/Mantle-Prefix.pch
Normal file
@ -0,0 +1,7 @@
|
||||
//
|
||||
// Prefix header for all source files of the 'Mantle' target in the 'Mantle' project
|
||||
//
|
||||
|
||||
#ifdef __OBJC__
|
||||
#import <Foundation/Foundation.h>
|
||||
#endif
|
||||
@ -6,15 +6,9 @@
|
||||
// Copyright (c) 2012 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
//! Project version number for Mantle.
|
||||
FOUNDATION_EXPORT double MantleVersionNumber;
|
||||
|
||||
//! Project version string for Mantle.
|
||||
FOUNDATION_EXPORT const unsigned char MantleVersionString[];
|
||||
|
||||
#import <Mantle/MTLJSONAdapter.h>
|
||||
#import <Mantle/MTLManagedObject.h>
|
||||
#import <Mantle/MTLManagedObjectAdapter.h>
|
||||
#import <Mantle/MTLModel.h>
|
||||
#import <Mantle/MTLModel+NSCoding.h>
|
||||
#import <Mantle/MTLValueTransformer.h>
|
||||
|
||||
@ -10,19 +10,19 @@
|
||||
|
||||
@interface NSArray (MTLManipulationAdditions)
|
||||
|
||||
/// The first object in the array or nil if the array is empty.
|
||||
/// Forwards to `firstObject` which has been first declared in iOS7, but works with iOS4/10.6.
|
||||
// The first object in the array or nil if the array is empty.
|
||||
// Forwards to `firstObject` which has been first declared in iOS7, but works with iOS4/10.6.
|
||||
@property (nonatomic, readonly, strong) id mtl_firstObject;
|
||||
|
||||
/// Returns a new array without all instances of the given object.
|
||||
// Returns a new array without all instances of the given object.
|
||||
- (NSArray *)mtl_arrayByRemovingObject:(id)object;
|
||||
|
||||
/// Returns a new array without the first object. If the array is empty, it
|
||||
/// returns the empty array.
|
||||
// Returns a new array without the first object. If the array is empty, it
|
||||
// returns the empty array.
|
||||
- (NSArray *)mtl_arrayByRemovingFirstObject;
|
||||
|
||||
/// Returns a new array without the last object. If the array is empty, it
|
||||
/// returns the empty array.
|
||||
// Returns a new array without the last object. If the array is empty, it
|
||||
// returns the empty array.
|
||||
- (NSArray *)mtl_arrayByRemovingLastObject;
|
||||
|
||||
@end
|
||||
|
||||
@ -10,18 +10,18 @@
|
||||
|
||||
@interface NSDictionary (MTLJSONKeyPath)
|
||||
|
||||
/// Looks up the value of a key path in the receiver.
|
||||
///
|
||||
/// JSONKeyPath - The key path that should be resolved. Every element along this
|
||||
/// key path needs to be an instance of NSDictionary for the
|
||||
/// resolving to be successful.
|
||||
/// success - If not NULL, this will be set to a boolean indicating whether
|
||||
/// the key path was resolved successfully.
|
||||
/// error - If not NULL, this may be set to an error that occurs during
|
||||
/// resolving the value.
|
||||
///
|
||||
/// Returns the value for the key path which may be nil. Clients should inspect
|
||||
/// the success parameter to decide how to proceed with the result.
|
||||
// Looks up the value of a key path in the receiver.
|
||||
//
|
||||
// JSONKeyPath - The key path that should be resolved. Every element along this
|
||||
// key path needs to be an instance of NSDictionary for the
|
||||
// resolving to be successful.
|
||||
// success - If not NULL, this will be set to a boolean indicating whether
|
||||
// the key path was resolved successfully.
|
||||
// error - If not NULL, this may be set to an error that occurs during
|
||||
// resolving the value.
|
||||
//
|
||||
// Returns the value for the key path which may be nil. Clients should inspect
|
||||
// the success parameter to decide how to proceed with the result.
|
||||
- (id)mtl_valueForJSONKeyPath:(NSString *)JSONKeyPath success:(BOOL *)success error:(NSError **)error;
|
||||
|
||||
@end
|
||||
|
||||
@ -10,22 +10,16 @@
|
||||
|
||||
@interface NSDictionary (MTLManipulationAdditions)
|
||||
|
||||
/// Merges the keys and values from the given dictionary into the receiver. If
|
||||
/// both the receiver and `dictionary` have a given key, the value from
|
||||
/// `dictionary` is used.
|
||||
///
|
||||
/// Returns a new dictionary containing the entries of the receiver combined with
|
||||
/// those of `dictionary`.
|
||||
// Merges the keys and values from the given dictionary into the receiver. If
|
||||
// both the receiver and `dictionary` have a given key, the value from
|
||||
// `dictionary` is used.
|
||||
//
|
||||
// Returns a new dictionary containing the entries of the receiver combined with
|
||||
// those of `dictionary`.
|
||||
- (NSDictionary *)mtl_dictionaryByAddingEntriesFromDictionary:(NSDictionary *)dictionary;
|
||||
|
||||
/// Creates a new dictionary with all the entries for the given keys removed from
|
||||
/// the receiver.
|
||||
- (NSDictionary *)mtl_dictionaryByRemovingValuesForKeys:(NSArray *)keys;
|
||||
|
||||
@end
|
||||
|
||||
@interface NSDictionary (MTLManipulationAdditions_Deprecated)
|
||||
|
||||
- (NSDictionary *)mtl_dictionaryByRemovingEntriesWithKeys:(NSSet *)keys __attribute__((deprecated("Replaced by -mtl_dictionaryByRemovingValuesForKeys:")));
|
||||
// Creates a new dictionary with all the entries for the given keys removed from
|
||||
// the receiver.
|
||||
- (NSDictionary *)mtl_dictionaryByRemovingEntriesWithKeys:(NSArray *)keys;
|
||||
|
||||
@end
|
||||
|
||||
@ -16,23 +16,10 @@
|
||||
return result;
|
||||
}
|
||||
|
||||
- (NSDictionary *)mtl_dictionaryByRemovingValuesForKeys:(NSArray *)keys {
|
||||
- (NSDictionary *)mtl_dictionaryByRemovingEntriesWithKeys:(NSArray *)keys {
|
||||
NSMutableDictionary *result = [self mutableCopy];
|
||||
[result removeObjectsForKeys:keys];
|
||||
return result;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation NSDictionary (MTLManipulationAdditions_Deprecated)
|
||||
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wdeprecated"
|
||||
|
||||
- (NSDictionary *)mtl_dictionaryByRemovingEntriesWithKeys:(NSSet *)keys {
|
||||
return [self mtl_dictionaryByRemovingValuesForKeys:keys.allObjects];
|
||||
}
|
||||
|
||||
#pragma clang diagnostic pop
|
||||
|
||||
@end
|
||||
|
||||
@ -10,12 +10,12 @@
|
||||
|
||||
@interface NSDictionary (MTLMappingAdditions)
|
||||
|
||||
/// Creates an identity mapping for serialization.
|
||||
///
|
||||
/// class - A subclass of MTLModel.
|
||||
///
|
||||
/// Returns a dictionary that maps all properties of the given class to
|
||||
/// themselves.
|
||||
+ (NSDictionary *)mtl_identityPropertyMapWithModel:(Class)modelClass;
|
||||
// Creates an identity mapping for serialization.
|
||||
//
|
||||
// class - A subclass of MTLModel.
|
||||
//
|
||||
// Returns a dictionary that maps all properties of the given class to
|
||||
// themselves.
|
||||
+ (NSDictionary *)mtl_identityPropertyMapWithModel:(Class)class;
|
||||
|
||||
@end
|
||||
|
||||
@ -12,10 +12,10 @@
|
||||
|
||||
@implementation NSDictionary (MTLMappingAdditions)
|
||||
|
||||
+ (NSDictionary *)mtl_identityPropertyMapWithModel:(Class)modelClass {
|
||||
NSCParameterAssert([modelClass conformsToProtocol:@protocol(MTLModel)]);
|
||||
+ (NSDictionary *)mtl_identityPropertyMapWithModel:(Class)class {
|
||||
NSCParameterAssert([class isSubclassOfClass:MTLModel.class]);
|
||||
|
||||
NSArray *propertyKeys = [modelClass propertyKeys].allObjects;
|
||||
NSArray *propertyKeys = [class propertyKeys].allObjects;
|
||||
|
||||
return [NSDictionary dictionaryWithObjects:propertyKeys forKeys:propertyKeys];
|
||||
}
|
||||
|
||||
@ -10,14 +10,14 @@
|
||||
|
||||
@interface NSError (MTLModelException)
|
||||
|
||||
/// Creates a new error for an exception that occurred during updating an
|
||||
/// MTLModel.
|
||||
///
|
||||
/// exception - The exception that was thrown while updating the model.
|
||||
/// This argument must not be nil.
|
||||
///
|
||||
/// Returns an error that takes its localized description and failure reason
|
||||
/// from the exception.
|
||||
// Creates a new error for an exception that occured during updating an
|
||||
// MTLModel.
|
||||
//
|
||||
// exception - The exception that was thrown while updating the model.
|
||||
// This argument must not be nil.
|
||||
//
|
||||
// Returns an error that takes its localized description and failure reason
|
||||
// from the exception.
|
||||
+ (instancetype)mtl_modelErrorWithException:(NSException *)exception;
|
||||
|
||||
@end
|
||||
|
||||
@ -11,5 +11,5 @@
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
/// Returns whether both objects are identical or equal via -isEqual:
|
||||
// Returns whether both objects are identical or equal via -isEqual:
|
||||
BOOL MTLEqualObjects(id obj1, id obj2);
|
||||
|
||||
@ -10,12 +10,12 @@
|
||||
|
||||
@interface NSValueTransformer (MTLInversionAdditions)
|
||||
|
||||
/// Flips the direction of the receiver's transformation, such that
|
||||
/// -transformedValue: will become -reverseTransformedValue:, and vice-versa.
|
||||
///
|
||||
/// The receiver must allow reverse transformation.
|
||||
///
|
||||
/// Returns an inverted transformer.
|
||||
// Flips the direction of the receiver's transformation, such that
|
||||
// -transformedValue: will become -reverseTransformedValue:, and vice-versa.
|
||||
//
|
||||
// The receiver must allow reverse transformation.
|
||||
//
|
||||
// Returns an inverted transformer.
|
||||
- (NSValueTransformer *)mtl_invertedTransformer;
|
||||
|
||||
@end
|
||||
|
||||
@ -10,109 +10,88 @@
|
||||
|
||||
#import "MTLTransformerErrorHandling.h"
|
||||
|
||||
/// The name for a value transformer that converts strings into URLs and back.
|
||||
// The name for a value transformer that converts strings into URLs and back.
|
||||
extern NSString * const MTLURLValueTransformerName;
|
||||
|
||||
/// The name for a value transformer that converts strings into NSUUIDs and back.
|
||||
extern NSString * const MTLUUIDValueTransformerName;
|
||||
|
||||
/// Ensure an NSNumber is backed by __NSCFBoolean/CFBooleanRef
|
||||
///
|
||||
/// NSJSONSerialization, and likely other serialization libraries, ordinarily
|
||||
/// serialize NSNumbers as numbers, and thus booleans would be serialized as
|
||||
/// 0/1. The exception is when the NSNumber is backed by __NSCFBoolean, which,
|
||||
/// though very much an implementation detail, is detected and serialized as a
|
||||
/// proper boolean.
|
||||
// Ensure an NSNumber is backed by __NSCFBoolean/CFBooleanRef
|
||||
//
|
||||
// NSJSONSerialization, and likely other serialization libraries, ordinarily
|
||||
// serialize NSNumbers as numbers, and thus booleans would be serialized as
|
||||
// 0/1. The exception is when the NSNumber is backed by __NSCFBoolean, which,
|
||||
// though very much an implementation detail, is detected and serialized as a
|
||||
// proper boolean.
|
||||
extern NSString * const MTLBooleanValueTransformerName;
|
||||
|
||||
@interface NSValueTransformer (MTLPredefinedTransformerAdditions)
|
||||
|
||||
/// An optionally reversible transformer which applies the given transformer to
|
||||
/// each element of an array.
|
||||
///
|
||||
/// transformer - The transformer to apply to each element. If the transformer
|
||||
/// is reversible, the transformer returned by this method will be
|
||||
/// reversible. This argument must not be nil.
|
||||
///
|
||||
/// Returns a transformer which applies a transformation to each element of an
|
||||
/// array.
|
||||
// Creates a reversible transformer to convert a JSON dictionary into a MTLModel
|
||||
// object, and vice-versa.
|
||||
//
|
||||
// modelClass - The MTLModel subclass to attempt to parse from the JSON. This
|
||||
// class must conform to <MTLJSONSerializing>. This argument must
|
||||
// not be nil.
|
||||
//
|
||||
// Returns a reversible transformer which uses MTLJSONAdapter for transforming
|
||||
// values back and forth.
|
||||
+ (NSValueTransformer<MTLTransformerErrorHandling> *)mtl_JSONDictionaryTransformerWithModelClass:(Class)modelClass;
|
||||
|
||||
// Creates a reversible transformer to convert an array of JSON dictionaries
|
||||
// into an array of MTLModel objects, and vice-versa.
|
||||
//
|
||||
// modelClass - The MTLModel subclass to attempt to parse from each JSON
|
||||
// dictionary. This class must conform to <MTLJSONSerializing>.
|
||||
// This argument must not be nil.
|
||||
//
|
||||
// Returns a reversible transformer which uses MTLJSONAdapter for transforming
|
||||
// array elements back and forth.
|
||||
+ (NSValueTransformer<MTLTransformerErrorHandling> *)mtl_JSONArrayTransformerWithModelClass:(Class)modelClass;
|
||||
|
||||
// An optionally reversible transformer which applies the given transformer to
|
||||
// each element of an array.
|
||||
//
|
||||
// transformer - The transformer to apply to each element. If the transformer
|
||||
// is reversible, the transformer returned by this method will be
|
||||
// reversible. This argument must not be nil.
|
||||
//
|
||||
// Returns a transformer which applies a transformation to each element of an
|
||||
// array.
|
||||
+ (NSValueTransformer<MTLTransformerErrorHandling> *)mtl_arrayMappingTransformerWithTransformer:(NSValueTransformer *)transformer;
|
||||
|
||||
/// A reversible value transformer to transform between the keys and objects of a
|
||||
/// dictionary.
|
||||
///
|
||||
/// dictionary - The dictionary whose keys and values should be
|
||||
/// transformed between. This argument must not be nil.
|
||||
/// defaultValue - The result to fall back to, in case no key matching the
|
||||
/// input value was found during a forward transformation.
|
||||
/// reverseDefaultValue - The result to fall back to, in case no value matching
|
||||
/// the input value was found during a reverse
|
||||
/// transformation.
|
||||
///
|
||||
/// Can for example be used for transforming between enum values and their string
|
||||
/// representation.
|
||||
///
|
||||
/// NSValueTransformer *valueTransformer = [NSValueTransformer mtl_valueMappingTransformerWithDictionary:@{
|
||||
/// @"foo": @(EnumDataTypeFoo),
|
||||
/// @"bar": @(EnumDataTypeBar),
|
||||
/// } defaultValue: @(EnumDataTypeUndefined) reverseDefaultValue: @"undefined"];
|
||||
///
|
||||
/// Returns a transformer which will map from keys to objects for forward
|
||||
/// transformations, and from objects to keys for reverse transformations.
|
||||
// A reversible value transformer to transform between the keys and objects of a
|
||||
// dictionary.
|
||||
//
|
||||
// dictionary - The dictionary whose keys and values should be
|
||||
// transformed between. This argument must not be nil.
|
||||
// defaultValue - The result to fall back to, in case no key matching the
|
||||
// input value was found during a forward transformation.
|
||||
// reverseDefaultValue - The result to fall back to, in case no value matching
|
||||
// the input value was found during a reverse
|
||||
// transformation.
|
||||
//
|
||||
// Can for example be used for transforming between enum values and their string
|
||||
// representation.
|
||||
//
|
||||
// NSValueTransformer *valueTransformer = [NSValueTransformer mtl_valueMappingTransformerWithDictionary:@{
|
||||
// @"foo": @(EnumDataTypeFoo),
|
||||
// @"bar": @(EnumDataTypeBar),
|
||||
// } defaultValue: @(EnumDataTypeUndefined) reverseDefaultValue: @"undefined"];
|
||||
//
|
||||
// Returns a transformer which will map from keys to objects for forward
|
||||
// transformations, and from objects to keys for reverse transformations.
|
||||
+ (NSValueTransformer<MTLTransformerErrorHandling> *)mtl_valueMappingTransformerWithDictionary:(NSDictionary *)dictionary defaultValue:(id)defaultValue reverseDefaultValue:(id)reverseDefaultValue;
|
||||
|
||||
/// Returns a value transformer created by calling
|
||||
/// `+mtl_valueMappingTransformerWithDictionary:defaultValue:reverseDefaultValue:`
|
||||
/// with a default value of `nil` and a reverse default value of `nil`.
|
||||
// Returns a value transformer created by calling
|
||||
// `+mtl_valueMappingTransformerWithDictionary:defaultValue:reverseDefaultValue:`
|
||||
// with a default value of `nil` and a reverse default value of `nil`.
|
||||
+ (NSValueTransformer<MTLTransformerErrorHandling> *)mtl_valueMappingTransformerWithDictionary:(NSDictionary *)dictionary;
|
||||
|
||||
/// A reversible value transformer to transform between a date and its string
|
||||
/// representation
|
||||
///
|
||||
/// dateFormat - The date format used by the date formatter (http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Field_Symbol_Table)
|
||||
/// calendar - The calendar used by the date formatter
|
||||
/// locale - The locale used by the date formatter
|
||||
/// timeZone - The time zone used by the date formatter
|
||||
///
|
||||
/// Returns a transformer which will map from strings to dates for forward
|
||||
/// transformations, and from dates to strings for reverse transformations.
|
||||
+ (NSValueTransformer<MTLTransformerErrorHandling> *)mtl_dateTransformerWithDateFormat:(NSString *)dateFormat calendar:(NSCalendar *)calendar locale:(NSLocale *)locale timeZone:(NSTimeZone *)timeZone defaultDate:(NSDate *)defaultDate;
|
||||
|
||||
/// Returns a value transformer created by calling
|
||||
/// `+mtl_dateTransformerWithDateFormat:calendar:locale:timeZone:defaultDate:`
|
||||
/// with a calendar, locale, time zone and default date of `nil`.
|
||||
+ (NSValueTransformer<MTLTransformerErrorHandling> *)mtl_dateTransformerWithDateFormat:(NSString *)dateFormat locale:(NSLocale *)locale;
|
||||
|
||||
/// A reversible value transformer to transform between a number and its string
|
||||
/// representation
|
||||
///
|
||||
/// numberStyle - The number style used by the number formatter
|
||||
///
|
||||
/// Returns a transformer which will map from strings to numbers for forward
|
||||
/// transformations, and from numbers to strings for reverse transformations.
|
||||
+ (NSValueTransformer<MTLTransformerErrorHandling> *)mtl_numberTransformerWithNumberStyle:(NSNumberFormatterStyle)numberStyle locale:(NSLocale *)locale;
|
||||
|
||||
/// A reversible value transformer to transform between an object and its string
|
||||
/// representation
|
||||
///
|
||||
/// formatter - The formatter used to perform the transformation
|
||||
/// objectClass - The class of object that the formatter operates on
|
||||
///
|
||||
/// Returns a transformer which will map from strings to objects for forward
|
||||
/// transformations, and from objects to strings for reverse transformations.
|
||||
+ (NSValueTransformer<MTLTransformerErrorHandling> *)mtl_transformerWithFormatter:(NSFormatter *)formatter forObjectClass:(Class)objectClass;
|
||||
|
||||
/// A value transformer that errors if the transformed value are not of the given
|
||||
/// class.
|
||||
///
|
||||
/// class - The expected class. This argument must not be nil.
|
||||
///
|
||||
/// Returns a transformer which will return an error if the transformed in value
|
||||
/// is not a member of class. Otherwise, the value is simply passed through.
|
||||
+ (NSValueTransformer<MTLTransformerErrorHandling> *)mtl_validatingTransformerForClass:(Class)modelClass;
|
||||
|
||||
+ (NSValueTransformer<MTLTransformerErrorHandling> *)mtl_JSONDictionaryTransformerWithModelClass:(Class)modelClass __attribute__((deprecated("Replaced by +[MTLJSONAdapter dictionaryTransformerWithModelClass:]")));
|
||||
|
||||
+ (NSValueTransformer<MTLTransformerErrorHandling> *)mtl_JSONArrayTransformerWithModelClass:(Class)modelClass __attribute__((deprecated("Replaced by +[MTLJSONAdapter arrayTransformerWithModelClass:]")));
|
||||
// A value transformer that errors if the transformed value are not of the given
|
||||
// class.
|
||||
//
|
||||
// class - The expected class. This argument must not be nil.
|
||||
//
|
||||
// Returns a transformer which will return an error if the transformed in value
|
||||
// is not a member of class. Otherwise, the value is simply passed through.
|
||||
+ (NSValueTransformer<MTLTransformerErrorHandling> *)mtl_validatingTransformerForClass:(Class)class;
|
||||
|
||||
@end
|
||||
|
||||
@ -12,7 +12,6 @@
|
||||
#import "MTLValueTransformer.h"
|
||||
|
||||
NSString * const MTLURLValueTransformerName = @"MTLURLValueTransformerName";
|
||||
NSString * const MTLUUIDValueTransformerName = @"MTLUUIDValueTransformerName";
|
||||
NSString * const MTLBooleanValueTransformerName = @"MTLBooleanValueTransformerName";
|
||||
|
||||
@implementation NSValueTransformer (MTLPredefinedTransformerAdditions)
|
||||
@ -78,59 +77,6 @@ NSString * const MTLBooleanValueTransformerName = @"MTLBooleanValueTransformerNa
|
||||
|
||||
[NSValueTransformer setValueTransformer:URLValueTransformer forName:MTLURLValueTransformerName];
|
||||
|
||||
MTLValueTransformer *UUIDValueTransformer = [MTLValueTransformer
|
||||
transformerUsingForwardBlock:^id(NSString *string, BOOL *success, NSError **error) {
|
||||
if (string == nil) return nil;
|
||||
|
||||
if (![string isKindOfClass:NSString.class]) {
|
||||
if (error) {
|
||||
NSDictionary *userInfo = @{
|
||||
NSLocalizedDescriptionKey: NSLocalizedString(@"Could not convert string to UUID", @""),
|
||||
NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:NSLocalizedString(@"Expected an NSString, got: %@.", @""), string],
|
||||
MTLTransformerErrorHandlingInputValueErrorKey : string
|
||||
};
|
||||
*error = [NSError errorWithDomain:MTLTransformerErrorHandlingErrorDomain code:MTLTransformerErrorHandlingErrorInvalidInput userInfo:userInfo];
|
||||
}
|
||||
*success = NO;
|
||||
return nil;
|
||||
}
|
||||
|
||||
NSUUID *result = [[NSUUID alloc] initWithUUIDString:string];
|
||||
|
||||
if (result == nil) {
|
||||
if (error) {
|
||||
NSDictionary *userInfo = @{
|
||||
NSLocalizedDescriptionKey: NSLocalizedString(@"Could not convert string to UUID", @""),
|
||||
NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:NSLocalizedString(@"Input UUID string %@ was malformed", @""), string],
|
||||
MTLTransformerErrorHandlingInputValueErrorKey : string
|
||||
};
|
||||
*error = [NSError errorWithDomain:MTLTransformerErrorHandlingErrorDomain code:MTLTransformerErrorHandlingErrorInvalidInput userInfo:userInfo];
|
||||
}
|
||||
*success = NO;
|
||||
return nil;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
reverseBlock:^id(NSUUID *uuid, BOOL *success, NSError **error) {
|
||||
if (uuid == nil) return nil;
|
||||
|
||||
if (![uuid isKindOfClass:NSUUID.class]) {
|
||||
if (error != NULL) {
|
||||
NSDictionary *userInfo = @{NSLocalizedDescriptionKey: NSLocalizedString(@"Could not convert UUID to string", @""),
|
||||
NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:NSLocalizedString(@"Expected an NSUUID, got: %@.", @""), uuid],
|
||||
MTLTransformerErrorHandlingInputValueErrorKey : uuid};
|
||||
*error = [NSError errorWithDomain:MTLTransformerErrorHandlingErrorDomain code:MTLTransformerErrorHandlingErrorInvalidInput userInfo:userInfo];
|
||||
}
|
||||
*success = NO;
|
||||
return nil;
|
||||
}
|
||||
|
||||
return uuid.UUIDString;
|
||||
}];
|
||||
|
||||
[NSValueTransformer setValueTransformer:UUIDValueTransformer forName:MTLUUIDValueTransformerName];
|
||||
|
||||
MTLValueTransformer *booleanValueTransformer = [MTLValueTransformer
|
||||
transformerUsingReversibleBlock:^ id (NSNumber *boolean, BOOL *success, NSError **error) {
|
||||
if (boolean == nil) return nil;
|
||||
@ -157,6 +103,57 @@ NSString * const MTLBooleanValueTransformerName = @"MTLBooleanValueTransformerNa
|
||||
|
||||
#pragma mark Customizable Transformers
|
||||
|
||||
+ (NSValueTransformer<MTLTransformerErrorHandling> *)mtl_JSONDictionaryTransformerWithModelClass:(Class)modelClass {
|
||||
NSParameterAssert([modelClass isSubclassOfClass:MTLModel.class]);
|
||||
NSParameterAssert([modelClass conformsToProtocol:@protocol(MTLJSONSerializing)]);
|
||||
|
||||
return [MTLValueTransformer
|
||||
transformerUsingForwardBlock:^ id (id JSONDictionary, BOOL *success, NSError **error) {
|
||||
if (JSONDictionary == nil) return nil;
|
||||
|
||||
if (![JSONDictionary isKindOfClass:NSDictionary.class]) {
|
||||
if (error != NULL) {
|
||||
NSDictionary *userInfo = @{
|
||||
NSLocalizedDescriptionKey: NSLocalizedString(@"Could not convert JSON dictionary to model object", @""),
|
||||
NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:NSLocalizedString(@"Expected an NSDictionary, got: %@", @""), JSONDictionary],
|
||||
MTLTransformerErrorHandlingInputValueErrorKey : JSONDictionary
|
||||
};
|
||||
|
||||
*error = [NSError errorWithDomain:MTLTransformerErrorHandlingErrorDomain code:MTLTransformerErrorHandlingErrorInvalidInput userInfo:userInfo];
|
||||
}
|
||||
*success = NO;
|
||||
return nil;
|
||||
}
|
||||
|
||||
return [MTLJSONAdapter modelOfClass:modelClass fromJSONDictionary:JSONDictionary error:error];
|
||||
}
|
||||
reverseBlock:^ id (id model, BOOL *success, NSError **error) {
|
||||
if (model == nil) return nil;
|
||||
|
||||
if (![model isKindOfClass:MTLModel.class] || ![model conformsToProtocol:@protocol(MTLJSONSerializing)]) {
|
||||
if (error != NULL) {
|
||||
NSDictionary *userInfo = @{
|
||||
NSLocalizedDescriptionKey: NSLocalizedString(@"Could not convert model object to JSON dictionary", @""),
|
||||
NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:NSLocalizedString(@"Expected a MTLModel object conforming to <MTLJSONSerializing>, got: %@.", @""), model],
|
||||
MTLTransformerErrorHandlingInputValueErrorKey : model
|
||||
};
|
||||
|
||||
*error = [NSError errorWithDomain:MTLTransformerErrorHandlingErrorDomain code:MTLTransformerErrorHandlingErrorInvalidInput userInfo:userInfo];
|
||||
}
|
||||
*success = NO;
|
||||
return nil;
|
||||
}
|
||||
|
||||
return [MTLJSONAdapter JSONDictionaryFromModel:model error:error];
|
||||
}];
|
||||
}
|
||||
|
||||
+ (NSValueTransformer<MTLTransformerErrorHandling> *)mtl_JSONArrayTransformerWithModelClass:(Class)modelClass {
|
||||
id<MTLTransformerErrorHandling> dictionaryTransformer = [self mtl_JSONDictionaryTransformerWithModelClass:modelClass];
|
||||
|
||||
return [self mtl_arrayMappingTransformerWithTransformer:dictionaryTransformer];
|
||||
}
|
||||
|
||||
+ (NSValueTransformer<MTLTransformerErrorHandling> *)mtl_arrayMappingTransformerWithTransformer:(NSValueTransformer *)transformer {
|
||||
NSParameterAssert(transformer != nil);
|
||||
|
||||
@ -241,7 +238,6 @@ NSString * const MTLBooleanValueTransformerName = @"MTLBooleanValueTransformerNa
|
||||
index++;
|
||||
if (value == NSNull.null) {
|
||||
[transformedValues addObject:NSNull.null];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
@ -282,17 +278,17 @@ NSString * const MTLBooleanValueTransformerName = @"MTLBooleanValueTransformerNa
|
||||
}
|
||||
}
|
||||
|
||||
+ (NSValueTransformer<MTLTransformerErrorHandling> *)mtl_validatingTransformerForClass:(Class)modelClass {
|
||||
NSParameterAssert(modelClass != nil);
|
||||
+ (NSValueTransformer<MTLTransformerErrorHandling> *)mtl_validatingTransformerForClass:(Class)class {
|
||||
NSParameterAssert(class != nil);
|
||||
|
||||
return [MTLValueTransformer transformerUsingForwardBlock:^ id (id value, BOOL *success, NSError **error) {
|
||||
if (value != nil && ![value isKindOfClass:modelClass]) {
|
||||
if (value != nil && ![value isKindOfClass:class]) {
|
||||
if (error != NULL) {
|
||||
NSDictionary *userInfo = @{
|
||||
NSLocalizedDescriptionKey: NSLocalizedString(@"Value did not match expected type", @""),
|
||||
NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:NSLocalizedString(@"Expected %1$@ to be of class %2$@ but got %3$@", @""), value, modelClass, [value class]],
|
||||
MTLTransformerErrorHandlingInputValueErrorKey : value
|
||||
};
|
||||
NSLocalizedDescriptionKey: NSLocalizedString(@"Value did not match expected type", @""),
|
||||
NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:NSLocalizedString(@"Expected %1$@ to be of class %2$@", @""), value, class],
|
||||
MTLTransformerErrorHandlingInputValueErrorKey : value
|
||||
};
|
||||
|
||||
*error = [NSError errorWithDomain:MTLTransformerErrorHandlingErrorDomain code:MTLTransformerErrorHandlingErrorInvalidInput userInfo:userInfo];
|
||||
}
|
||||
@ -329,119 +325,4 @@ NSString * const MTLBooleanValueTransformerName = @"MTLBooleanValueTransformerNa
|
||||
return [self mtl_valueMappingTransformerWithDictionary:dictionary defaultValue:nil reverseDefaultValue:nil];
|
||||
}
|
||||
|
||||
+ (NSValueTransformer<MTLTransformerErrorHandling> *)mtl_dateTransformerWithDateFormat:(NSString *)dateFormat calendar:(NSCalendar *)calendar locale:(NSLocale *)locale timeZone:(NSTimeZone *)timeZone defaultDate:(NSDate *)defaultDate {
|
||||
NSParameterAssert(dateFormat.length);
|
||||
|
||||
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
|
||||
dateFormatter.dateFormat = dateFormat;
|
||||
dateFormatter.calendar = calendar;
|
||||
dateFormatter.locale = locale;
|
||||
dateFormatter.timeZone = timeZone;
|
||||
dateFormatter.defaultDate = defaultDate;
|
||||
|
||||
return [NSValueTransformer mtl_transformerWithFormatter:dateFormatter forObjectClass:NSDate.class];
|
||||
}
|
||||
|
||||
|
||||
+ (NSValueTransformer<MTLTransformerErrorHandling> *)mtl_dateTransformerWithDateFormat:(NSString *)dateFormat locale:(NSLocale *)locale {
|
||||
return [self mtl_dateTransformerWithDateFormat:dateFormat calendar:nil locale:locale timeZone:nil defaultDate:nil];
|
||||
}
|
||||
|
||||
+ (NSValueTransformer<MTLTransformerErrorHandling> *)mtl_numberTransformerWithNumberStyle:(NSNumberFormatterStyle)numberStyle locale:(NSLocale *)locale {
|
||||
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
|
||||
numberFormatter.numberStyle = numberStyle;
|
||||
numberFormatter.locale = locale;
|
||||
|
||||
return [self mtl_transformerWithFormatter:numberFormatter forObjectClass:NSNumber.class];
|
||||
}
|
||||
|
||||
+ (NSValueTransformer<MTLTransformerErrorHandling> *)mtl_transformerWithFormatter:(NSFormatter *)formatter forObjectClass:(Class)objectClass {
|
||||
NSParameterAssert(formatter != nil);
|
||||
NSParameterAssert(objectClass != nil);
|
||||
return [MTLValueTransformer
|
||||
transformerUsingForwardBlock:^ id (NSString *str, BOOL *success, NSError *__autoreleasing *error) {
|
||||
if (str == nil) return nil;
|
||||
|
||||
if (![str isKindOfClass:NSString.class]) {
|
||||
if (error != NULL) {
|
||||
NSDictionary *userInfo = @{
|
||||
NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedString(@"Could not convert string to %@", @""), objectClass],
|
||||
NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:NSLocalizedString(@"Expected an NSString as input, got: %@.", @""), str],
|
||||
MTLTransformerErrorHandlingInputValueErrorKey : str
|
||||
};
|
||||
|
||||
*error = [NSError errorWithDomain:MTLTransformerErrorHandlingErrorDomain code:MTLTransformerErrorHandlingErrorInvalidInput userInfo:userInfo];
|
||||
}
|
||||
*success = NO;
|
||||
return nil;
|
||||
}
|
||||
|
||||
id object = nil;
|
||||
NSString *errorDescription = nil;
|
||||
*success = [formatter getObjectValue:&object forString:str errorDescription:&errorDescription];
|
||||
|
||||
if (errorDescription != nil) {
|
||||
if (error != NULL) {
|
||||
NSDictionary *userInfo = @{
|
||||
NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedString(@"Could not convert string to %@", @""), objectClass],
|
||||
NSLocalizedFailureReasonErrorKey: errorDescription,
|
||||
MTLTransformerErrorHandlingInputValueErrorKey : str
|
||||
};
|
||||
|
||||
*error = [NSError errorWithDomain:MTLTransformerErrorHandlingErrorDomain code:MTLTransformerErrorHandlingErrorInvalidInput userInfo:userInfo];
|
||||
}
|
||||
*success = NO;
|
||||
return nil;
|
||||
}
|
||||
|
||||
if (![object isKindOfClass:objectClass]) {
|
||||
if (error != NULL) {
|
||||
NSDictionary *userInfo = @{
|
||||
NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedString(@"Could not convert string to %@", @""), objectClass],
|
||||
NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:NSLocalizedString(@"Expected an %@ as output from the formatter, got: %@.", @""), objectClass, object],
|
||||
};
|
||||
|
||||
*error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFormattingError userInfo:userInfo];
|
||||
}
|
||||
*success = NO;
|
||||
return nil;
|
||||
}
|
||||
|
||||
return object;
|
||||
} reverseBlock:^id(id object, BOOL *success, NSError *__autoreleasing *error) {
|
||||
if (object == nil) return nil;
|
||||
|
||||
if (![object isKindOfClass:objectClass]) {
|
||||
if (error != NULL) {
|
||||
NSDictionary *userInfo = @{
|
||||
NSLocalizedDescriptionKey: [NSString stringWithFormat:NSLocalizedString(@"Could not convert %@ to string", @""), objectClass],
|
||||
NSLocalizedFailureReasonErrorKey: [NSString stringWithFormat:NSLocalizedString(@"Expected an %@ as input, got: %@.", @""), objectClass, object],
|
||||
MTLTransformerErrorHandlingInputValueErrorKey : object
|
||||
};
|
||||
|
||||
*error = [NSError errorWithDomain:MTLTransformerErrorHandlingErrorDomain code:MTLTransformerErrorHandlingErrorInvalidInput userInfo:userInfo];
|
||||
}
|
||||
*success = NO;
|
||||
return nil;
|
||||
}
|
||||
|
||||
NSString *string = [formatter stringForObjectValue:object];
|
||||
*success = (string != nil);
|
||||
return string;
|
||||
}];
|
||||
}
|
||||
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wdeprecated-implementations"
|
||||
|
||||
+ (NSValueTransformer<MTLTransformerErrorHandling> *)mtl_JSONDictionaryTransformerWithModelClass:(Class)modelClass {
|
||||
return [MTLJSONAdapter dictionaryTransformerWithModelClass:modelClass];
|
||||
}
|
||||
|
||||
+ (NSValueTransformer<MTLTransformerErrorHandling> *)mtl_JSONArrayTransformerWithModelClass:(Class)modelClass {
|
||||
return [MTLJSONAdapter arrayTransformerWithModelClass:modelClass];
|
||||
}
|
||||
|
||||
#pragma clang diagnostic pop
|
||||
|
||||
@end
|
||||
|
||||
@ -50,10 +50,10 @@ NSString *lowercaseStringPath = @keypath(NSString.new, lowercaseString);
|
||||
*
|
||||
* @code
|
||||
|
||||
NSString *employeesFirstNamePath = @collectionKeypath(department.employees, Employee.new, firstName)
|
||||
NSString *employessFirstNamePath = @collectionKeypath(department.employees, Employee.new, firstName)
|
||||
// => @"employees.firstName"
|
||||
|
||||
NSString *employeesFirstNamePath = @collectionKeypath(Department.new, employees, Employee.new, firstName)
|
||||
NSString *employessFirstNamePath = @collectionKeypath(Department.new, employees, Employee.new, firstName)
|
||||
// => @"employees.firstName"
|
||||
|
||||
* @endcode
|
||||
|
||||
@ -9,8 +9,6 @@
|
||||
|
||||
#import "EXTRuntimeExtensions.h"
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
mtl_propertyAttributes *mtl_copyPropertyAttributes (objc_property_t property) {
|
||||
const char * const attrString = property_getAttributes(property);
|
||||
if (!attrString) {
|
||||
|
||||
@ -88,7 +88,7 @@
|
||||
_Pragma("clang diagnostic pop")
|
||||
|
||||
/*** implementation details follow ***/
|
||||
typedef void (^mtl_cleanupBlock_t)(void);
|
||||
typedef void (^mtl_cleanupBlock_t)();
|
||||
|
||||
void mtl_executeCleanupBlock (__strong mtl_cleanupBlock_t *block);
|
||||
|
||||
|
||||
@ -6,21 +6,17 @@
|
||||
// Copyright (c) 2012 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Mantle/Mantle.h>
|
||||
#import <Nimble/Nimble.h>
|
||||
#import <Quick/Quick.h>
|
||||
|
||||
QuickSpecBegin(MTLArrayManipulationAdditions)
|
||||
SpecBegin(MTLArrayManipulationAdditions)
|
||||
|
||||
describe(@"-mtl_firstObject", ^{
|
||||
it(@"should return the first object", ^{
|
||||
NSArray *array = @[ @1, @2, @3 ];
|
||||
expect(array.mtl_firstObject).to(equal(@1));
|
||||
expect(array.mtl_firstObject).to.equal(@1);
|
||||
});
|
||||
|
||||
it(@"should return nil for an empty array", ^{
|
||||
NSArray *array = @[];
|
||||
expect(array.mtl_firstObject).to(beNil());
|
||||
expect(array.mtl_firstObject).to.beNil();
|
||||
});
|
||||
});
|
||||
|
||||
@ -28,18 +24,18 @@ describe(@"-mtl_arrayByRemovingObject:", ^{
|
||||
it(@"should return a new array without the object", ^{
|
||||
NSArray *array = @[ @1, @2, @3 ];
|
||||
NSArray *expected = @[ @2, @3 ];
|
||||
expect([array mtl_arrayByRemovingObject:@1]).to(equal(expected));
|
||||
expect([array mtl_arrayByRemovingObject:@1]).to.equal(expected);
|
||||
});
|
||||
|
||||
it(@"should return a new array without all occurrences of the object", ^{
|
||||
NSArray *array = @[ @1, @2, @3, @1, @1 ];
|
||||
NSArray *expected = @[ @2, @3 ];
|
||||
expect([array mtl_arrayByRemovingObject:@1]).to(equal(expected));
|
||||
expect([array mtl_arrayByRemovingObject:@1]).to.equal(expected);
|
||||
});
|
||||
|
||||
|
||||
it(@"should return an equivalent array if it doesn't contain the object", ^{
|
||||
NSArray *array = @[ @1, @2, @3 ];
|
||||
expect([array mtl_arrayByRemovingObject:@42]).to(equal(array));
|
||||
expect([array mtl_arrayByRemovingObject:@42]).to.equal(array);
|
||||
});
|
||||
});
|
||||
|
||||
@ -47,12 +43,12 @@ describe(@"-mtl_arrayByRemovingFirstObject", ^{
|
||||
it(@"should return the array without the first object", ^{
|
||||
NSArray *array = @[ @1, @2, @3 ];
|
||||
NSArray *expected = @[ @2, @3 ];
|
||||
expect(array.mtl_arrayByRemovingFirstObject).to(equal(expected));
|
||||
expect(array.mtl_arrayByRemovingFirstObject).to.equal(expected);
|
||||
});
|
||||
|
||||
it(@"should return the same array if it's empty", ^{
|
||||
NSArray *array = @[];
|
||||
expect(array.mtl_arrayByRemovingFirstObject).to(equal(array));
|
||||
expect(array.mtl_arrayByRemovingFirstObject).to.equal(array);
|
||||
});
|
||||
});
|
||||
|
||||
@ -60,13 +56,13 @@ describe(@"-mtl_arrayByRemovingLastObject", ^{
|
||||
it(@"should return the array without the last object", ^{
|
||||
NSArray *array = @[ @1, @2, @3 ];
|
||||
NSArray *expected = @[ @1, @2 ];
|
||||
expect(array.mtl_arrayByRemovingLastObject).to(equal(expected));
|
||||
expect(array.mtl_arrayByRemovingLastObject).to.equal(expected);
|
||||
});
|
||||
|
||||
it(@"should return the same array if it's empty", ^{
|
||||
NSArray *array = @[];
|
||||
expect(array.mtl_arrayByRemovingLastObject).to(equal(array));
|
||||
expect(array.mtl_arrayByRemovingLastObject).to.equal(array);
|
||||
});
|
||||
});
|
||||
|
||||
QuickSpecEnd
|
||||
SpecEnd
|
||||
|
||||
@ -9,36 +9,32 @@
|
||||
// See the LICENSE file for more information.
|
||||
//
|
||||
|
||||
#import <Mantle/Mantle.h>
|
||||
#import <Nimble/Nimble.h>
|
||||
#import <Quick/Quick.h>
|
||||
|
||||
#import "NSObject+MTLComparisonAdditions.h"
|
||||
|
||||
QuickSpecBegin(MTLComparisonAdditions)
|
||||
SpecBegin(MTLComparisonAdditions)
|
||||
|
||||
describe(@"MTLEqualObjects", ^{
|
||||
id obj1 = @"Test1";
|
||||
id obj2 = @"Test2";
|
||||
|
||||
it(@"returns true when given two values of nil", ^{
|
||||
expect(@(MTLEqualObjects(nil, nil))).to(beTruthy());
|
||||
expect(MTLEqualObjects(nil, nil)).to.beTruthy();
|
||||
});
|
||||
|
||||
it(@"returns true when given two equal objects", ^{
|
||||
expect(@(MTLEqualObjects(obj1, obj1))).to(beTruthy());
|
||||
expect(MTLEqualObjects(obj1, obj1)).to.beTruthy();
|
||||
});
|
||||
|
||||
it(@"returns false when given two inequal objects", ^{
|
||||
expect(@(MTLEqualObjects(obj1, obj2))).to(beFalsy());
|
||||
expect(MTLEqualObjects(obj1, obj2)).to.beFalsy();
|
||||
});
|
||||
|
||||
it(@"returns false when given an object and nil", ^{
|
||||
expect(@(MTLEqualObjects(obj1, nil))).to(beFalsy());
|
||||
expect(MTLEqualObjects(obj1, nil)).to.beFalsy();
|
||||
});
|
||||
|
||||
it(@"returns the same value when given symmetric arguments", ^{
|
||||
expect(@(MTLEqualObjects(obj2, obj1))).to(equal(@(MTLEqualObjects(obj1, obj2))));
|
||||
expect(MTLEqualObjects(obj2, obj1)).to.equal(MTLEqualObjects(obj1, obj2));
|
||||
});
|
||||
|
||||
describe(@"when comparing mutable objects", ^{
|
||||
@ -46,9 +42,9 @@ describe(@"MTLEqualObjects", ^{
|
||||
id mutableObj2 = [obj1 mutableCopy];
|
||||
|
||||
it(@"returns true when given two equal but not identical objects", ^{
|
||||
expect(@(MTLEqualObjects(mutableObj1, mutableObj2))).to(beTruthy());
|
||||
expect(MTLEqualObjects(mutableObj1, mutableObj2)).to.beTruthy();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
QuickSpecEnd
|
||||
SpecEnd
|
||||
|
||||
53
MantleTests/MTLCoreDataObjects.h
Normal file
53
MantleTests/MTLCoreDataObjects.h
Normal file
@ -0,0 +1,53 @@
|
||||
//
|
||||
// MTLCoreDataObjects.h
|
||||
// Mantle
|
||||
//
|
||||
// Created by Robert Böhnke on 9/4/13.
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <CoreData/CoreData.h>
|
||||
|
||||
@class MTLParent;
|
||||
|
||||
@interface MTLChild : NSManagedObject
|
||||
|
||||
+ (instancetype)insertInManagedObjectContext:(NSManagedObjectContext*)moc;
|
||||
|
||||
@property (readwrite, nonatomic, strong) NSNumber *childID;
|
||||
|
||||
@property (readwrite, nonatomic, strong) MTLParent *parent1;
|
||||
@property (readwrite, nonatomic, strong) MTLParent *parent2;
|
||||
|
||||
@end
|
||||
|
||||
@interface MTLParent : NSManagedObject
|
||||
|
||||
+ (instancetype)insertInManagedObjectContext:(NSManagedObjectContext*)moc;
|
||||
|
||||
@property (readwrite, nonatomic, strong) NSDate *date;
|
||||
@property (readwrite, nonatomic, strong) NSNumber* number;
|
||||
@property (readwrite, nonatomic, copy) NSString *string;
|
||||
@property (readwrite, nonatomic, copy) NSString *url;
|
||||
|
||||
@property (readwrite, nonatomic, copy) NSOrderedSet *orderedChildren;
|
||||
@property (readwrite, nonatomic, copy) NSSet *unorderedChildren;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
@interface MTLParent (CoreDataGeneratedAccesssors)
|
||||
|
||||
- (void)addOrderedChildren:(NSOrderedSet*)orderedChildren;
|
||||
- (void)removeOrderedChildren:(NSOrderedSet*)orderedChildren;
|
||||
|
||||
- (void)addOrderedChildrenObject:(MTLChild*)child;
|
||||
- (void)removeOrderedChildrenObject:(MTLChild*)child;
|
||||
|
||||
- (void)addUnorderedChildren:(NSSet*)unorderedChildren;
|
||||
- (void)removeUnorderedChildren:(NSSet*)unorderedChildren;
|
||||
|
||||
- (void)addUnorderedChildrenObject:(MTLChild*)child;
|
||||
- (void)removeUnorderedChildrenObject:(MTLChild*)child;
|
||||
|
||||
@end
|
||||
57
MantleTests/MTLCoreDataObjects.m
Normal file
57
MantleTests/MTLCoreDataObjects.m
Normal file
@ -0,0 +1,57 @@
|
||||
//
|
||||
// MTLCoreDataObjects.m
|
||||
// Mantle
|
||||
//
|
||||
// Created by Robert Böhnke on 9/4/13.
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import "MTLCoreDataObjects.h"
|
||||
|
||||
@implementation MTLChild
|
||||
|
||||
@dynamic childID;
|
||||
@dynamic parent1;
|
||||
@dynamic parent2;
|
||||
|
||||
+ (id)insertInManagedObjectContext:(NSManagedObjectContext*)moc {
|
||||
NSParameterAssert(moc != nil);
|
||||
|
||||
return [NSEntityDescription insertNewObjectForEntityForName:@"Child" inManagedObjectContext:moc];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation MTLParent
|
||||
|
||||
@dynamic date;
|
||||
@dynamic number;
|
||||
@dynamic string;
|
||||
@dynamic url;
|
||||
@dynamic unorderedChildren;
|
||||
@dynamic orderedChildren;
|
||||
|
||||
+ (id)insertInManagedObjectContext:(NSManagedObjectContext*)moc {
|
||||
NSParameterAssert(moc != nil);
|
||||
|
||||
return [NSEntityDescription insertNewObjectForEntityForName:@"Parent" inManagedObjectContext:moc];
|
||||
}
|
||||
|
||||
// Working around http://openradar.appspot.com/10114310
|
||||
- (void)addOrderedChildrenObject:(MTLChild*)child {
|
||||
NSMutableOrderedSet *mutableCopy = [self.orderedChildren mutableCopy];
|
||||
|
||||
[mutableCopy addObject:child];
|
||||
|
||||
self.orderedChildren = [mutableCopy copy];
|
||||
}
|
||||
|
||||
- (void)removeOrderedChildrenObject:(MTLChild*)child {
|
||||
NSMutableOrderedSet *mutableCopy = [self.orderedChildren mutableCopy];
|
||||
|
||||
[mutableCopy removeObject:child];
|
||||
|
||||
self.orderedChildren = [mutableCopy copy];
|
||||
}
|
||||
|
||||
@end
|
||||
68
MantleTests/MTLCoreDataTestModels.h
Normal file
68
MantleTests/MTLCoreDataTestModels.h
Normal file
@ -0,0 +1,68 @@
|
||||
//
|
||||
// MTLCoreDataTestModels.h
|
||||
// Mantle
|
||||
//
|
||||
// Created by Justin Spahr-Summers on 2013-04-05.
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Mantle/Mantle.h>
|
||||
#import <CoreData/CoreData.h>
|
||||
|
||||
extern NSString * const MTLCoreDataTestModelsDomain;
|
||||
|
||||
// Corresponds to the `Parent` entity.
|
||||
@interface MTLParentTestModel : MTLModel <MTLManagedObjectSerializing>
|
||||
|
||||
// Associated with the `number` attribute.
|
||||
@property (nonatomic, copy) NSString *numberString;
|
||||
|
||||
@property (nonatomic, copy) NSDate *date;
|
||||
@property (nonatomic, copy) NSString *requiredString;
|
||||
|
||||
@property (nonatomic, copy) NSURL *URL;
|
||||
|
||||
@property (nonatomic, copy) NSArray *orderedChildren;
|
||||
@property (nonatomic, copy) NSSet *unorderedChildren;
|
||||
|
||||
@end
|
||||
|
||||
// Model for Parent that has custom merging behaviour for CoreData
|
||||
@interface MTLParentMergingTestModel : MTLParentTestModel
|
||||
|
||||
@end
|
||||
|
||||
// Model for Parent entity which doesn't serialize required properties
|
||||
@interface MTLParentIncorrectTestModel : MTLModel <MTLManagedObjectSerializing>
|
||||
|
||||
@end
|
||||
|
||||
// Corresponds to the `Child` entity.
|
||||
@interface MTLChildTestModel : MTLModel <MTLManagedObjectSerializing>
|
||||
|
||||
// Associated with the `id` attribute.
|
||||
@property (nonatomic, assign) NSUInteger childID;
|
||||
|
||||
@property (nonatomic, weak) MTLParentTestModel *parent1;
|
||||
@property (nonatomic, weak) MTLParentTestModel *parent2;
|
||||
|
||||
@end
|
||||
|
||||
@interface MTLBadChildTestModel : MTLModel <MTLManagedObjectSerializing>
|
||||
|
||||
@property (nonatomic, assign) NSUInteger childID;
|
||||
|
||||
@end
|
||||
|
||||
// Claims to correspond to the `Empty` entity which lacks the `notSupported`
|
||||
// property.
|
||||
@interface MTLFailureModel : MTLModel <MTLManagedObjectSerializing>
|
||||
|
||||
// Not present in the `Empty` entity.
|
||||
@property (nonatomic, assign) NSString *notSupported;
|
||||
|
||||
@end
|
||||
|
||||
// Maps a non-existant property "name" to the "string" attribute.
|
||||
@interface MTLIllegalManagedObjectMappingModel : MTLModel <MTLManagedObjectSerializing>
|
||||
@end
|
||||
153
MantleTests/MTLCoreDataTestModels.m
Normal file
153
MantleTests/MTLCoreDataTestModels.m
Normal file
@ -0,0 +1,153 @@
|
||||
//
|
||||
// MTLCoreDataTestModels.m
|
||||
// Mantle
|
||||
//
|
||||
// Created by Justin Spahr-Summers on 2013-04-05.
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import "MTLCoreDataTestModels.h"
|
||||
#import "NSDictionary+MTLMappingAdditions.h"
|
||||
|
||||
NSString * const MTLCoreDataTestModelsDomain = @"MTLCoreDataTestModelsDomain";
|
||||
|
||||
@implementation MTLParentTestModel
|
||||
|
||||
+ (NSString *)managedObjectEntityName {
|
||||
return @"Parent";
|
||||
}
|
||||
|
||||
+ (NSDictionary *)managedObjectKeysByPropertyKey {
|
||||
NSDictionary *mapping = [NSDictionary mtl_identityPropertyMapWithModel:self];
|
||||
|
||||
return [mapping mtl_dictionaryByAddingEntriesFromDictionary:@{
|
||||
@"numberString": @"number",
|
||||
@"requiredString": @"string",
|
||||
@"URL": @"url"
|
||||
}];
|
||||
}
|
||||
|
||||
+ (NSSet *)propertyKeysForManagedObjectUniquing {
|
||||
return [NSSet setWithObject:@"numberString"];
|
||||
}
|
||||
|
||||
+ (NSValueTransformer *)numberStringEntityAttributeTransformer {
|
||||
return [MTLValueTransformer transformerUsingForwardBlock:^ id (NSNumber *num, BOOL *success, NSError **error) {
|
||||
if (![num isKindOfClass:NSNumber.class]) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:MTLCoreDataTestModelsDomain code:666 userInfo:nil];
|
||||
}
|
||||
*success = NO;
|
||||
return nil;
|
||||
}
|
||||
|
||||
return num.stringValue;
|
||||
} reverseBlock:^ id (NSString *str, BOOL *success, NSError **error) {
|
||||
if (![str isKindOfClass:NSString.class]) {
|
||||
if (error != NULL) {
|
||||
*error = [NSError errorWithDomain:MTLCoreDataTestModelsDomain code:666 userInfo:nil];
|
||||
}
|
||||
*success = NO;
|
||||
return nil;
|
||||
}
|
||||
|
||||
return [NSDecimalNumber decimalNumberWithString:str];
|
||||
}];
|
||||
}
|
||||
|
||||
+ (NSDictionary *)relationshipModelClassesByPropertyKey {
|
||||
return @{
|
||||
@"orderedChildren": MTLChildTestModel.class,
|
||||
@"unorderedChildren": MTLChildTestModel.class,
|
||||
};
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation MTLParentMergingTestModel
|
||||
|
||||
- (void)mergeValueForKey:(NSString *)key fromManagedObject:(NSManagedObject *)managedObject {
|
||||
if ([key isEqualToString:@"requiredString"]) {
|
||||
self.requiredString = @"merged";
|
||||
}
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation MTLParentIncorrectTestModel
|
||||
|
||||
+ (NSString *)managedObjectEntityName {
|
||||
return @"Parent";
|
||||
}
|
||||
|
||||
+ (NSDictionary *)managedObjectKeysByPropertyKey {
|
||||
return @{};
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation MTLChildTestModel
|
||||
|
||||
+ (NSString *)managedObjectEntityName {
|
||||
return @"Child";
|
||||
}
|
||||
|
||||
+ (NSDictionary *)managedObjectKeysByPropertyKey {
|
||||
return [NSDictionary mtl_identityPropertyMapWithModel:self];
|
||||
}
|
||||
|
||||
+ (NSSet *)propertyKeysForManagedObjectUniquing {
|
||||
return [NSSet setWithObjects:@"childID", nil];
|
||||
}
|
||||
|
||||
+ (NSDictionary *)relationshipModelClassesByPropertyKey {
|
||||
return @{
|
||||
@"parent1": MTLParentTestModel.class,
|
||||
@"parent2": MTLParentTestModel.class,
|
||||
};
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation MTLBadChildTestModel
|
||||
|
||||
+ (NSString *)managedObjectEntityName {
|
||||
return @"BadChild";
|
||||
}
|
||||
|
||||
+ (NSDictionary *)managedObjectKeysByPropertyKey {
|
||||
return [NSDictionary mtl_identityPropertyMapWithModel:self];
|
||||
}
|
||||
|
||||
+ (NSSet *)propertyKeysForManagedObjectUniquing {
|
||||
return [NSSet setWithObjects:@"childID", nil];
|
||||
}
|
||||
|
||||
|
||||
@end
|
||||
|
||||
@implementation MTLFailureModel
|
||||
|
||||
+ (NSDictionary *)managedObjectKeysByPropertyKey {
|
||||
return [NSDictionary mtl_identityPropertyMapWithModel:self];
|
||||
}
|
||||
|
||||
+ (NSString *)managedObjectEntityName {
|
||||
return @"Empty";
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation MTLIllegalManagedObjectMappingModel
|
||||
|
||||
+ (NSString *)managedObjectEntityName {
|
||||
return @"Parent";
|
||||
}
|
||||
|
||||
+ (NSDictionary *)managedObjectKeysByPropertyKey {
|
||||
return @{
|
||||
@"name": @"username"
|
||||
};
|
||||
}
|
||||
|
||||
@end
|
||||
@ -6,62 +6,58 @@
|
||||
// Copyright (c) 2012 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Mantle/Mantle.h>
|
||||
#import <Nimble/Nimble.h>
|
||||
#import <Quick/Quick.h>
|
||||
|
||||
QuickSpecBegin(MTLDictionaryManipulationAdditions)
|
||||
SpecBegin(MTLDictionaryManipulationAdditions)
|
||||
|
||||
describe(@"-mtl_dictionaryByAddingEntriesFromDictionary:", ^{
|
||||
NSDictionary *dict = @{ @"foo": @"bar", @(5): NSNull.null };
|
||||
|
||||
it(@"should return the same dictionary when adding from an empty dictionary", ^{
|
||||
NSDictionary *combined = [dict mtl_dictionaryByAddingEntriesFromDictionary:@{}];
|
||||
expect(combined).to(equal(dict));
|
||||
expect(combined).to.equal(dict);
|
||||
});
|
||||
|
||||
it(@"should return the same dictionary when adding from nil", ^{
|
||||
NSDictionary *combined = [dict mtl_dictionaryByAddingEntriesFromDictionary:nil];
|
||||
expect(combined).to(equal(dict));
|
||||
expect(combined).to.equal(dict);
|
||||
});
|
||||
|
||||
it(@"should add any new keys", ^{
|
||||
NSDictionary *combined = [dict mtl_dictionaryByAddingEntriesFromDictionary:@{ @"buzz": @(10), @"baz": NSNull.null }];
|
||||
NSDictionary *expected = @{ @"foo": @"bar", @(5): NSNull.null, @"buzz": @(10), @"baz": NSNull.null };
|
||||
expect(combined).to(equal(expected));
|
||||
expect(combined).to.equal(expected);
|
||||
});
|
||||
|
||||
it(@"should replace any existing keys", ^{
|
||||
NSDictionary *combined = [dict mtl_dictionaryByAddingEntriesFromDictionary:@{ @(5): @(10), @"buzz": @"baz" }];
|
||||
NSDictionary *expected = @{ @"foo": @"bar", @(5): @(10), @"buzz": @"baz" };
|
||||
expect(combined).to(equal(expected));
|
||||
expect(combined).to.equal(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe(@"-mtl_dictionaryByRemovingValuesForKeys:", ^{
|
||||
describe(@"-mtl_dictionaryByRemovingEntriesWithKeys:", ^{
|
||||
NSDictionary *dict = @{ @"foo": @"bar", @(5): NSNull.null };
|
||||
|
||||
it(@"should return the same dictionary when removing keys that don't exist in the receiver", ^{
|
||||
NSDictionary *removed = [dict mtl_dictionaryByRemovingValuesForKeys:@[ @"hi"]];
|
||||
expect(removed).to(equal(dict));
|
||||
NSDictionary *removed = [dict mtl_dictionaryByRemovingEntriesWithKeys:@[ @"hi" ]];
|
||||
expect(removed).to.equal(dict);
|
||||
});
|
||||
|
||||
it(@"should return the same dictionary when given a nil array of keys", ^{
|
||||
NSDictionary *removed = [dict mtl_dictionaryByRemovingValuesForKeys:nil];
|
||||
expect(removed).to(equal(dict));
|
||||
NSDictionary *removed = [dict mtl_dictionaryByRemovingEntriesWithKeys:nil];
|
||||
expect(removed).to.equal(dict);
|
||||
});
|
||||
|
||||
it(@"should remove all the entries for the given keys", ^{
|
||||
NSDictionary *removed = [dict mtl_dictionaryByRemovingValuesForKeys:@[ @5 ]];
|
||||
NSDictionary *removed = [dict mtl_dictionaryByRemovingEntriesWithKeys:@[ @(5) ]];
|
||||
NSDictionary *expected = @{ @"foo": @"bar" };
|
||||
expect(removed).to(equal(expected));
|
||||
expect(removed).to.equal(expected);
|
||||
});
|
||||
|
||||
it(@"should return an empty dictionary when it removes all its keys", ^{
|
||||
NSDictionary *removed = [dict mtl_dictionaryByRemovingValuesForKeys:dict.allKeys];
|
||||
NSDictionary *removed = [dict mtl_dictionaryByRemovingEntriesWithKeys:dict.allKeys];
|
||||
NSDictionary *expected = @{};
|
||||
expect(removed).to(equal(expected));
|
||||
expect(removed).to.equal(expected);
|
||||
});
|
||||
});
|
||||
|
||||
QuickSpecEnd
|
||||
SpecEnd
|
||||
|
||||
@ -6,13 +6,11 @@
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Quick/Quick.h>
|
||||
#import <Nimble/Nimble.h>
|
||||
#import "MTLTestModel.h"
|
||||
|
||||
#import "NSDictionary+MTLMappingAdditions.h"
|
||||
|
||||
QuickSpecBegin(MTLDictionaryMappingAdditions)
|
||||
SpecBegin(MTLDictionaryMappingAdditions)
|
||||
|
||||
it(@"should return a mapping", ^{
|
||||
NSDictionary *mapping = @{
|
||||
@ -22,7 +20,7 @@ it(@"should return a mapping", ^{
|
||||
@"weakModel": @"weakModel"
|
||||
};
|
||||
|
||||
expect([NSDictionary mtl_identityPropertyMapWithModel:MTLTestModel.class]).to(equal(mapping));
|
||||
expect([NSDictionary mtl_identityPropertyMapWithModel:MTLTestModel.class]).to.equal(mapping);
|
||||
});
|
||||
|
||||
QuickSpecEnd
|
||||
SpecEnd
|
||||
|
||||
@ -6,13 +6,9 @@
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Mantle/Mantle.h>
|
||||
#import <Nimble/Nimble.h>
|
||||
#import <Quick/Quick.h>
|
||||
|
||||
#import "NSError+MTLModelException.h"
|
||||
|
||||
QuickSpecBegin(MTLErrorModelException)
|
||||
SpecBegin(MTLErrorModelException)
|
||||
|
||||
describe(@"+mtl_modelErrorWithException:", ^{
|
||||
it(@"should return a new error for that exception", ^{
|
||||
@ -20,10 +16,10 @@ describe(@"+mtl_modelErrorWithException:", ^{
|
||||
|
||||
NSError *error = [NSError mtl_modelErrorWithException:exception];
|
||||
|
||||
expect(error).notTo(beNil());
|
||||
expect(error.localizedDescription).to(equal(@"Just Testing"));
|
||||
expect(error.localizedFailureReason).to(equal(@"Just Testing"));
|
||||
expect(error).toNot.beNil();
|
||||
expect(error.localizedDescription).to.equal(@"Just Testing");
|
||||
expect(error.localizedFailureReason).to.equal(@"Just Testing");
|
||||
});
|
||||
});
|
||||
|
||||
QuickSpecEnd
|
||||
SpecEnd
|
||||
|
||||
@ -6,30 +6,10 @@
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Mantle/Mantle.h>
|
||||
#import <Nimble/Nimble.h>
|
||||
#import <Quick/Quick.h>
|
||||
|
||||
#import "MTLTestJSONAdapter.h"
|
||||
#import "MTLTestModel.h"
|
||||
#import "MTLTransformerErrorExamples.h"
|
||||
#import "MTLTestJSONAdapter.h"
|
||||
|
||||
@interface MTLJSONAdapter (SpecExtensions)
|
||||
|
||||
// Used for testing transformer lifetimes.
|
||||
+ (NSValueTransformer *)NSDateJSONTransformer;
|
||||
|
||||
@end
|
||||
|
||||
@implementation MTLJSONAdapter (SpecExtensions)
|
||||
|
||||
+ (NSValueTransformer *)NSDateJSONTransformer {
|
||||
return [[NSValueTransformer alloc] init];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
QuickSpecBegin(MTLJSONAdapterSpec)
|
||||
SpecBegin(MTLJSONAdapter)
|
||||
|
||||
it(@"should initialize with a model class", ^{
|
||||
NSDictionary *values = @{
|
||||
@ -38,16 +18,16 @@ it(@"should initialize with a model class", ^{
|
||||
};
|
||||
|
||||
MTLJSONAdapter *adapter = [[MTLJSONAdapter alloc] initWithModelClass:MTLTestModel.class];
|
||||
expect(adapter).notTo(beNil());
|
||||
expect(adapter).notTo.beNil();
|
||||
|
||||
NSError *error = nil;
|
||||
MTLTestModel *model = [adapter modelFromJSONDictionary:values error:&error];
|
||||
expect(error).to(beNil());
|
||||
|
||||
expect(model).notTo(beNil());
|
||||
expect(model.name).to(beNil());
|
||||
expect(@(model.count)).to(equal(@5));
|
||||
expect(error).to.beNil();
|
||||
|
||||
expect(model).notTo.beNil();
|
||||
expect(model.name).to.beNil();
|
||||
expect(model.count).to.equal(5);
|
||||
|
||||
NSDictionary *JSONDictionary = @{
|
||||
@"username": NSNull.null,
|
||||
@"count": @"5",
|
||||
@ -55,8 +35,8 @@ it(@"should initialize with a model class", ^{
|
||||
};
|
||||
|
||||
__block NSError *serializationError;
|
||||
expect([adapter JSONDictionaryFromModel:model error:&serializationError]).to(equal(JSONDictionary));
|
||||
expect(serializationError).to(beNil());
|
||||
expect([adapter JSONDictionaryFromModel:model error:&serializationError]).to.equal(JSONDictionary);
|
||||
expect(serializationError).to.beNil();
|
||||
});
|
||||
|
||||
it(@"should initialize nested key paths from JSON", ^{
|
||||
@ -68,16 +48,16 @@ it(@"should initialize nested key paths from JSON", ^{
|
||||
|
||||
NSError *error = nil;
|
||||
MTLTestModel *model = [MTLJSONAdapter modelOfClass:MTLTestModel.class fromJSONDictionary:values error:&error];
|
||||
expect(model).notTo(beNil());
|
||||
expect(error).to(beNil());
|
||||
expect(model).notTo.beNil();
|
||||
expect(error).to.beNil();
|
||||
|
||||
expect(model.name).to(equal(@"foo"));
|
||||
expect(@(model.count)).to(equal(@0));
|
||||
expect(model.nestedName).to(equal(@"bar"));
|
||||
expect(model.name).to.equal(@"foo");
|
||||
expect(model.count).to.equal(0);
|
||||
expect(model.nestedName).to.equal(@"bar");
|
||||
|
||||
__block NSError *serializationError;
|
||||
expect([MTLJSONAdapter JSONDictionaryFromModel:model error:&serializationError]).to(equal(values));
|
||||
expect(serializationError).to(beNil());
|
||||
expect([MTLJSONAdapter JSONDictionaryFromModel:model error:&serializationError]).to.equal(values);
|
||||
expect(serializationError).to.beNil();
|
||||
});
|
||||
|
||||
it(@"it should initialize properties with multiple key paths from JSON", ^{
|
||||
@ -92,18 +72,18 @@ it(@"it should initialize properties with multiple key paths from JSON", ^{
|
||||
|
||||
NSError *error = nil;
|
||||
MTLMultiKeypathModel *model = [MTLJSONAdapter modelOfClass:MTLMultiKeypathModel.class fromJSONDictionary:values error:&error];
|
||||
expect(model).notTo(beNil());
|
||||
expect(error).to(beNil());
|
||||
expect(model).notTo.beNil();
|
||||
expect(error).to.beNil();
|
||||
|
||||
expect(@(model.range.location)).to(equal(@20));
|
||||
expect(@(model.range.length)).to(equal(@12));
|
||||
expect(model.range.location).to.equal(20);
|
||||
expect(model.range.length).to.equal(12);
|
||||
|
||||
expect(@(model.nestedRange.location)).to(equal(@12));
|
||||
expect(@(model.nestedRange.length)).to(equal(@34));
|
||||
expect(model.nestedRange.location).to.equal(12);
|
||||
expect(model.nestedRange.length).to.equal(34);
|
||||
|
||||
__block NSError *serializationError;
|
||||
expect([MTLJSONAdapter JSONDictionaryFromModel:model error:&serializationError]).to(equal(values));
|
||||
expect(serializationError).to(beNil());
|
||||
expect([MTLJSONAdapter JSONDictionaryFromModel:model error:&serializationError]).to.equal(values);
|
||||
expect(serializationError).to.beNil();
|
||||
});
|
||||
|
||||
it(@"should return nil and error with an invalid key path from JSON",^{
|
||||
@ -112,16 +92,16 @@ it(@"should return nil and error with an invalid key path from JSON",^{
|
||||
@"nested": @"bar",
|
||||
@"count": @"0"
|
||||
};
|
||||
|
||||
|
||||
NSError *error = nil;
|
||||
MTLTestModel *model = [MTLJSONAdapter modelOfClass:MTLTestModel.class fromJSONDictionary:values error:&error];
|
||||
expect(model).to(beNil());
|
||||
expect(error).notTo(beNil());
|
||||
expect(error.domain).to(equal(MTLJSONAdapterErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(MTLJSONAdapterErrorInvalidJSONDictionary)));
|
||||
expect(model).beNil();
|
||||
expect(error).notTo.beNil();
|
||||
expect(error.domain).to.equal(MTLJSONAdapterErrorDomain);
|
||||
expect(error.code).to.equal(MTLJSONAdapterErrorInvalidJSONDictionary);
|
||||
});
|
||||
|
||||
it(@"should support key paths across arrays", ^{
|
||||
it(@"should not support key paths across arrays", ^{
|
||||
NSDictionary *values = @{
|
||||
@"users": @[
|
||||
@{
|
||||
@ -138,11 +118,11 @@ it(@"should support key paths across arrays", ^{
|
||||
|
||||
NSError *error = nil;
|
||||
MTLArrayTestModel *model = [MTLJSONAdapter modelOfClass:MTLArrayTestModel.class fromJSONDictionary:values error:&error];
|
||||
expect(model).to(beNil());
|
||||
expect(error).notTo(beNil());
|
||||
expect(model).to.beNil();
|
||||
expect(error).notTo.beNil();
|
||||
|
||||
expect(error.domain).to(equal(MTLJSONAdapterErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(MTLJSONAdapterErrorInvalidJSONDictionary)));
|
||||
expect(error.domain).to.equal(MTLJSONAdapterErrorDomain);
|
||||
expect(error.code).to.equal(MTLJSONAdapterErrorInvalidJSONDictionary);
|
||||
});
|
||||
|
||||
it(@"should initialize without returning any error when using a JSON dictionary which Null.null as value",^{
|
||||
@ -151,15 +131,15 @@ it(@"should initialize without returning any error when using a JSON dictionary
|
||||
@"nested": NSNull.null,
|
||||
@"count": @"0"
|
||||
};
|
||||
|
||||
|
||||
NSError *error = nil;
|
||||
MTLTestModel *model = [MTLJSONAdapter modelOfClass:MTLTestModel.class fromJSONDictionary:values error:&error];
|
||||
expect(model).notTo(beNil());
|
||||
expect(error).to(beNil());
|
||||
|
||||
expect(model.name).to(equal(@"foo"));
|
||||
expect(@(model.count)).to(equal(@0));
|
||||
expect(model.nestedName).to(beNil());
|
||||
expect(model).notTo.beNil();
|
||||
expect(error).to.beNil();
|
||||
|
||||
expect(model.name).to.equal(@"foo");
|
||||
expect(model.count).to.equal(0);
|
||||
expect(model.nestedName).to.beNil();
|
||||
});
|
||||
|
||||
it(@"should ignore unrecognized JSON keys", ^{
|
||||
@ -173,12 +153,12 @@ it(@"should ignore unrecognized JSON keys", ^{
|
||||
|
||||
NSError *error = nil;
|
||||
MTLTestModel *model = [MTLJSONAdapter modelOfClass:MTLTestModel.class fromJSONDictionary:values error:&error];
|
||||
expect(model).notTo(beNil());
|
||||
expect(error).to(beNil());
|
||||
expect(model).notTo.beNil();
|
||||
expect(error).to.beNil();
|
||||
|
||||
expect(model.name).to(equal(@"buzz"));
|
||||
expect(@(model.count)).to(equal(@2));
|
||||
expect(model.nestedName).to(equal(@"bar"));
|
||||
expect(model.name).to.equal(@"buzz");
|
||||
expect(model.count).to.equal(2);
|
||||
expect(model.nestedName).to.equal(@"bar");
|
||||
});
|
||||
|
||||
it(@"should fail to initialize if JSON dictionary validation fails", ^{
|
||||
@ -188,56 +168,19 @@ it(@"should fail to initialize if JSON dictionary validation fails", ^{
|
||||
|
||||
NSError *error = nil;
|
||||
MTLTestModel *model = [MTLJSONAdapter modelOfClass:MTLTestModel.class fromJSONDictionary:values error:&error];
|
||||
expect(model).to(beNil());
|
||||
expect(error.domain).to(equal(MTLTestModelErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(MTLTestModelNameTooLong)));
|
||||
});
|
||||
|
||||
it(@"should implicitly transform NSStrings to URLs", ^{
|
||||
NSDictionary *values = @{
|
||||
@"URL": @"http://github.com/1",
|
||||
@"otherURL": @"http://github.com/2",
|
||||
};
|
||||
|
||||
NSError *error = nil;
|
||||
MTLURLSubclassModel *model = [MTLJSONAdapter modelOfClass:MTLURLSubclassModel.class fromJSONDictionary:values error:&error];
|
||||
expect(model.URL).to(equal([NSURL URLWithString:@"http://github.com/1"]));
|
||||
expect(model.otherURL).to(equal([NSURL URLWithString:@"http://github.com/2"]));
|
||||
expect(error).to(beNil());
|
||||
expect(model).to.beNil();
|
||||
expect(error.domain).to.equal(MTLTestModelErrorDomain);
|
||||
expect(error.code).to.equal(MTLTestModelNameTooLong);
|
||||
});
|
||||
|
||||
it(@"should implicitly transform URLs", ^{
|
||||
MTLURLModel *model = [[MTLURLModel alloc] init];
|
||||
|
||||
NSError *error = nil;
|
||||
NSDictionary *JSONDictionary = [MTLJSONAdapter JSONDictionaryFromModel:model error:&error];
|
||||
|
||||
expect(JSONDictionary[@"URL"]).to(equal(@"http://github.com"));
|
||||
expect(error).to(beNil());
|
||||
});
|
||||
|
||||
|
||||
it(@"should implicitly transform NSStrings to UUIDs", ^{
|
||||
NSDictionary *values = @{
|
||||
@"UUID": @"D278C472-6DC3-4EE1-A947-861E6AF311C3",
|
||||
@"otherUUID": @"24E1E56A-3F37-4ECE-8310-931F6ACD401A",
|
||||
};
|
||||
|
||||
NSError *error = nil;
|
||||
MTLUUIDSubclassModel *model = [MTLJSONAdapter modelOfClass:MTLUUIDSubclassModel.class fromJSONDictionary:values error:&error];
|
||||
expect(model.UUID).to(equal([[NSUUID alloc] initWithUUIDString:@"D278C472-6DC3-4EE1-A947-861E6AF311C3"]));
|
||||
expect(model.otherUUID).to(equal([[NSUUID alloc] initWithUUIDString:@"24E1E56A-3F37-4ECE-8310-931F6ACD401A"]));
|
||||
expect(error).to(beNil());
|
||||
});
|
||||
|
||||
it(@"should implicitly transform UUIDs", ^{
|
||||
MTLUUIDModel *model = [[MTLUUIDModel alloc] init];
|
||||
|
||||
NSError *error = nil;
|
||||
NSDictionary *JSONDictionary = [MTLJSONAdapter JSONDictionaryFromModel:model error:&error];
|
||||
|
||||
expect(JSONDictionary[@"UUID"]).to(equal(@"4A275FBD-8217-4397-964B-403F4C2B8545"));
|
||||
expect(error).to(beNil());
|
||||
expect(JSONDictionary[@"URL"]).to.equal(@"http://github.com");
|
||||
expect(error).to.beNil();
|
||||
});
|
||||
|
||||
it(@"should implicitly transform BOOLs", ^{
|
||||
@ -246,8 +189,8 @@ it(@"should implicitly transform BOOLs", ^{
|
||||
NSError *error = nil;
|
||||
NSDictionary *JSONDictionary = [MTLJSONAdapter JSONDictionaryFromModel:model error:&error];
|
||||
|
||||
expect(JSONDictionary[@"flag"]).to(beIdenticalTo((id)kCFBooleanFalse));
|
||||
expect(error).to(beNil());
|
||||
expect(JSONDictionary[@"flag"]).to.beIdenticalTo((id)kCFBooleanFalse);
|
||||
expect(error).to.beNil();
|
||||
});
|
||||
|
||||
it(@"should not invoke implicit transformers for property keys not actually backed by properties", ^{
|
||||
@ -256,8 +199,8 @@ it(@"should not invoke implicit transformers for property keys not actually back
|
||||
NSError *error = nil;
|
||||
NSDictionary *JSONDictionary = [MTLJSONAdapter JSONDictionaryFromModel:model error:&error];
|
||||
|
||||
expect(error).to(beNil());
|
||||
expect(JSONDictionary[@"homepage"]).to(equal(model.homepage));
|
||||
expect(error).to.beNil();
|
||||
expect(JSONDictionary[@"homepage"]).to.equal(model.homepage);
|
||||
});
|
||||
|
||||
it(@"should fail to initialize if JSON transformer fails", ^{
|
||||
@ -266,39 +209,25 @@ it(@"should fail to initialize if JSON transformer fails", ^{
|
||||
};
|
||||
|
||||
NSError *error = nil;
|
||||
MTLModel *model = [MTLJSONAdapter modelOfClass:MTLURLModel.class fromJSONDictionary:values error:&error];
|
||||
expect(model).to(beNil());
|
||||
expect(error.domain).to(equal(MTLTransformerErrorHandlingErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(MTLTransformerErrorHandlingErrorInvalidInput)));
|
||||
expect(error.userInfo[MTLTransformerErrorHandlingInputValueErrorKey]).to(equal(@666));
|
||||
MTLTestModel *model = [MTLJSONAdapter modelOfClass:MTLURLModel.class fromJSONDictionary:values error:&error];
|
||||
expect(model).to.beNil();
|
||||
expect(error.domain).to.equal(MTLTransformerErrorHandlingErrorDomain);
|
||||
expect(error.code).to.equal(MTLTransformerErrorHandlingErrorInvalidInput);
|
||||
expect(error.userInfo[MTLTransformerErrorHandlingInputValueErrorKey]).to.equal(@666);
|
||||
});
|
||||
|
||||
it(@"should fail to deserialize if the JSON types don't match the primitive properties", ^{
|
||||
it(@"should fail to deserialize if the JSON types don't match the properties", ^{
|
||||
NSDictionary *values = @{
|
||||
@"flag": @"Potentially"
|
||||
};
|
||||
|
||||
NSError *error = nil;
|
||||
MTLModel *model = [MTLJSONAdapter modelOfClass:MTLBoolModel.class fromJSONDictionary:values error:&error];
|
||||
expect(model).to(beNil());
|
||||
MTLTestModel *model = [MTLJSONAdapter modelOfClass:MTLBoolModel.class fromJSONDictionary:values error:&error];
|
||||
expect(model).to.beNil();
|
||||
|
||||
expect(error.domain).to(equal(MTLTransformerErrorHandlingErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(MTLTransformerErrorHandlingErrorInvalidInput)));
|
||||
expect(error.userInfo[MTLTransformerErrorHandlingInputValueErrorKey]).to(equal(@"Potentially"));
|
||||
});
|
||||
|
||||
it(@"should fail to deserialize if the JSON types don't match the properties", ^{
|
||||
NSDictionary *values = @{
|
||||
@"string": @666
|
||||
};
|
||||
|
||||
NSError *error = nil;
|
||||
MTLModel *model = [MTLJSONAdapter modelOfClass:MTLStringModel.class fromJSONDictionary:values error:&error];
|
||||
expect(model).to(beNil());
|
||||
|
||||
expect(error.domain).to(equal(MTLTransformerErrorHandlingErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(MTLTransformerErrorHandlingErrorInvalidInput)));
|
||||
expect(error.userInfo[MTLTransformerErrorHandlingInputValueErrorKey]).to(equal(@666));
|
||||
expect(error.domain).to.equal(MTLTransformerErrorHandlingErrorDomain);
|
||||
expect(error.code).to.equal(MTLTransformerErrorHandlingErrorInvalidInput);
|
||||
expect(error.userInfo[MTLTransformerErrorHandlingInputValueErrorKey]).to.equal(@"Potentially");
|
||||
});
|
||||
|
||||
it(@"should allow subclasses to filter serialized property keys", ^{
|
||||
@ -312,25 +241,20 @@ it(@"should allow subclasses to filter serialized property keys", ^{
|
||||
|
||||
NSError *error;
|
||||
MTLTestModel *model = [adapter modelFromJSONDictionary:values error:&error];
|
||||
expect(model).notTo(beNil());
|
||||
expect(error).to(beNil());
|
||||
expect(model).notTo.beNil();
|
||||
expect(error).to.beNil();
|
||||
|
||||
NSDictionary *complete = [adapter JSONDictionaryFromModel:model error:&error];
|
||||
NSDictionary *expected = [values mtl_dictionaryByAddingEntriesFromDictionary:@{ @"test": @YES }];
|
||||
|
||||
expect(complete).to(equal(expected));
|
||||
expect(error).to(beNil());
|
||||
expect(complete).to.equal(values);
|
||||
expect(error).to.beNil();
|
||||
|
||||
adapter.ignoredPropertyKeys = [NSSet setWithObjects:@"count", @"nestedName", nil];
|
||||
|
||||
NSDictionary *partial = [adapter JSONDictionaryFromModel:model error:&error];
|
||||
expected = @{
|
||||
@"username": @"foo",
|
||||
@"test": @YES,
|
||||
};
|
||||
|
||||
expect(partial).to(equal(expected));
|
||||
expect(error).to(beNil());
|
||||
expect(partial).to.equal(@{ @"username": @"foo" });
|
||||
expect(error).to.beNil();
|
||||
});
|
||||
|
||||
it(@"should accept any object for id properties", ^{
|
||||
@ -340,10 +264,10 @@ it(@"should accept any object for id properties", ^{
|
||||
|
||||
NSError *error = nil;
|
||||
MTLIDModel *model = [MTLJSONAdapter modelOfClass:MTLIDModel.class fromJSONDictionary:values error:&error];
|
||||
expect(model).notTo(beNil());
|
||||
expect(model.anyObject).to(equal(@"Not an NSValue"));
|
||||
expect(model).notTo.beNil();
|
||||
expect(model.anyObject).to.equal(@"Not an NSValue");
|
||||
|
||||
expect(error.domain).to(beNil());
|
||||
expect(error.domain).to.beNil();
|
||||
});
|
||||
|
||||
it(@"should fail to serialize if a JSON transformer errors", ^{
|
||||
@ -353,10 +277,10 @@ it(@"should fail to serialize if a JSON transformer errors", ^{
|
||||
|
||||
NSError *error;
|
||||
NSDictionary *dictionary = [MTLJSONAdapter JSONDictionaryFromModel:model error:&error];
|
||||
expect(dictionary).to(beNil());
|
||||
expect(error.domain).to(equal(MTLTransformerErrorHandlingErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(MTLTransformerErrorHandlingErrorInvalidInput)));
|
||||
expect(error.userInfo[MTLTransformerErrorHandlingInputValueErrorKey]).to(equal(@"totallyNotAnNSURL"));
|
||||
expect(dictionary).to.beNil();
|
||||
expect(error.domain).to.equal(MTLTransformerErrorHandlingErrorDomain);
|
||||
expect(error.code).to.equal(MTLTransformerErrorHandlingErrorInvalidInput);
|
||||
expect(error.userInfo[MTLTransformerErrorHandlingInputValueErrorKey]).to.equal(@"totallyNotAnNSURL");
|
||||
});
|
||||
|
||||
it(@"should parse a different model class", ^{
|
||||
@ -368,16 +292,16 @@ it(@"should parse a different model class", ^{
|
||||
|
||||
NSError *error = nil;
|
||||
MTLTestModel *model = [MTLJSONAdapter modelOfClass:MTLSubstitutingTestModel.class fromJSONDictionary:values error:&error];
|
||||
expect(model).to(beAnInstanceOf(MTLTestModel.class));
|
||||
expect(error).to(beNil());
|
||||
expect(model).to.beKindOf(MTLTestModel.class);
|
||||
expect(error).to.beNil();
|
||||
|
||||
expect(model.name).to(equal(@"foo"));
|
||||
expect(@(model.count)).to(equal(@0));
|
||||
expect(model.nestedName).to(equal(@"bar"));
|
||||
expect(model.name).to.equal(@"foo");
|
||||
expect(model.count).to.equal(0);
|
||||
expect(model.nestedName).to.equal(@"bar");
|
||||
|
||||
__block NSError *serializationError;
|
||||
expect([MTLJSONAdapter JSONDictionaryFromModel:model error:&serializationError]).to(equal(values));
|
||||
expect(serializationError).to(beNil());
|
||||
expect([MTLJSONAdapter JSONDictionaryFromModel:model error:&serializationError]).to.equal(values);
|
||||
expect(serializationError).to.beNil();
|
||||
});
|
||||
|
||||
it(@"should serialize different model classes", ^{
|
||||
@ -390,11 +314,11 @@ it(@"should serialize different model classes", ^{
|
||||
NSError *error = nil;
|
||||
NSDictionary *chocolateValues = [adapter JSONDictionaryFromModel:chocolate error:&error];
|
||||
|
||||
expect(error).to(beNil());
|
||||
expect(chocolateValues).to(equal((@{
|
||||
expect(error).to.beNil();
|
||||
expect(chocolateValues).to.equal((@{
|
||||
@"flavor": @"chocolate",
|
||||
@"chocolate_bitterness": @"100"
|
||||
})));
|
||||
}));
|
||||
|
||||
MTLStrawberryClassClusterModel *strawberry = [MTLStrawberryClassClusterModel modelWithDictionary:@{
|
||||
@"freshness": @20
|
||||
@ -402,11 +326,11 @@ it(@"should serialize different model classes", ^{
|
||||
|
||||
NSDictionary *strawberryValues = [adapter JSONDictionaryFromModel:strawberry error:&error];
|
||||
|
||||
expect(error).to(beNil());
|
||||
expect(strawberryValues).to(equal((@{
|
||||
expect(error).to.beNil();
|
||||
expect(strawberryValues).to.equal((@{
|
||||
@"flavor": @"strawberry",
|
||||
@"strawberry_freshness": @20
|
||||
})));
|
||||
}));
|
||||
});
|
||||
|
||||
it(@"should parse model classes not inheriting from MTLModel", ^{
|
||||
@ -416,133 +340,20 @@ it(@"should parse model classes not inheriting from MTLModel", ^{
|
||||
|
||||
NSError *error = nil;
|
||||
MTLConformingModel *model = [MTLJSONAdapter modelOfClass:MTLConformingModel.class fromJSONDictionary:values error:&error];
|
||||
expect(model).to(beAnInstanceOf(MTLConformingModel.class));
|
||||
expect(error).to(beNil());
|
||||
expect(model).to.beKindOf(MTLConformingModel.class);
|
||||
expect(error).to.beNil();
|
||||
|
||||
expect(model.name).to(equal(@"foo"));
|
||||
expect(model.name).to.equal(@"foo");
|
||||
});
|
||||
|
||||
it(@"should return an error when no suitable model class is found", ^{
|
||||
NSError *error = nil;
|
||||
MTLTestModel *model = [MTLJSONAdapter modelOfClass:MTLSubstitutingTestModel.class fromJSONDictionary:@{} error:&error];
|
||||
expect(model).to(beNil());
|
||||
expect(model).to.beNil();
|
||||
|
||||
expect(error).notTo(beNil());
|
||||
expect(error.domain).to(equal(MTLJSONAdapterErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(MTLJSONAdapterErrorNoClassFound)));
|
||||
});
|
||||
|
||||
it(@"should validate models", ^{
|
||||
NSError *error = nil;
|
||||
MTLValidationModel *model = [MTLJSONAdapter modelOfClass:MTLValidationModel.class fromJSONDictionary:@{} error:&error];
|
||||
|
||||
expect(model).to(beNil());
|
||||
|
||||
expect(error).notTo(beNil());
|
||||
expect(error.domain).to(equal(MTLTestModelErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(MTLTestModelNameMissing)));
|
||||
});
|
||||
|
||||
describe(@"JSON transformers", ^{
|
||||
describe(@"dictionary transformer", ^{
|
||||
__block NSValueTransformer *transformer;
|
||||
|
||||
__block MTLTestModel *model;
|
||||
__block NSDictionary *JSONDictionary;
|
||||
|
||||
beforeEach(^{
|
||||
model = [[MTLTestModel alloc] init];
|
||||
JSONDictionary = [MTLJSONAdapter JSONDictionaryFromModel:model error:NULL];
|
||||
|
||||
transformer = [MTLJSONAdapter dictionaryTransformerWithModelClass:MTLTestModel.class];
|
||||
expect(transformer).notTo(beNil());
|
||||
});
|
||||
|
||||
it(@"should transform a JSON dictionary into a model", ^{
|
||||
expect([transformer transformedValue:JSONDictionary]).to(equal(model));
|
||||
});
|
||||
|
||||
it(@"should transform a model into a JSON dictionary", ^{
|
||||
expect(@([transformer.class allowsReverseTransformation])).to(beTruthy());
|
||||
expect([transformer reverseTransformedValue:model]).to(equal(JSONDictionary));
|
||||
});
|
||||
|
||||
itBehavesLike(MTLTransformerErrorExamples, ^{
|
||||
return @{
|
||||
MTLTransformerErrorExamplesTransformer: transformer,
|
||||
MTLTransformerErrorExamplesInvalidTransformationInput: NSNull.null,
|
||||
MTLTransformerErrorExamplesInvalidReverseTransformationInput: NSNull.null
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
describe(@"external representation array transformer", ^{
|
||||
__block NSValueTransformer *transformer;
|
||||
|
||||
__block NSArray *models;
|
||||
__block NSArray *JSONDictionaries;
|
||||
|
||||
beforeEach(^{
|
||||
NSMutableArray *uniqueModels = [NSMutableArray array];
|
||||
NSMutableArray *mutableDictionaries = [NSMutableArray array];
|
||||
|
||||
for (NSUInteger i = 0; i < 10; i++) {
|
||||
MTLTestModel *model = [[MTLTestModel alloc] init];
|
||||
model.count = i;
|
||||
|
||||
[uniqueModels addObject:model];
|
||||
|
||||
NSDictionary *dict = [MTLJSONAdapter JSONDictionaryFromModel:model error:NULL];
|
||||
expect(dict).notTo(beNil());
|
||||
|
||||
[mutableDictionaries addObject:dict];
|
||||
}
|
||||
|
||||
uniqueModels[2] = NSNull.null;
|
||||
mutableDictionaries[2] = NSNull.null;
|
||||
|
||||
models = [uniqueModels copy];
|
||||
JSONDictionaries = [mutableDictionaries copy];
|
||||
|
||||
transformer = [MTLJSONAdapter arrayTransformerWithModelClass:MTLTestModel.class];
|
||||
expect(transformer).notTo(beNil());
|
||||
});
|
||||
|
||||
it(@"should transform JSON dictionaries into models", ^{
|
||||
expect([transformer transformedValue:JSONDictionaries]).to(equal(models));
|
||||
});
|
||||
|
||||
it(@"should transform models into JSON dictionaries", ^{
|
||||
expect(@([transformer.class allowsReverseTransformation])).to(beTruthy());
|
||||
expect([transformer reverseTransformedValue:models]).to(equal(JSONDictionaries));
|
||||
});
|
||||
|
||||
itBehavesLike(MTLTransformerErrorExamples, ^{
|
||||
return @{
|
||||
MTLTransformerErrorExamplesTransformer: transformer,
|
||||
MTLTransformerErrorExamplesInvalidTransformationInput: NSNull.null,
|
||||
MTLTransformerErrorExamplesInvalidReverseTransformationInput: NSNull.null
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
it(@"should use receiving class for serialization", ^{
|
||||
NSDictionary *values = @{
|
||||
@"username": @"foo",
|
||||
@"count": @"5",
|
||||
@"nested": @{ @"name": NSNull.null }
|
||||
};
|
||||
|
||||
NSValueTransformer *transformer = [MTLTestJSONAdapter dictionaryTransformerWithModelClass:MTLTestModel.class];
|
||||
|
||||
MTLTestModel *model = [transformer transformedValue:values];
|
||||
expect(model).to(beAKindOf(MTLTestModel.class));
|
||||
expect(model).notTo(beNil());
|
||||
|
||||
NSDictionary *serialized = [transformer reverseTransformedValue:model];
|
||||
expect(serialized).notTo(beNil());
|
||||
expect(serialized[@"test"]).to(beTruthy());
|
||||
});
|
||||
expect(error).notTo.beNil();
|
||||
expect(error.domain).to.equal(MTLJSONAdapterErrorDomain);
|
||||
expect(error.code).to.equal(MTLJSONAdapterErrorNoClassFound);
|
||||
});
|
||||
|
||||
describe(@"Deserializing multiple models", ^{
|
||||
@ -560,11 +371,11 @@ describe(@"Deserializing multiple models", ^{
|
||||
NSError *error = nil;
|
||||
NSArray *mantleModels = [MTLJSONAdapter modelsOfClass:MTLTestModel.class fromJSONArray:JSONModels error:&error];
|
||||
|
||||
expect(error).to(beNil());
|
||||
expect(mantleModels).notTo(beNil());
|
||||
expect(@(mantleModels.count)).to(equal(@2));
|
||||
expect([mantleModels[0] name]).to(equal(@"foo"));
|
||||
expect([mantleModels[1] name]).to(equal(@"bar"));
|
||||
expect(error).to.beNil();
|
||||
expect(mantleModels).toNot.beNil();
|
||||
expect(mantleModels).haveCountOf(2);
|
||||
expect([mantleModels[0] name]).to.equal(@"foo");
|
||||
expect([mantleModels[1] name]).to.equal(@"bar");
|
||||
});
|
||||
|
||||
it(@"should not be affected by a NULL error parameter", ^{
|
||||
@ -572,7 +383,7 @@ describe(@"Deserializing multiple models", ^{
|
||||
NSArray *expected = [MTLJSONAdapter modelsOfClass:MTLTestModel.class fromJSONArray:JSONModels error:&error];
|
||||
NSArray *models = [MTLJSONAdapter modelsOfClass:MTLTestModel.class fromJSONArray:JSONModels error:NULL];
|
||||
|
||||
expect(models).to(equal(expected));
|
||||
expect(models).to.equal(expected);
|
||||
});
|
||||
});
|
||||
|
||||
@ -591,10 +402,10 @@ it(@"should return nil and an error if it fails to initialize any model from an
|
||||
NSError *error = nil;
|
||||
NSArray *mantleModels = [MTLJSONAdapter modelsOfClass:MTLSubstitutingTestModel.class fromJSONArray:JSONModels error:&error];
|
||||
|
||||
expect(error).notTo(beNil());
|
||||
expect(error.domain).to(equal(MTLJSONAdapterErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(MTLJSONAdapterErrorNoClassFound)));
|
||||
expect(mantleModels).to(beNil());
|
||||
expect(error).toNot.beNil();
|
||||
expect(error.domain).to.equal(MTLJSONAdapterErrorDomain);
|
||||
expect(error.code).to.equal(MTLJSONAdapterErrorNoClassFound);
|
||||
expect(mantleModels).to.beNil();
|
||||
});
|
||||
|
||||
it(@"should return an array of dictionaries from models", ^{
|
||||
@ -607,86 +418,13 @@ it(@"should return an array of dictionaries from models", ^{
|
||||
NSError *error;
|
||||
NSArray *JSONArray = [MTLJSONAdapter JSONArrayFromModels:@[ model1, model2 ] error:&error];
|
||||
|
||||
expect(error).to(beNil());
|
||||
expect(error).to.beNil();
|
||||
|
||||
expect(JSONArray).notTo(beNil());
|
||||
expect(@(JSONArray.count)).to(equal(@2));
|
||||
expect(JSONArray[0][@"username"]).to(equal(@"foo"));
|
||||
expect(JSONArray[1][@"username"]).to(equal(@"bar"));
|
||||
expect(JSONArray).toNot.beNil();
|
||||
expect(JSONArray).haveCountOf(2);
|
||||
expect(JSONArray[0][@"username"]).to.equal(@"foo");
|
||||
expect(JSONArray[1][@"username"]).to.equal(@"bar");
|
||||
});
|
||||
|
||||
it(@"should not leak transformers", ^{
|
||||
__weak id weakTransformer;
|
||||
|
||||
@autoreleasepool {
|
||||
id transformer = [MTLJSONAdapter transformerForModelPropertiesOfClass:NSDate.class];
|
||||
weakTransformer = transformer;
|
||||
|
||||
expect(transformer).notTo(beNil());
|
||||
}
|
||||
|
||||
expect(weakTransformer).toEventually(beNil());
|
||||
});
|
||||
|
||||
it(@"should support recursive models", ^{
|
||||
NSDictionary *dictionary = @{
|
||||
@"owner": @{ @"name": @"Cameron" },
|
||||
@"users": @[
|
||||
@{ @"name": @"Dimitri" },
|
||||
@{ @"name": @"John" },
|
||||
],
|
||||
};
|
||||
|
||||
NSError *error = nil;
|
||||
MTLRecursiveGroupModel *group = [MTLJSONAdapter modelOfClass:MTLRecursiveGroupModel.class fromJSONDictionary:dictionary error:&error];
|
||||
expect(group).notTo(beNil());
|
||||
expect(@(group.users.count)).to(equal(@2));
|
||||
});
|
||||
|
||||
it(@"should automatically transform a property that conforms to MTLJSONSerializing", ^{
|
||||
NSDictionary *JSONDictionary = @{
|
||||
@"property": @"property",
|
||||
@"conformingMTLJSONSerializingProperty":@{
|
||||
@"username": @"testName",
|
||||
@"count": @"5",
|
||||
},
|
||||
@"nonConformingMTLJSONSerializingProperty": NSNull.null
|
||||
};
|
||||
|
||||
MTLJSONAdapter *adapter = [[MTLJSONAdapter alloc] initWithModelClass:MTLPropertyDefaultAdapterModel.class];
|
||||
expect(adapter).notTo(beNil());
|
||||
|
||||
NSError *error = nil;
|
||||
MTLPropertyDefaultAdapterModel *model = [MTLJSONAdapter modelOfClass:MTLPropertyDefaultAdapterModel.class fromJSONDictionary:JSONDictionary error:&error];
|
||||
expect(model).notTo(beNil());
|
||||
expect(model.conformingMTLJSONSerializingProperty).notTo(beNil());
|
||||
expect(model.conformingMTLJSONSerializingProperty.name).to(equal(@"testName"));
|
||||
expect(model.nonConformingMTLJSONSerializingProperty).to(beNil());
|
||||
expect(model.property).to(equal(@"property"));
|
||||
expect(error).to(beNil());
|
||||
});
|
||||
|
||||
it(@"should not automatically transform a property that conforms to MTLModel but not MTLJSONSerializing", ^{
|
||||
NSDictionary *JSONDictionary = @{
|
||||
@"property": @"property",
|
||||
@"conformingMTLJSONSerializingProperty":@{
|
||||
@"username": @"testName",
|
||||
@"count": @"5",
|
||||
},
|
||||
/// Triggers an error since the dictionary is not automatically parsed
|
||||
/// and no transformer is supplied.
|
||||
@"nonConformingMTLJSONSerializingProperty": @{}
|
||||
};
|
||||
|
||||
MTLJSONAdapter *adapter = [[MTLJSONAdapter alloc] initWithModelClass:MTLPropertyDefaultAdapterModel.class];
|
||||
expect(adapter).notTo(beNil());
|
||||
|
||||
NSError *error = nil;
|
||||
MTLPropertyDefaultAdapterModel *model = [adapter modelFromJSONDictionary:JSONDictionary error:&error];
|
||||
expect(model).to(beNil());
|
||||
expect(error).notTo(beNil());
|
||||
expect(error.domain).to(equal(MTLTransformerErrorHandlingErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(MTLTransformerErrorHandlingErrorInvalidInput)));
|
||||
});
|
||||
|
||||
QuickSpecEnd
|
||||
SpecEnd
|
||||
|
||||
425
MantleTests/MTLManagedObjectAdapterSpec.m
Normal file
425
MantleTests/MTLManagedObjectAdapterSpec.m
Normal file
@ -0,0 +1,425 @@
|
||||
//
|
||||
// MTLManagedObjectAdapterSpec.m
|
||||
// Mantle
|
||||
//
|
||||
// Created by Justin Spahr-Summers on 2013-05-17.
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import "MTLCoreDataObjects.h"
|
||||
|
||||
#import "MTLCoreDataTestModels.h"
|
||||
|
||||
SpecBegin(MTLManagedObjectAdapter)
|
||||
|
||||
__block NSPersistentStoreCoordinator *persistentStoreCoordinator;
|
||||
|
||||
beforeEach(^{
|
||||
NSURL *url = [[NSBundle bundleForClass:self.class] URLForResource:@"TestModel" withExtension:@"momd"];
|
||||
expect(url).notTo.beNil();
|
||||
|
||||
NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:url];
|
||||
expect(model).notTo.beNil();
|
||||
|
||||
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
|
||||
expect(persistentStoreCoordinator).notTo.beNil();
|
||||
expect([persistentStoreCoordinator addPersistentStoreWithType:NSInMemoryStoreType configuration:nil URL:nil options:nil error:NULL]).notTo.beNil();
|
||||
});
|
||||
|
||||
describe(@"with a confined context", ^{
|
||||
__block NSManagedObjectContext *context;
|
||||
|
||||
__block NSEntityDescription *parentEntity;
|
||||
__block NSEntityDescription *childEntity;
|
||||
|
||||
beforeEach(^{
|
||||
context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSConfinementConcurrencyType];
|
||||
expect(context).notTo.beNil();
|
||||
|
||||
context.undoManager = nil;
|
||||
context.persistentStoreCoordinator = persistentStoreCoordinator;
|
||||
|
||||
parentEntity = [NSEntityDescription entityForName:@"Parent" inManagedObjectContext:context];
|
||||
expect(parentEntity).notTo.beNil();
|
||||
|
||||
childEntity = [NSEntityDescription entityForName:@"Child" inManagedObjectContext:context];
|
||||
expect(childEntity).notTo.beNil();
|
||||
});
|
||||
|
||||
describe(@"+modelOfClass:fromManagedObject:error:", ^{
|
||||
__block MTLParent *parent;
|
||||
|
||||
__block NSDate *date;
|
||||
__block NSString *numberString;
|
||||
__block NSString *requiredString;
|
||||
__block NSURL *URL;
|
||||
|
||||
beforeEach(^{
|
||||
date = [NSDate date];
|
||||
numberString = @"123";
|
||||
requiredString = @"foobar";
|
||||
URL = [NSURL URLWithString:@"http://github.com"];
|
||||
|
||||
parent = [MTLParent insertInManagedObjectContext:context];
|
||||
expect(parent).notTo.beNil();
|
||||
|
||||
for (NSUInteger i = 0; i < 3; i++) {
|
||||
MTLChild *child = [MTLChild insertInManagedObjectContext:context];
|
||||
expect(child).notTo.beNil();
|
||||
|
||||
child.childID = @(i);
|
||||
[parent addOrderedChildrenObject:child];
|
||||
}
|
||||
|
||||
for (NSUInteger i = 3; i < 6; i++) {
|
||||
MTLChild *child = [MTLChild insertInManagedObjectContext:context];
|
||||
expect(child).notTo.beNil();
|
||||
|
||||
child.childID = @(i);
|
||||
[parent addUnorderedChildrenObject:child];
|
||||
}
|
||||
|
||||
parent.string = requiredString;
|
||||
|
||||
__block NSError *error = nil;
|
||||
expect([context save:&error]).to.beTruthy();
|
||||
expect(error).to.beNil();
|
||||
|
||||
// Make sure that pending changes are picked up too.
|
||||
[parent setValue:@(numberString.integerValue) forKey:@"number"];
|
||||
[parent setValue:date forKey:@"date"];
|
||||
[parent setValue:URL.absoluteString forKey:@"url"];
|
||||
});
|
||||
|
||||
it(@"should initialize a MTLParentTestModel with children", ^{
|
||||
NSError *error = nil;
|
||||
MTLParentTestModel *parentModel = [MTLManagedObjectAdapter modelOfClass:MTLParentTestModel.class fromManagedObject:parent error:&error];
|
||||
expect(parentModel).to.beKindOf(MTLParentTestModel.class);
|
||||
expect(error).to.beNil();
|
||||
|
||||
expect(parentModel.date).to.equal(date);
|
||||
expect(parentModel.numberString).to.equal(numberString);
|
||||
expect(parentModel.requiredString).to.equal(requiredString);
|
||||
expect(parentModel.URL).to.equal(URL);
|
||||
|
||||
expect(parentModel.orderedChildren).to.haveCountOf(3);
|
||||
expect(parentModel.unorderedChildren).to.haveCountOf(3);
|
||||
|
||||
for (NSUInteger i = 0; i < 3; i++) {
|
||||
MTLChildTestModel *child = parentModel.orderedChildren[i];
|
||||
expect(child).to.beKindOf(MTLChildTestModel.class);
|
||||
|
||||
expect(child.childID).to.equal(i);
|
||||
expect(child.parent1).to.beNil();
|
||||
expect(child.parent2).to.beIdenticalTo(parentModel);
|
||||
}
|
||||
|
||||
for (MTLChildTestModel *child in parentModel.unorderedChildren) {
|
||||
expect(child).to.beKindOf(MTLChildTestModel.class);
|
||||
|
||||
expect(child.childID).to.beGreaterThanOrEqualTo(3);
|
||||
expect(child.childID).to.beLessThan(6);
|
||||
|
||||
expect(child.parent1).to.beIdenticalTo(parentModel);
|
||||
expect(child.parent2).to.beNil();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe(@"+managedObjectFromModel:insertingIntoContext:error:", ^{
|
||||
__block MTLParentTestModel *parentModel;
|
||||
|
||||
beforeEach(^{
|
||||
parentModel = [MTLParentTestModel modelWithDictionary:@{
|
||||
@"date": [NSDate date],
|
||||
@"numberString": @"1234",
|
||||
@"requiredString": @"foobar"
|
||||
} error:NULL];
|
||||
expect(parentModel).notTo.beNil();
|
||||
|
||||
NSMutableArray *orderedChildren = [NSMutableArray array];
|
||||
NSMutableSet *unorderedChildren = [NSMutableSet set];
|
||||
|
||||
for (NSUInteger i = 0; i < 3; i++) {
|
||||
MTLChildTestModel *child = [MTLChildTestModel modelWithDictionary:@{
|
||||
@"childID": @(i),
|
||||
@"parent2": parentModel
|
||||
} error:NULL];
|
||||
expect(child).notTo.beNil();
|
||||
|
||||
[orderedChildren addObject:child];
|
||||
}
|
||||
|
||||
for (NSUInteger i = 3; i < 6; i++) {
|
||||
MTLChildTestModel *child = [MTLChildTestModel modelWithDictionary:@{
|
||||
@"childID": @(i),
|
||||
@"parent1": parentModel
|
||||
} error:NULL];
|
||||
expect(child).notTo.beNil();
|
||||
|
||||
[unorderedChildren addObject:child];
|
||||
}
|
||||
|
||||
parentModel.orderedChildren = orderedChildren;
|
||||
parentModel.unorderedChildren = unorderedChildren;
|
||||
});
|
||||
|
||||
it(@"should insert a managed object with children", ^{
|
||||
__block NSError *error = nil;
|
||||
MTLParent *parent = [MTLManagedObjectAdapter managedObjectFromModel:parentModel insertingIntoContext:context error:&error];
|
||||
expect(parent).notTo.beNil();
|
||||
expect(parent).to.beKindOf(MTLParent.class);
|
||||
expect(error).to.beNil();
|
||||
|
||||
expect(parent.entity).to.equal(parentEntity);
|
||||
expect(context.insertedObjects).to.contain(parent);
|
||||
|
||||
expect(parent.date).to.equal(parentModel.date);
|
||||
expect(parent.number.stringValue).to.equal(parentModel.numberString);
|
||||
expect(parent.string).to.equal(parentModel.requiredString);
|
||||
|
||||
expect(parent.orderedChildren).to.haveCountOf(3);
|
||||
|
||||
expect(parent.unorderedChildren).to.haveCountOf(3);
|
||||
|
||||
for (NSUInteger i = 0; i < 3; i++) {
|
||||
MTLChild *child = parent.orderedChildren[i];
|
||||
expect(child).to.beKindOf(MTLChild.class);
|
||||
|
||||
expect(child.entity).to.equal(childEntity);
|
||||
expect(context.insertedObjects).to.contain(child);
|
||||
|
||||
expect(child.childID).to.equal(i);
|
||||
expect(child.parent1).to.beNil();
|
||||
expect(child.parent2).to.equal(parent);
|
||||
}
|
||||
|
||||
for (MTLChild *child in parent.unorderedChildren) {
|
||||
expect(child).to.beKindOf(MTLChild.class);
|
||||
|
||||
expect(child.entity).to.equal(childEntity);
|
||||
expect(context.insertedObjects).to.contain(child);
|
||||
|
||||
expect(child.childID).to.beGreaterThanOrEqualTo(3);
|
||||
expect(child.childID).to.beLessThan(6);
|
||||
|
||||
expect(child.parent1).to.equal(parent);
|
||||
expect(child.parent2).to.beNil();
|
||||
}
|
||||
|
||||
expect([context save:&error]).to.beTruthy();
|
||||
expect(error).to.beNil();
|
||||
});
|
||||
|
||||
it(@"should return an error if a model object could not be inserted", ^{
|
||||
MTLFailureModel *failureModel = [MTLFailureModel modelWithDictionary:@{
|
||||
@"notSupported": @"foobar"
|
||||
} error:NULL];
|
||||
|
||||
__block NSError *error = nil;
|
||||
NSManagedObject *failure =[MTLManagedObjectAdapter managedObjectFromModel:failureModel insertingIntoContext:context error:&error];
|
||||
|
||||
expect(failure).to.beNil();
|
||||
expect(error).notTo.beNil();
|
||||
});
|
||||
|
||||
it(@"should return an error if model doesn't validate for attribute description", ^{
|
||||
MTLParentTestModel *parentModel = [MTLParentTestModel modelWithDictionary:@{} error:NULL];
|
||||
|
||||
NSError *error;
|
||||
NSManagedObject *managedObject = [MTLManagedObjectAdapter managedObjectFromModel:parentModel insertingIntoContext:context error:&error];
|
||||
|
||||
expect(managedObject).to.beNil();
|
||||
expect(error).notTo.beNil();
|
||||
});
|
||||
|
||||
it(@"should return nil and error with an illegal JSON mapping", ^{
|
||||
MTLParent *parent = [MTLParent insertInManagedObjectContext:context];
|
||||
expect(parent).notTo.beNil();
|
||||
|
||||
parent.string = @"foobar";
|
||||
|
||||
NSError *error = nil;
|
||||
MTLIllegalManagedObjectMappingModel *model = [MTLManagedObjectAdapter modelOfClass:MTLIllegalManagedObjectMappingModel.class fromManagedObject:parent error:&error];
|
||||
expect(model).beNil();
|
||||
expect(error).notTo.beNil();
|
||||
expect(error.domain).to.equal(MTLManagedObjectAdapterErrorDomain);
|
||||
expect(error.code).to.equal(MTLManagedObjectAdapterErrorInvalidManagedObjectMapping);
|
||||
});
|
||||
|
||||
it(@"should return an error if model doesn't validate for insert", ^{
|
||||
MTLParentIncorrectTestModel *parentModel = [MTLParentIncorrectTestModel modelWithDictionary:@{} error:NULL];
|
||||
|
||||
NSError *error;
|
||||
NSManagedObject *managedObject = [MTLManagedObjectAdapter managedObjectFromModel:parentModel insertingIntoContext:context error:&error];
|
||||
|
||||
expect(managedObject).to.beNil();
|
||||
expect(error).notTo.beNil();
|
||||
});
|
||||
|
||||
it(@"should respect the uniqueness constraint", ^{
|
||||
NSError *errorOne;
|
||||
MTLParent *parentOne = [MTLManagedObjectAdapter managedObjectFromModel:parentModel insertingIntoContext:context error:&errorOne];
|
||||
expect(parentOne).notTo.beNil();
|
||||
expect(errorOne).to.beNil();
|
||||
|
||||
NSError *errorTwo;
|
||||
MTLParent *parentTwo = [MTLManagedObjectAdapter managedObjectFromModel:parentModel insertingIntoContext:context error:&errorTwo];
|
||||
expect(parentTwo).notTo.beNil();
|
||||
expect(errorTwo).to.beNil();
|
||||
|
||||
expect(parentOne.objectID).to.equal(parentTwo.objectID);
|
||||
});
|
||||
|
||||
it(@"should return an error if the uniqueness property cannot be transformed", ^{
|
||||
[parentModel setValue:NSNull.null forKey:@"numberString"];
|
||||
|
||||
NSError *error;
|
||||
MTLParent *parent = [MTLManagedObjectAdapter managedObjectFromModel:parentModel insertingIntoContext:context error:&error];
|
||||
|
||||
expect(parent).to.beNil();
|
||||
expect(error).notTo.beNil();
|
||||
expect(error.domain).to.equal(MTLCoreDataTestModelsDomain);
|
||||
});
|
||||
|
||||
it(@"should update relationships for an existing object", ^{
|
||||
NSError *error;
|
||||
MTLParent *parentOne = [MTLManagedObjectAdapter managedObjectFromModel:parentModel insertingIntoContext:context error:&error];
|
||||
expect(parentOne).notTo.beNil();
|
||||
expect(error).to.beNil();
|
||||
expect(parentOne.orderedChildren).to.haveCountOf(3);
|
||||
expect(parentOne.unorderedChildren).to.haveCountOf(3);
|
||||
|
||||
MTLChild *child1Parent1 = parentOne.orderedChildren[0];
|
||||
MTLChild *child2Parent1 = parentOne.orderedChildren[1];
|
||||
MTLChild *child3Parent1 = parentOne.orderedChildren[2];
|
||||
|
||||
MTLParentTestModel *parentModelCopy = [parentModel copy];
|
||||
[[parentModelCopy mutableOrderedSetValueForKey:@"orderedChildren"] removeObjectAtIndex:1];
|
||||
|
||||
MTLChildTestModel *childToDeleteModel = [parentModelCopy.unorderedChildren anyObject];
|
||||
[[parentModelCopy mutableSetValueForKey:@"unorderedChildren"] removeObject:childToDeleteModel];
|
||||
|
||||
MTLParent *parentTwo = [MTLManagedObjectAdapter managedObjectFromModel:parentModelCopy insertingIntoContext:context error:&error];
|
||||
expect(parentTwo).notTo.beNil();
|
||||
expect(error).to.beNil();
|
||||
expect(parentTwo.orderedChildren).to.haveCountOf(2);
|
||||
expect(parentTwo.unorderedChildren).to.haveCountOf(2);
|
||||
|
||||
for (MTLChild *child in parentTwo.orderedChildren) {
|
||||
expect(child.childID).notTo.equal(child2Parent1.childID);
|
||||
}
|
||||
|
||||
for (MTLChild *child in parentTwo.unorderedChildren) {
|
||||
expect(child.childID).notTo.equal(childToDeleteModel.childID);
|
||||
}
|
||||
|
||||
MTLChild *child1Parent2 = parentTwo.orderedChildren[0];
|
||||
MTLChild *child2Parent2 = parentTwo.orderedChildren[1];
|
||||
expect(child1Parent2).to.equal(child1Parent1);
|
||||
expect(child2Parent2).to.equal(child3Parent1);
|
||||
});
|
||||
|
||||
it(@"should try to merge existing values before overwriting data", ^{
|
||||
NSError *error;
|
||||
MTLParent *parentOne = [MTLManagedObjectAdapter managedObjectFromModel:parentModel insertingIntoContext:context error:&error];
|
||||
expect(parentOne).notTo.beNil();
|
||||
expect(error).to.beNil();
|
||||
|
||||
NSDictionary *updates = @{
|
||||
@"date": [NSDate date],
|
||||
@"numberString": @"1234",
|
||||
@"requiredString": @"We expect this string to be 'merged' after insertion"
|
||||
};
|
||||
|
||||
MTLParentMergingTestModel *updatedParentModel = [MTLParentMergingTestModel modelWithDictionary:updates error:NULL];
|
||||
|
||||
expect(parentModel).notTo.beNil();
|
||||
|
||||
BOOL saveSuccessful = [context save:nil];
|
||||
expect(saveSuccessful).to.equal(YES);
|
||||
|
||||
NSString *initialValueOfRequiredString = updatedParentModel.requiredString;
|
||||
MTLParent *updatedParentOne = [MTLManagedObjectAdapter managedObjectFromModel:updatedParentModel insertingIntoContext:context error:&error];
|
||||
expect(updatedParentOne).notTo.beNil();
|
||||
expect(updatedParentOne.string).notTo.equal(initialValueOfRequiredString);
|
||||
expect(updatedParentOne.string).to.equal(@"merged");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe(@"with a main queue context", ^{
|
||||
__block NSManagedObjectContext *context;
|
||||
|
||||
beforeEach(^{
|
||||
context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
|
||||
expect(context).notTo.beNil();
|
||||
|
||||
context.undoManager = nil;
|
||||
context.persistentStoreCoordinator = persistentStoreCoordinator;
|
||||
});
|
||||
|
||||
it(@"should not deadlock on the main thread", ^{
|
||||
MTLParent *parent = [MTLParent insertInManagedObjectContext:context];
|
||||
expect(parent).notTo.beNil();
|
||||
|
||||
parent.string = @"foobar";
|
||||
|
||||
NSError *error = nil;
|
||||
MTLParentTestModel *parentModel = [MTLManagedObjectAdapter modelOfClass:MTLParentTestModel.class fromManagedObject:parent error:&error];
|
||||
expect(parentModel).to.beKindOf(MTLParentTestModel.class);
|
||||
expect(error).to.beNil();
|
||||
});
|
||||
});
|
||||
|
||||
describe(@"with a child that fails serialization", ^{
|
||||
__block NSManagedObjectContext *context;
|
||||
|
||||
__block NSEntityDescription *parentEntity;
|
||||
__block NSEntityDescription *childEntity;
|
||||
__block MTLParentTestModel *parentModel;
|
||||
|
||||
beforeEach(^{
|
||||
context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSConfinementConcurrencyType];
|
||||
expect(context).notTo.beNil();
|
||||
|
||||
context.undoManager = nil;
|
||||
context.persistentStoreCoordinator = persistentStoreCoordinator;
|
||||
|
||||
parentEntity = [NSEntityDescription entityForName:@"Parent" inManagedObjectContext:context];
|
||||
expect(parentEntity).notTo.beNil();
|
||||
|
||||
childEntity = [NSEntityDescription entityForName:@"BadChild" inManagedObjectContext:context];
|
||||
expect(childEntity).notTo.beNil();
|
||||
|
||||
parentModel = [MTLParentTestModel modelWithDictionary:@{
|
||||
@"date": [NSDate date],
|
||||
@"numberString": @"1234",
|
||||
@"requiredString": @"foobar"
|
||||
} error:NULL];
|
||||
expect(parentModel).notTo.beNil();
|
||||
|
||||
NSMutableArray *orderedChildren = [NSMutableArray array];
|
||||
|
||||
for (NSUInteger i = 3; i < 6; i++) {
|
||||
MTLBadChildTestModel *child = [MTLBadChildTestModel modelWithDictionary:@{
|
||||
@"childID": @(i)
|
||||
} error:NULL];
|
||||
expect(child).notTo.beNil();
|
||||
|
||||
[orderedChildren addObject:child];
|
||||
}
|
||||
|
||||
parentModel.orderedChildren = orderedChildren;
|
||||
});
|
||||
|
||||
it(@"should insert a managed object with children", ^{
|
||||
__block NSError *error = nil;
|
||||
MTLParent *parent = [MTLManagedObjectAdapter managedObjectFromModel:parentModel insertingIntoContext:context error:&error];
|
||||
expect(parent).to.beNil();
|
||||
expect(error).notTo.beNil();
|
||||
expect([context save:&error]).to.beTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
SpecEnd
|
||||
130
MantleTests/MTLManagedObjectSpec.m
Normal file
130
MantleTests/MTLManagedObjectSpec.m
Normal file
@ -0,0 +1,130 @@
|
||||
//
|
||||
// MTLManagedObjectSpec.m
|
||||
// Mantle
|
||||
//
|
||||
// Created by Robert Böhnke on 17/05/14.
|
||||
// Copyright (c) 2014 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import "MTLManagedObject.h"
|
||||
|
||||
#import "MTLManagedObjectSubclasses.h"
|
||||
|
||||
SpecBegin(MTLManagedObject)
|
||||
|
||||
it(@"should include properties from the entity that aren't exposed as properties", ^{
|
||||
NSSet *expectedKeys = [NSSet setWithObjects:@"date", @"string", @"number", @"url", nil];
|
||||
|
||||
expect(MTLManagedObjectParent.propertyKeys).to.equal(expectedKeys);
|
||||
});
|
||||
|
||||
describe(@"when initialized with a dictionary", ^{
|
||||
__block NSDictionary *values;
|
||||
__block MTLManagedObjectParent *model;
|
||||
|
||||
beforeEach(^{
|
||||
NSError *error;
|
||||
|
||||
values = @{
|
||||
@"date": [NSDate dateWithTimeIntervalSince1970:0],
|
||||
@"number": @5,
|
||||
@"string": @"fuzzbuzz",
|
||||
@"url": NSNull.null,
|
||||
};
|
||||
|
||||
model = [MTLManagedObjectParent modelWithDictionary:values error:&error];
|
||||
|
||||
expect(error).to.beNil();
|
||||
expect(model).notTo.beNil();
|
||||
});
|
||||
|
||||
it(@"should initialize with the given values", ^{
|
||||
expect(model.date).to.equal([NSDate dateWithTimeIntervalSince1970:0]);
|
||||
expect(model.number).to.equal(5);
|
||||
expect(model.string).to.equal(@"fuzzbuzz");
|
||||
expect(model.url).to.equal(nil);
|
||||
|
||||
expect(model.dictionaryValue).to.equal(values);
|
||||
expect([model dictionaryWithValuesForKeys:values.allKeys]).to.equal(values);
|
||||
});
|
||||
|
||||
it(@"should not have a context", ^{
|
||||
expect(model.managedObjectContext).to.beNil();
|
||||
});
|
||||
});
|
||||
|
||||
describe(@"Persisting a model", ^{
|
||||
__block NSPersistentStoreCoordinator *persistentStoreCoordinator;
|
||||
__block NSManagedObjectContext *context;
|
||||
__block NSEntityDescription *entity;
|
||||
|
||||
__block MTLManagedObjectParent *parent;
|
||||
|
||||
beforeEach(^{
|
||||
// It's necessary to use the exact same instance for the MOM.
|
||||
// Loading it again from disk using -initWithContentsOfURL: will cause
|
||||
// -[NSManagedObjectContext save:] to fail, even though the two models
|
||||
// are considered equal.
|
||||
//
|
||||
// Is that expected behavior or a bug in CoreData?
|
||||
NSManagedObjectModel *model = MTLManagedObjectParent.managedObjectModel;
|
||||
|
||||
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
|
||||
|
||||
expect(persistentStoreCoordinator).notTo.beNil();
|
||||
expect(persistentStoreCoordinator.managedObjectModel).to.equal(model);
|
||||
expect(persistentStoreCoordinator.managedObjectModel).to.equal(MTLManagedObjectParent.managedObjectModel);
|
||||
|
||||
NSPersistentStore *store = [persistentStoreCoordinator
|
||||
addPersistentStoreWithType:NSInMemoryStoreType
|
||||
configuration:nil
|
||||
URL:nil
|
||||
options:nil
|
||||
error:NULL];
|
||||
|
||||
expect(store).notTo.beNil();
|
||||
|
||||
context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSConfinementConcurrencyType];
|
||||
expect(context).notTo.beNil();
|
||||
|
||||
context.undoManager = nil;
|
||||
context.persistentStoreCoordinator = persistentStoreCoordinator;
|
||||
|
||||
entity = [NSEntityDescription entityForName:@"Parent" inManagedObjectContext:context];
|
||||
expect(entity).notTo.beNil();
|
||||
|
||||
parent = [MTLManagedObjectParent modelWithDictionary:@{
|
||||
@"date": [NSDate dateWithTimeIntervalSince1970:0],
|
||||
@"number": @5,
|
||||
@"string": @"fuzzbuzz",
|
||||
@"url": NSNull.null,
|
||||
} error:NULL];
|
||||
expect(parent.entity).to.equal(entity);
|
||||
|
||||
[context insertObject:parent];
|
||||
|
||||
NSError *error;
|
||||
[context save:&error];
|
||||
|
||||
expect(error).to.beNil();
|
||||
});
|
||||
|
||||
it(@"should give it a context", ^{
|
||||
expect(parent.managedObjectContext).to.equal(context);
|
||||
});
|
||||
|
||||
it(@"should allow it to be fetched", ^{
|
||||
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Parent"];
|
||||
request.predicate = [NSPredicate predicateWithFormat:@"string == 'fuzzbuzz'"];
|
||||
|
||||
NSError *error;
|
||||
id result = [context executeFetchRequest:request error:&error].lastObject;
|
||||
|
||||
expect(error).to.beNil();
|
||||
|
||||
expect(result).notTo.beNil();
|
||||
expect(result).to.equal(parent);
|
||||
});
|
||||
});
|
||||
|
||||
SpecEnd
|
||||
20
MantleTests/MTLManagedObjectSubclasses.h
Normal file
20
MantleTests/MTLManagedObjectSubclasses.h
Normal file
@ -0,0 +1,20 @@
|
||||
//
|
||||
// MTLManagedObjectSubclasses.h
|
||||
// Mantle
|
||||
//
|
||||
// Created by Robert Böhnke on 17/05/14.
|
||||
// Copyright (c) 2014 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Mantle/Mantle.h>
|
||||
|
||||
@interface MTLManagedObjectParent : MTLManagedObject
|
||||
|
||||
@property (readwrite, nonatomic, strong) NSDate *date;
|
||||
@property (readwrite, nonatomic, strong) NSNumber *number;
|
||||
@property (readwrite, nonatomic, copy) NSString *string;
|
||||
@property (readwrite, nonatomic, copy) NSString *url;
|
||||
|
||||
+ (NSManagedObjectModel *)managedObjectModel;
|
||||
|
||||
@end
|
||||
34
MantleTests/MTLManagedObjectSubclasses.m
Normal file
34
MantleTests/MTLManagedObjectSubclasses.m
Normal file
@ -0,0 +1,34 @@
|
||||
//
|
||||
// MTLManagedObjectSubclasses.m
|
||||
// Mantle
|
||||
//
|
||||
// Created by Robert Böhnke on 17/05/14.
|
||||
// Copyright (c) 2014 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import "MTLManagedObjectSubclasses.h"
|
||||
|
||||
@implementation MTLManagedObjectParent
|
||||
|
||||
@dynamic date;
|
||||
@dynamic number;
|
||||
@dynamic string;
|
||||
@dynamic url;
|
||||
|
||||
+ (NSManagedObjectModel *)managedObjectModel {
|
||||
static NSManagedObjectModel *model;
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
NSURL *url = [[NSBundle bundleForClass:self.class] URLForResource:@"MTLManagedObjectTest" withExtension:@"momd"];
|
||||
|
||||
model = [[NSManagedObjectModel alloc] initWithContentsOfURL:url];
|
||||
});
|
||||
|
||||
return model;
|
||||
}
|
||||
|
||||
+ (NSEntityDescription *)entityDescription {
|
||||
return [[self managedObjectModel] entitiesByName][@"Parent"];
|
||||
}
|
||||
|
||||
@end
|
||||
@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<model userDefinedModelVersionIdentifier="" type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" lastSavedToolsVersion="5064" systemVersion="13C1021" minimumToolsVersion="Xcode 4.3" macOSVersion="Automatic" iOSVersion="Automatic">
|
||||
<entity name="Parent" representedClassName="MTLManagedObjectParent" syncable="YES">
|
||||
<attribute name="date" optional="YES" attributeType="Date" syncable="YES"/>
|
||||
<attribute name="number" optional="YES" attributeType="Integer 64" defaultValueString="0" syncable="YES"/>
|
||||
<attribute name="string" attributeType="String" syncable="YES"/>
|
||||
<attribute name="url" optional="YES" attributeType="Transformable" syncable="YES"/>
|
||||
</entity>
|
||||
<elements>
|
||||
<element name="Parent" positionX="-63" positionY="-18" width="128" height="103"/>
|
||||
</elements>
|
||||
</model>
|
||||
@ -6,39 +6,35 @@
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Mantle/Mantle.h>
|
||||
#import <Nimble/Nimble.h>
|
||||
#import <Quick/Quick.h>
|
||||
|
||||
#import "MTLTestModel.h"
|
||||
|
||||
QuickSpecBegin(MTLModelNSCoding)
|
||||
SpecBegin(MTLModelNSCoding)
|
||||
|
||||
it(@"should have default encoding behaviors", ^{
|
||||
NSDictionary *behaviors = MTLTestModel.encodingBehaviorsByPropertyKey;
|
||||
expect(behaviors).notTo(beNil());
|
||||
expect(behaviors).notTo.beNil();
|
||||
|
||||
expect(behaviors[@"name"]).to(equal(@(MTLModelEncodingBehaviorUnconditional)));
|
||||
expect(behaviors[@"count"]).to(equal(@(MTLModelEncodingBehaviorUnconditional)));
|
||||
expect(behaviors[@"weakModel"]).to(equal(@(MTLModelEncodingBehaviorConditional)));
|
||||
expect(behaviors[@"dynamicName"]).to(beNil());
|
||||
expect(behaviors[@"name"]).to.equal(@(MTLModelEncodingBehaviorUnconditional));
|
||||
expect(behaviors[@"count"]).to.equal(@(MTLModelEncodingBehaviorUnconditional));
|
||||
expect(behaviors[@"weakModel"]).to.equal(@(MTLModelEncodingBehaviorConditional));
|
||||
expect(behaviors[@"dynamicName"]).to.beNil();
|
||||
});
|
||||
|
||||
it(@"should have default allowed classes", ^{
|
||||
NSDictionary *allowedClasses = MTLTestModel.allowedSecureCodingClassesByPropertyKey;
|
||||
expect(allowedClasses).notTo(beNil());
|
||||
|
||||
expect(allowedClasses[@"name"]).to(equal(@[ NSString.class ]));
|
||||
expect(allowedClasses[@"count"]).to(equal(@[ NSValue.class ]));
|
||||
expect(allowedClasses[@"weakModel"]).to(equal(@[ MTLEmptyTestModel.class ]));
|
||||
expect(allowedClasses).notTo.beNil();
|
||||
|
||||
expect(allowedClasses[@"name"]).to.equal(@[ NSString.class ]);
|
||||
expect(allowedClasses[@"count"]).to.equal(@[ NSValue.class ]);
|
||||
expect(allowedClasses[@"weakModel"]).to.equal(@[ MTLEmptyTestModel.class ]);
|
||||
|
||||
// Not encoded into archives.
|
||||
expect(allowedClasses[@"nestedName"]).to(beNil());
|
||||
expect(allowedClasses[@"dynamicName"]).to(beNil());
|
||||
expect(allowedClasses[@"nestedName"]).to.beNil();
|
||||
expect(allowedClasses[@"dynamicName"]).to.beNil();
|
||||
});
|
||||
|
||||
it(@"should default to version 0", ^{
|
||||
expect(@(MTLEmptyTestModel.modelVersion)).to(equal(@0));
|
||||
expect(MTLEmptyTestModel.modelVersion).to.equal(0);
|
||||
});
|
||||
|
||||
describe(@"archiving", ^{
|
||||
@ -50,7 +46,7 @@ describe(@"archiving", ^{
|
||||
|
||||
beforeEach(^{
|
||||
emptyModel = [[MTLEmptyTestModel alloc] init];
|
||||
expect(emptyModel).notTo(beNil());
|
||||
expect(emptyModel).notTo.beNil();
|
||||
|
||||
values = @{
|
||||
@"name": @"foobar",
|
||||
@ -59,77 +55,77 @@ describe(@"archiving", ^{
|
||||
|
||||
NSError *error = nil;
|
||||
model = [[MTLTestModel alloc] initWithDictionary:values error:&error];
|
||||
expect(model).notTo(beNil());
|
||||
expect(error).to(beNil());
|
||||
expect(model).notTo.beNil();
|
||||
expect(error).to.beNil();
|
||||
|
||||
archiveAndUnarchiveModel = [^{
|
||||
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:model];
|
||||
expect(data).notTo(beNil());
|
||||
expect(data).notTo.beNil();
|
||||
|
||||
MTLTestModel *unarchivedModel = [NSKeyedUnarchiver unarchiveObjectWithData:data];
|
||||
expect(unarchivedModel).notTo(beNil());
|
||||
expect(unarchivedModel).notTo.beNil();
|
||||
|
||||
return unarchivedModel;
|
||||
} copy];
|
||||
});
|
||||
|
||||
it(@"should archive unconditional properties", ^{
|
||||
expect(archiveAndUnarchiveModel()).to(equal(model));
|
||||
expect(archiveAndUnarchiveModel()).to.equal(model);
|
||||
});
|
||||
|
||||
it(@"should not archive excluded properties", ^{
|
||||
model.nestedName = @"foobar";
|
||||
|
||||
|
||||
MTLTestModel *unarchivedModel = archiveAndUnarchiveModel();
|
||||
expect(unarchivedModel.nestedName).to(beNil());
|
||||
expect(unarchivedModel).notTo(equal(model));
|
||||
expect(unarchivedModel.nestedName).to.beNil();
|
||||
expect(unarchivedModel).notTo.equal(model);
|
||||
|
||||
model.nestedName = nil;
|
||||
expect(unarchivedModel).to(equal(model));
|
||||
expect(unarchivedModel).to.equal(model);
|
||||
});
|
||||
|
||||
it(@"should not archive conditional properties if not encoded elsewhere", ^{
|
||||
model.weakModel = emptyModel;
|
||||
|
||||
|
||||
MTLTestModel *unarchivedModel = archiveAndUnarchiveModel();
|
||||
expect(unarchivedModel.weakModel).to(beNil());
|
||||
expect(unarchivedModel.weakModel).to.beNil();
|
||||
});
|
||||
|
||||
it(@"should archive conditional properties if encoded elsewhere", ^{
|
||||
model.weakModel = emptyModel;
|
||||
|
||||
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:@[ model, emptyModel ]];
|
||||
expect(data).notTo(beNil());
|
||||
expect(data).notTo.beNil();
|
||||
|
||||
NSArray *objects = [NSKeyedUnarchiver unarchiveObjectWithData:data];
|
||||
expect(@(objects.count)).to(equal(@2));
|
||||
expect(objects[1]).to(equal(emptyModel));
|
||||
|
||||
expect(objects.count).to.equal(2);
|
||||
expect(objects[1]).to.equal(emptyModel);
|
||||
|
||||
MTLTestModel *unarchivedModel = objects[0];
|
||||
expect(unarchivedModel).to(equal(model));
|
||||
expect(unarchivedModel.weakModel).to(equal(emptyModel));
|
||||
expect(unarchivedModel).to.equal(model);
|
||||
expect(unarchivedModel.weakModel).to.equal(emptyModel);
|
||||
});
|
||||
|
||||
it(@"should invoke custom decoding logic", ^{
|
||||
MTLTestModel.modelVersion = 0;
|
||||
|
||||
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:model];
|
||||
expect(data).notTo(beNil());
|
||||
expect(data).notTo.beNil();
|
||||
|
||||
MTLTestModel.modelVersion = 1;
|
||||
|
||||
MTLTestModel *unarchivedModel = [NSKeyedUnarchiver unarchiveObjectWithData:data];
|
||||
expect(unarchivedModel).notTo(beNil());
|
||||
expect(unarchivedModel.name).to(equal(@"M: foobar"));
|
||||
expect(@(unarchivedModel.count)).to(equal(@5));
|
||||
expect(unarchivedModel).notTo.beNil();
|
||||
expect(unarchivedModel.name).to.equal(@"M: foobar");
|
||||
expect(unarchivedModel.count).to.equal(@5);
|
||||
});
|
||||
|
||||
it(@"should unarchive an external representation from the old model format", ^{
|
||||
NSURL *archiveURL = [[NSBundle bundleForClass:self.class] URLForResource:@"MTLTestModel-OldArchive" withExtension:@"plist"];
|
||||
expect(archiveURL).notTo(beNil());
|
||||
expect(archiveURL).notTo.beNil();
|
||||
|
||||
MTLTestModel *unarchivedModel = [NSKeyedUnarchiver unarchiveObjectWithFile:archiveURL.path];
|
||||
expect(unarchivedModel).notTo(beNil());
|
||||
expect(unarchivedModel).notTo.beNil();
|
||||
|
||||
NSDictionary *expectedValues = @{
|
||||
@"name": @"foobar",
|
||||
@ -137,9 +133,9 @@ describe(@"archiving", ^{
|
||||
@"nestedName": @"fuzzbuzz",
|
||||
@"weakModel": NSNull.null,
|
||||
};
|
||||
|
||||
expect(unarchivedModel.dictionaryValue).to(equal(expectedValues));
|
||||
|
||||
expect(unarchivedModel.dictionaryValue).to.equal(expectedValues);
|
||||
});
|
||||
});
|
||||
|
||||
QuickSpecEnd
|
||||
SpecEnd
|
||||
|
||||
@ -6,29 +6,30 @@
|
||||
// Copyright (c) 2012 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Mantle/Mantle.h>
|
||||
#import <Nimble/Nimble.h>
|
||||
#import <Quick/Quick.h>
|
||||
#import <objc/runtime.h>
|
||||
|
||||
#import "EXTRuntimeExtensions.h"
|
||||
#import "EXTScope.h"
|
||||
|
||||
#import "MTLTestModel.h"
|
||||
|
||||
QuickSpecBegin(MTLModelSpec)
|
||||
SpecBegin(MTLModel)
|
||||
|
||||
it(@"should not loop infinitely in +propertyKeys without any properties", ^{
|
||||
expect(MTLEmptyTestModel.propertyKeys).to(equal([NSSet set]));
|
||||
expect(MTLEmptyTestModel.propertyKeys).to.equal([NSSet set]);
|
||||
});
|
||||
|
||||
it(@"should not include dynamic readonly properties in +propertyKeys", ^{
|
||||
NSSet *expectedKeys = [NSSet setWithObjects:@"name", @"count", @"nestedName", @"weakModel", nil];
|
||||
expect(MTLTestModel.propertyKeys).to(equal(expectedKeys));
|
||||
expect(MTLTestModel.propertyKeys).to.equal(expectedKeys);
|
||||
});
|
||||
|
||||
it(@"should initialize with default values", ^{
|
||||
MTLTestModel *model = [[MTLTestModel alloc] init];
|
||||
expect(model).notTo(beNil());
|
||||
expect(model).notTo.beNil();
|
||||
|
||||
expect(model.name).to(beNil());
|
||||
expect(@(model.count)).to(equal(@1));
|
||||
expect(model.name).to.beNil();
|
||||
expect(model.count).to.equal(1);
|
||||
|
||||
NSDictionary *expectedValues = @{
|
||||
@"name": NSNull.null,
|
||||
@ -37,18 +38,18 @@ it(@"should initialize with default values", ^{
|
||||
@"weakModel": NSNull.null,
|
||||
};
|
||||
|
||||
expect(model.dictionaryValue).to(equal(expectedValues));
|
||||
expect([model dictionaryWithValuesForKeys:expectedValues.allKeys]).to(equal(expectedValues));
|
||||
expect(model.dictionaryValue).to.equal(expectedValues);
|
||||
expect([model dictionaryWithValuesForKeys:expectedValues.allKeys]).to.equal(expectedValues);
|
||||
});
|
||||
|
||||
it(@"should initialize to default values with a nil dictionary", ^{
|
||||
NSError *error = nil;
|
||||
MTLTestModel *dictionaryModel = [[MTLTestModel alloc] initWithDictionary:nil error:&error];
|
||||
expect(dictionaryModel).notTo(beNil());
|
||||
expect(error).to(beNil());
|
||||
expect(dictionaryModel).notTo.beNil();
|
||||
expect(error).to.beNil();
|
||||
|
||||
MTLTestModel *defaultModel = [[MTLTestModel alloc] init];
|
||||
expect(dictionaryModel).to(equal(defaultModel));
|
||||
expect(dictionaryModel).to.equal(defaultModel);
|
||||
});
|
||||
|
||||
describe(@"with a dictionary of values", ^{
|
||||
@ -58,7 +59,7 @@ describe(@"with a dictionary of values", ^{
|
||||
|
||||
beforeEach(^{
|
||||
emptyModel = [[MTLEmptyTestModel alloc] init];
|
||||
expect(emptyModel).notTo(beNil());
|
||||
expect(emptyModel).notTo.beNil();
|
||||
|
||||
values = @{
|
||||
@"name": @"foobar",
|
||||
@ -69,96 +70,86 @@ describe(@"with a dictionary of values", ^{
|
||||
|
||||
NSError *error = nil;
|
||||
model = [[MTLTestModel alloc] initWithDictionary:values error:&error];
|
||||
expect(model).notTo(beNil());
|
||||
expect(error).to(beNil());
|
||||
expect(model).notTo.beNil();
|
||||
expect(error).to.beNil();
|
||||
});
|
||||
|
||||
it(@"should initialize with the given values", ^{
|
||||
expect(model.name).to(equal(@"foobar"));
|
||||
expect(@(model.count)).to(equal(@5));
|
||||
expect(model.nestedName).to(equal(@"fuzzbuzz"));
|
||||
expect(model.weakModel).to(equal(emptyModel));
|
||||
expect(model.name).to.equal(@"foobar");
|
||||
expect(model.count).to.equal(5);
|
||||
expect(model.nestedName).to.equal(@"fuzzbuzz");
|
||||
expect(model.weakModel).to.equal(emptyModel);
|
||||
|
||||
expect(model.dictionaryValue).to(equal(values));
|
||||
expect([model dictionaryWithValuesForKeys:values.allKeys]).to(equal(values));
|
||||
expect(model.dictionaryValue).to.equal(values);
|
||||
expect([model dictionaryWithValuesForKeys:values.allKeys]).to.equal(values);
|
||||
});
|
||||
|
||||
it(@"should compare equal to a matching model", ^{
|
||||
expect(model).to(equal(model));
|
||||
expect(model).to.equal(model);
|
||||
|
||||
MTLTestModel *matchingModel = [[MTLTestModel alloc] initWithDictionary:values error:NULL];
|
||||
expect(model).to(equal(matchingModel));
|
||||
expect(@(model.hash)).to(equal(@(matchingModel.hash)));
|
||||
expect(model.dictionaryValue).to(equal(matchingModel.dictionaryValue));
|
||||
expect(model).to.equal(matchingModel);
|
||||
expect(model.hash).to.equal(matchingModel.hash);
|
||||
expect(model.dictionaryValue).to.equal(matchingModel.dictionaryValue);
|
||||
});
|
||||
|
||||
it(@"should not compare equal to different model", ^{
|
||||
MTLTestModel *differentModel = [[MTLTestModel alloc] init];
|
||||
expect(model).notTo(equal(differentModel));
|
||||
expect(model.dictionaryValue).notTo(equal(differentModel.dictionaryValue));
|
||||
expect(model).notTo.equal(differentModel);
|
||||
expect(model.dictionaryValue).notTo.equal(differentModel.dictionaryValue);
|
||||
});
|
||||
|
||||
it(@"should implement <NSCopying>", ^{
|
||||
MTLTestModel *copiedModel = [model copy];
|
||||
expect(copiedModel).to(equal(model));
|
||||
expect(copiedModel).notTo(beIdenticalTo(model));
|
||||
expect(copiedModel).to.equal(model);
|
||||
expect(copiedModel).notTo.beIdenticalTo(model);
|
||||
});
|
||||
|
||||
it(@"should not consider -weakModel for equality", ^{
|
||||
MTLTestModel *copiedModel = [model copy];
|
||||
copiedModel.weakModel = nil;
|
||||
|
||||
expect(model).to(equal(copiedModel));
|
||||
expect(model).to.equal(copiedModel);
|
||||
});
|
||||
});
|
||||
|
||||
it(@"should fail to initialize if dictionary validation fails", ^{
|
||||
NSError *error = nil;
|
||||
MTLTestModel *model = [[MTLTestModel alloc] initWithDictionary:@{ @"name": @"this is too long a name" } error:&error];
|
||||
expect(model).to(beNil());
|
||||
expect(model).to.beNil();
|
||||
|
||||
expect(error).notTo(beNil());
|
||||
expect(error.domain).to(equal(MTLTestModelErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(MTLTestModelNameTooLong)));
|
||||
expect(error).notTo.beNil();
|
||||
expect(error.domain).to.equal(MTLTestModelErrorDomain);
|
||||
expect(error.code).to.equal(MTLTestModelNameTooLong);
|
||||
});
|
||||
|
||||
it(@"should merge two models together", ^{
|
||||
MTLTestModel *target = [[MTLTestModel alloc] initWithDictionary:@{ @"name": @"foo", @"count": @(5) } error:NULL];
|
||||
expect(target).notTo(beNil());
|
||||
expect(target).notTo.beNil();
|
||||
|
||||
MTLTestModel *source = [[MTLTestModel alloc] initWithDictionary:@{ @"name": @"bar", @"count": @(3) } error:NULL];
|
||||
expect(source).notTo(beNil());
|
||||
expect(source).notTo.beNil();
|
||||
|
||||
[target mergeValuesForKeysFromModel:source];
|
||||
|
||||
expect(target.name).to(equal(@"bar"));
|
||||
expect(@(target.count)).to(equal(@8));
|
||||
expect(target.name).to.equal(@"bar");
|
||||
expect(target.count).to.equal(8);
|
||||
});
|
||||
|
||||
it(@"should consider primitive properties permanent", ^{
|
||||
expect(@([MTLStorageBehaviorModel storageBehaviorForPropertyWithKey:@"primitive"])).to(equal(@(MTLPropertyStoragePermanent)));
|
||||
expect([MTLStorageBehaviorModel storageBehaviorForPropertyWithKey:@"primitive"]).to.equal(MTLPropertyStoragePermanent);
|
||||
});
|
||||
|
||||
it(@"should consider object-type assign properties permanent", ^{
|
||||
expect(@([MTLStorageBehaviorModel storageBehaviorForPropertyWithKey:@"assignProperty"])).to(equal(@(MTLPropertyStoragePermanent)));
|
||||
expect([MTLStorageBehaviorModel storageBehaviorForPropertyWithKey:@"assignProperty"]).to.equal(MTLPropertyStoragePermanent);
|
||||
});
|
||||
|
||||
it(@"should consider object-type strong properties permanent", ^{
|
||||
expect(@([MTLStorageBehaviorModel storageBehaviorForPropertyWithKey:@"strongProperty"])).to(equal(@(MTLPropertyStoragePermanent)));
|
||||
expect([MTLStorageBehaviorModel storageBehaviorForPropertyWithKey:@"strongProperty"]).to.equal(MTLPropertyStoragePermanent);
|
||||
});
|
||||
|
||||
it(@"should ignore readonly properties without backing ivar", ^{
|
||||
expect(@([MTLStorageBehaviorModel storageBehaviorForPropertyWithKey:@"notIvarBacked"])).to(equal(@(MTLPropertyStorageNone)));
|
||||
});
|
||||
|
||||
it(@"should consider properties declared in subclass with storage in superclass permanent", ^{
|
||||
expect(@([MTLStorageBehaviorModelSubclass storageBehaviorForPropertyWithKey:@"shadowedInSubclass"])).to(equal(@(MTLPropertyStoragePermanent)));
|
||||
expect(@([MTLStorageBehaviorModelSubclass storageBehaviorForPropertyWithKey:@"declaredInProtocol"])).to(equal(@(MTLPropertyStoragePermanent)));
|
||||
});
|
||||
|
||||
it(@"should ignore optional protocol properties not implemented", ^{
|
||||
expect(@([MTLOptionalPropertyModel storageBehaviorForPropertyWithKey:@"optionalUnimplementedProperty"])).to(equal(@(MTLPropertyStorageNone)));
|
||||
expect(@([MTLOptionalPropertyModel storageBehaviorForPropertyWithKey:@"optionalImplementedProperty"])).to(equal(@(MTLPropertyStoragePermanent)));
|
||||
expect([MTLStorageBehaviorModel storageBehaviorForPropertyWithKey:@"notIvarBacked"]).to.equal(MTLPropertyStorageNone);
|
||||
});
|
||||
|
||||
describe(@"merging with model subclasses", ^{
|
||||
@ -171,7 +162,7 @@ describe(@"merging with model subclasses", ^{
|
||||
@"count": @5
|
||||
} error:NULL];
|
||||
|
||||
expect(superclass).notTo(beNil());
|
||||
expect(superclass).notTo.beNil();
|
||||
|
||||
subclass = [MTLSubclassTestModel modelWithDictionary:@{
|
||||
@"name": @"bar",
|
||||
@ -180,25 +171,24 @@ describe(@"merging with model subclasses", ^{
|
||||
@"role": @"subclass"
|
||||
} error:NULL];
|
||||
|
||||
expect(subclass).notTo(beNil());
|
||||
expect(subclass).notTo.beNil();
|
||||
});
|
||||
|
||||
it(@"should merge from subclass model", ^{
|
||||
[superclass mergeValuesForKeysFromModel:subclass];
|
||||
|
||||
expect(superclass.name).to(equal(@"bar"));
|
||||
expect(@(superclass.count)).to(equal(@8));
|
||||
expect(superclass.name).to.equal(@"bar");
|
||||
expect(superclass.count).to.equal(8);
|
||||
});
|
||||
|
||||
it(@"should merge from superclass model", ^{
|
||||
[subclass mergeValuesForKeysFromModel:superclass];
|
||||
|
||||
expect(subclass.name).to(equal(@"foo"));
|
||||
expect(@(subclass.count)).to(equal(@8));
|
||||
expect(subclass.generation).to(equal(@1));
|
||||
expect(subclass.role).to(equal(@"subclass"));
|
||||
expect(subclass.name).to.equal(@"foo");
|
||||
expect(subclass.count).to.equal(8);
|
||||
expect(subclass.generation).to.equal(1);
|
||||
expect(subclass.role).to.equal(@"subclass");
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
QuickSpecEnd
|
||||
SpecEnd
|
||||
|
||||
@ -6,26 +6,22 @@
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Mantle/Mantle.h>
|
||||
#import <Nimble/Nimble.h>
|
||||
#import <Quick/Quick.h>
|
||||
|
||||
#import "MTLTestModel.h"
|
||||
|
||||
#import "MTLModel.h"
|
||||
|
||||
QuickSpecBegin(MTLModelValidation)
|
||||
SpecBegin(MTLModelValidation)
|
||||
|
||||
it(@"should fail with incorrect values", ^{
|
||||
MTLValidationModel *model = [[MTLValidationModel alloc] init];
|
||||
|
||||
NSError *error = nil;
|
||||
BOOL success = [model validate:&error];
|
||||
expect(@(success)).to(beFalsy());
|
||||
expect(success).to.beFalsy();
|
||||
|
||||
expect(error).notTo(beNil());
|
||||
expect(error.domain).to(equal(MTLTestModelErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(MTLTestModelNameMissing)));
|
||||
expect(error).notTo.beNil();
|
||||
expect(error.domain).to.equal(MTLTestModelErrorDomain);
|
||||
expect(error.code).to.equal(MTLTestModelNameMissing);
|
||||
});
|
||||
|
||||
it(@"should succeed with correct values", ^{
|
||||
@ -33,9 +29,9 @@ it(@"should succeed with correct values", ^{
|
||||
|
||||
NSError *error = nil;
|
||||
BOOL success = [model validate:&error];
|
||||
expect(@(success)).to(beTruthy());
|
||||
expect(success).to.beTruthy();
|
||||
|
||||
expect(error).to(beNil());
|
||||
expect(error).to.beNil();
|
||||
});
|
||||
|
||||
it(@"should apply values returned from -validateValue:error:", ^{
|
||||
@ -43,11 +39,11 @@ it(@"should apply values returned from -validateValue:error:", ^{
|
||||
|
||||
NSError *error = nil;
|
||||
BOOL success = [model validate:&error];
|
||||
expect(@(success)).to(beTruthy());
|
||||
expect(success).to.beTruthy();
|
||||
|
||||
expect(model.name).to(equal(@"foobar"));
|
||||
expect(model.name).to.equal(@"foobar");
|
||||
|
||||
expect(error).to(beNil());
|
||||
expect(error).to.beNil();
|
||||
});
|
||||
|
||||
QuickSpecEnd
|
||||
SpecEnd
|
||||
|
||||
@ -6,9 +6,6 @@
|
||||
// Copyright (c) 2012 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Mantle/Mantle.h>
|
||||
#import <Nimble/Nimble.h>
|
||||
#import <Quick/Quick.h>
|
||||
#import "MTLTransformerErrorExamples.h"
|
||||
|
||||
#import "MTLTestModel.h"
|
||||
@ -20,7 +17,7 @@ enum : NSInteger {
|
||||
MTLPredefinedTransformerAdditionsSpecEnumDefault = 42,
|
||||
} MTLPredefinedTransformerAdditionsSpecEnum;
|
||||
|
||||
QuickSpecBegin(MTLPredefinedTransformerAdditions)
|
||||
SpecBegin(MTLPredefinedTransformerAdditions)
|
||||
|
||||
describe(@"The URL transformer", ^{
|
||||
__block NSValueTransformer *transformer;
|
||||
@ -28,20 +25,20 @@ describe(@"The URL transformer", ^{
|
||||
beforeEach(^{
|
||||
transformer = [NSValueTransformer valueTransformerForName:MTLURLValueTransformerName];
|
||||
|
||||
expect(transformer).notTo(beNil());
|
||||
expect(@([transformer.class allowsReverseTransformation])).to(beTruthy());
|
||||
expect(transformer).notTo.beNil();
|
||||
expect([transformer.class allowsReverseTransformation]).to.beTruthy();
|
||||
});
|
||||
|
||||
it(@"should convert NSStrings to NSURLs and back", ^{
|
||||
NSString *URLString = @"http://www.github.com/";
|
||||
expect([transformer transformedValue:URLString]).to(equal([NSURL URLWithString:URLString]));
|
||||
expect([transformer reverseTransformedValue:[NSURL URLWithString:URLString]]).to(equal(URLString));
|
||||
expect([transformer transformedValue:URLString]).to.equal([NSURL URLWithString:URLString]);
|
||||
expect([transformer reverseTransformedValue:[NSURL URLWithString:URLString]]).to.equal(URLString);
|
||||
|
||||
expect([transformer transformedValue:nil]).to(beNil());
|
||||
expect([transformer reverseTransformedValue:nil]).to(beNil());
|
||||
expect([transformer transformedValue:nil]).to.beNil();
|
||||
expect([transformer reverseTransformedValue:nil]).to.beNil();
|
||||
});
|
||||
|
||||
itBehavesLike(MTLTransformerErrorExamples, ^{
|
||||
itShouldBehaveLike(MTLTransformerErrorExamples, ^{
|
||||
return @{
|
||||
MTLTransformerErrorExamplesTransformer: transformer,
|
||||
MTLTransformerErrorExamplesInvalidTransformationInput: @"not a valid URL",
|
||||
@ -50,41 +47,13 @@ describe(@"The URL transformer", ^{
|
||||
});
|
||||
});
|
||||
|
||||
describe(@"The UUID transformer", ^{
|
||||
__block NSValueTransformer *transformer;
|
||||
|
||||
beforeEach(^{
|
||||
transformer = [NSValueTransformer valueTransformerForName:MTLUUIDValueTransformerName];
|
||||
|
||||
expect(transformer).notTo(beNil());
|
||||
expect(@([transformer.class allowsReverseTransformation])).to(beTruthy());
|
||||
});
|
||||
|
||||
it(@"should convert NSStrings to NSUUIDs and back", ^{
|
||||
NSString *UUIDString = @"4A275FBD-8217-4397-964B-403F4C2B8545";
|
||||
expect([transformer transformedValue:UUIDString]).to(equal([[NSUUID alloc] initWithUUIDString:UUIDString]));
|
||||
expect([transformer reverseTransformedValue:[[NSUUID alloc] initWithUUIDString:UUIDString]]).to(equal(UUIDString));
|
||||
|
||||
expect([transformer transformedValue:nil]).to(beNil());
|
||||
expect([transformer reverseTransformedValue:nil]).to(beNil());
|
||||
});
|
||||
|
||||
itBehavesLike(MTLTransformerErrorExamples, ^{
|
||||
return @{
|
||||
MTLTransformerErrorExamplesTransformer: transformer,
|
||||
MTLTransformerErrorExamplesInvalidTransformationInput: @"not a valid UUID",
|
||||
MTLTransformerErrorExamplesInvalidReverseTransformationInput: NSNull.null
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
describe(@"The number transformer", ^{
|
||||
__block NSValueTransformer *transformer;
|
||||
|
||||
beforeEach(^{
|
||||
transformer = [NSValueTransformer valueTransformerForName:MTLBooleanValueTransformerName];
|
||||
expect(transformer).notTo(beNil());
|
||||
expect(@([transformer.class allowsReverseTransformation])).to(beTruthy());
|
||||
expect(transformer).notTo.beNil();
|
||||
expect([transformer.class allowsReverseTransformation]).to.beTruthy();
|
||||
});
|
||||
|
||||
it(@"it convert int- to boolean-backed NSNumbers and back", ^{
|
||||
@ -93,23 +62,23 @@ describe(@"The number transformer", ^{
|
||||
NSNumber *booleanYES = @(1);
|
||||
NSNumber *booleanNO = @(0);
|
||||
|
||||
expect([transformer transformedValue:booleanYES]).to(equal([NSNumber numberWithBool:YES]));
|
||||
expect([transformer transformedValue:booleanYES]).to(beIdenticalTo((id)kCFBooleanTrue));
|
||||
expect([transformer transformedValue:booleanYES]).to.equal([NSNumber numberWithBool:YES]);
|
||||
expect([transformer transformedValue:booleanYES]).to.beIdenticalTo((id)kCFBooleanTrue);
|
||||
|
||||
expect([transformer reverseTransformedValue:booleanYES]).to(equal([NSNumber numberWithBool:YES]));
|
||||
expect([transformer reverseTransformedValue:booleanYES]).to(beIdenticalTo((id)kCFBooleanTrue));
|
||||
expect([transformer reverseTransformedValue:booleanYES]).to.equal([NSNumber numberWithBool:YES]);
|
||||
expect([transformer reverseTransformedValue:booleanYES]).to.beIdenticalTo((id)kCFBooleanTrue);
|
||||
|
||||
expect([transformer transformedValue:booleanNO]).to(equal([NSNumber numberWithBool:NO]));
|
||||
expect([transformer transformedValue:booleanNO]).to(beIdenticalTo((id)kCFBooleanFalse));
|
||||
expect([transformer transformedValue:booleanNO]).to.equal([NSNumber numberWithBool:NO]);
|
||||
expect([transformer transformedValue:booleanNO]).to.beIdenticalTo((id)kCFBooleanFalse);
|
||||
|
||||
expect([transformer reverseTransformedValue:booleanNO]).to(equal([NSNumber numberWithBool:NO]));
|
||||
expect([transformer reverseTransformedValue:booleanNO]).to(beIdenticalTo((id)kCFBooleanFalse));
|
||||
expect([transformer reverseTransformedValue:booleanNO]).to.equal([NSNumber numberWithBool:NO]);
|
||||
expect([transformer reverseTransformedValue:booleanNO]).to.beIdenticalTo((id)kCFBooleanFalse);
|
||||
|
||||
expect([transformer transformedValue:nil]).to(beNil());
|
||||
expect([transformer reverseTransformedValue:nil]).to(beNil());
|
||||
expect([transformer transformedValue:nil]).to.beNil();
|
||||
expect([transformer reverseTransformedValue:nil]).to.beNil();
|
||||
});
|
||||
|
||||
itBehavesLike(MTLTransformerErrorExamples, ^{
|
||||
itShouldBehaveLike(MTLTransformerErrorExamples, ^{
|
||||
return @{
|
||||
MTLTransformerErrorExamplesTransformer: transformer,
|
||||
MTLTransformerErrorExamplesInvalidTransformationInput: NSNull.null,
|
||||
@ -118,9 +87,94 @@ describe(@"The number transformer", ^{
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe(@"JSON transformers", ^{
|
||||
describe(@"dictionary transformer", ^{
|
||||
__block NSValueTransformer *transformer;
|
||||
|
||||
__block MTLTestModel *model;
|
||||
__block NSDictionary *JSONDictionary;
|
||||
|
||||
before(^{
|
||||
model = [[MTLTestModel alloc] init];
|
||||
JSONDictionary = [MTLJSONAdapter JSONDictionaryFromModel:model error:NULL];
|
||||
|
||||
transformer = [NSValueTransformer mtl_JSONDictionaryTransformerWithModelClass:MTLTestModel.class];
|
||||
expect(transformer).notTo.beNil();
|
||||
});
|
||||
|
||||
it(@"should transform a JSON dictionary into a model", ^{
|
||||
expect([transformer transformedValue:JSONDictionary]).to.equal(model);
|
||||
});
|
||||
|
||||
it(@"should transform a model into a JSON dictionary", ^{
|
||||
expect([transformer.class allowsReverseTransformation]).to.beTruthy();
|
||||
expect([transformer reverseTransformedValue:model]).to.equal(JSONDictionary);
|
||||
});
|
||||
|
||||
itShouldBehaveLike(MTLTransformerErrorExamples, ^{
|
||||
return @{
|
||||
MTLTransformerErrorExamplesTransformer: transformer,
|
||||
MTLTransformerErrorExamplesInvalidTransformationInput: NSNull.null,
|
||||
MTLTransformerErrorExamplesInvalidReverseTransformationInput: NSNull.null
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
describe(@"external representation array transformer", ^{
|
||||
__block NSValueTransformer *transformer;
|
||||
|
||||
__block NSArray *models;
|
||||
__block NSArray *JSONDictionaries;
|
||||
|
||||
beforeEach(^{
|
||||
NSMutableArray *uniqueModels = [NSMutableArray array];
|
||||
NSMutableArray *mutableDictionaries = [NSMutableArray array];
|
||||
|
||||
for (NSUInteger i = 0; i < 10; i++) {
|
||||
MTLTestModel *model = [[MTLTestModel alloc] init];
|
||||
model.count = i;
|
||||
|
||||
[uniqueModels addObject:model];
|
||||
|
||||
NSDictionary *dict = [MTLJSONAdapter JSONDictionaryFromModel:model error:NULL];
|
||||
expect(dict).notTo.beNil();
|
||||
|
||||
[mutableDictionaries addObject:dict];
|
||||
}
|
||||
|
||||
uniqueModels[2] = NSNull.null;
|
||||
mutableDictionaries[2] = NSNull.null;
|
||||
|
||||
models = [uniqueModels copy];
|
||||
JSONDictionaries = [mutableDictionaries copy];
|
||||
|
||||
transformer = [NSValueTransformer mtl_JSONArrayTransformerWithModelClass:MTLTestModel.class];
|
||||
expect(transformer).notTo.beNil();
|
||||
});
|
||||
|
||||
it(@"should transform JSON dictionaries into models", ^{
|
||||
expect([transformer transformedValue:JSONDictionaries]).to.equal(models);
|
||||
});
|
||||
|
||||
it(@"should transform models into JSON dictionaries", ^{
|
||||
expect([transformer.class allowsReverseTransformation]).to.beTruthy();
|
||||
expect([transformer reverseTransformedValue:models]).to.equal(JSONDictionaries);
|
||||
});
|
||||
|
||||
itShouldBehaveLike(MTLTransformerErrorExamples, ^{
|
||||
return @{
|
||||
MTLTransformerErrorExamplesTransformer: transformer,
|
||||
MTLTransformerErrorExamplesInvalidTransformationInput: NSNull.null,
|
||||
MTLTransformerErrorExamplesInvalidReverseTransformationInput: NSNull.null
|
||||
};
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe(@"+mtl_arrayMappingTransformerWithTransformer:", ^{
|
||||
__block NSValueTransformer *transformer;
|
||||
|
||||
|
||||
NSArray *URLStrings = @[
|
||||
@"https://github.com/",
|
||||
@"https://github.com/MantleFramework",
|
||||
@ -131,46 +185,46 @@ describe(@"+mtl_arrayMappingTransformerWithTransformer:", ^{
|
||||
[NSURL URLWithString:@"https://github.com/MantleFramework"],
|
||||
[NSURL URLWithString:@"http://apple.com"]
|
||||
];
|
||||
|
||||
|
||||
describe(@"when called with a reversible transformer", ^{
|
||||
beforeEach(^{
|
||||
NSValueTransformer *appliedTransformer = [NSValueTransformer valueTransformerForName:MTLURLValueTransformerName];
|
||||
transformer = [NSValueTransformer mtl_arrayMappingTransformerWithTransformer:appliedTransformer];
|
||||
expect(transformer).notTo(beNil());
|
||||
expect(transformer).notTo.beNil();
|
||||
});
|
||||
|
||||
|
||||
it(@"should allow reverse transformation", ^{
|
||||
expect(@([transformer.class allowsReverseTransformation])).to(beTruthy());
|
||||
expect([transformer.class allowsReverseTransformation]).to.beTruthy();
|
||||
});
|
||||
|
||||
|
||||
it(@"should apply the transformer to each element", ^{
|
||||
expect([transformer transformedValue:URLStrings]).to(equal(URLs));
|
||||
expect([transformer transformedValue:URLStrings]).to.equal(URLs);
|
||||
});
|
||||
|
||||
|
||||
it(@"should apply the transformer to each element in reverse", ^{
|
||||
expect([transformer reverseTransformedValue:URLs]).to(equal(URLStrings));
|
||||
expect([transformer reverseTransformedValue:URLs]).to.equal(URLStrings);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
describe(@"when called with a non-reversible transformer", ^{
|
||||
beforeEach(^{
|
||||
NSValueTransformer *appliedTransformer = [MTLValueTransformer transformerUsingForwardBlock:^(NSString *str, BOOL *success, NSError **error) {
|
||||
return [NSURL URLWithString:str];
|
||||
}];
|
||||
transformer = [NSValueTransformer mtl_arrayMappingTransformerWithTransformer:appliedTransformer];
|
||||
expect(transformer).notTo(beNil());
|
||||
expect(transformer).notTo.beNil();
|
||||
});
|
||||
|
||||
|
||||
it(@"should not allow reverse transformation", ^{
|
||||
expect(@([transformer.class allowsReverseTransformation])).to(beFalsy());
|
||||
expect([transformer.class allowsReverseTransformation]).to.beFalsy();
|
||||
});
|
||||
|
||||
|
||||
it(@"should apply the transformer to each element", ^{
|
||||
expect([transformer transformedValue:URLStrings]).to(equal(URLs));
|
||||
expect([transformer transformedValue:URLStrings]).to.equal(URLs);
|
||||
});
|
||||
});
|
||||
|
||||
itBehavesLike(MTLTransformerErrorExamples, ^{
|
||||
|
||||
itShouldBehaveLike(MTLTransformerErrorExamples, ^{
|
||||
return @{
|
||||
MTLTransformerErrorExamplesTransformer: transformer,
|
||||
MTLTransformerErrorExamplesInvalidTransformationInput: NSNull.null,
|
||||
@ -193,17 +247,17 @@ describe(@"value mapping transformer", ^{
|
||||
});
|
||||
|
||||
it(@"should transform enum values into strings", ^{
|
||||
expect([transformer transformedValue:@"negative"]).to(equal(@(MTLPredefinedTransformerAdditionsSpecEnumNegative)));
|
||||
expect([transformer transformedValue:@[ @"zero" ]]).to(equal(@(MTLPredefinedTransformerAdditionsSpecEnumZero)));
|
||||
expect([transformer transformedValue:@"positive"]).to(equal(@(MTLPredefinedTransformerAdditionsSpecEnumPositive)));
|
||||
expect([transformer transformedValue:@"negative"]).to.equal(@(MTLPredefinedTransformerAdditionsSpecEnumNegative));
|
||||
expect([transformer transformedValue:@[ @"zero" ]]).to.equal(@(MTLPredefinedTransformerAdditionsSpecEnumZero));
|
||||
expect([transformer transformedValue:@"positive"]).to.equal(@(MTLPredefinedTransformerAdditionsSpecEnumPositive));
|
||||
});
|
||||
|
||||
it(@"should transform strings into enum values", ^{
|
||||
expect(@([transformer.class allowsReverseTransformation])).to(beTruthy());
|
||||
expect([transformer.class allowsReverseTransformation]).to.beTruthy();
|
||||
|
||||
expect([transformer reverseTransformedValue:@(MTLPredefinedTransformerAdditionsSpecEnumNegative)]).to(equal(@"negative"));
|
||||
expect([transformer reverseTransformedValue:@(MTLPredefinedTransformerAdditionsSpecEnumZero)]).to(equal(@[ @"zero" ]));
|
||||
expect([transformer reverseTransformedValue:@(MTLPredefinedTransformerAdditionsSpecEnumPositive)]).to(equal(@"positive"));
|
||||
expect([transformer reverseTransformedValue:@(MTLPredefinedTransformerAdditionsSpecEnumNegative)]).to.equal(@"negative");
|
||||
expect([transformer reverseTransformedValue:@(MTLPredefinedTransformerAdditionsSpecEnumZero)]).to.equal(@[ @"zero" ]);
|
||||
expect([transformer reverseTransformedValue:@(MTLPredefinedTransformerAdditionsSpecEnumPositive)]).to.equal(@"positive");
|
||||
});
|
||||
|
||||
describe(@"default values", ^{
|
||||
@ -212,93 +266,13 @@ describe(@"value mapping transformer", ^{
|
||||
});
|
||||
|
||||
it(@"should transform unknown strings into the default enum value", ^{
|
||||
expect([transformer transformedValue:@"unknown"]).to(equal(@(MTLPredefinedTransformerAdditionsSpecEnumDefault)));
|
||||
expect([transformer transformedValue:@"unknown"]).to.equal(@(MTLPredefinedTransformerAdditionsSpecEnumDefault));
|
||||
});
|
||||
|
||||
it(@"should transform the default enum value into the default string", ^{
|
||||
expect([transformer reverseTransformedValue:@(MTLPredefinedTransformerAdditionsSpecEnumDefault)]).to(equal(@"default"));
|
||||
expect([transformer reverseTransformedValue:@(MTLPredefinedTransformerAdditionsSpecEnumDefault)]).to.equal(@"default");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe(@"date format transformer", ^{
|
||||
__block NSValueTransformer<MTLTransformerErrorHandling> *transformer;
|
||||
|
||||
beforeEach(^{
|
||||
transformer = [NSValueTransformer mtl_dateTransformerWithDateFormat:@"MMMM d, yyyy" calendar:[NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian] locale:[NSLocale localeWithLocaleIdentifier:@"en_US"] timeZone:[NSTimeZone timeZoneWithName:@"America/Los_Angeles"] defaultDate:nil];
|
||||
expect(transformer).notTo(beNil());
|
||||
expect(@([transformer.class allowsReverseTransformation])).to(beTruthy());
|
||||
expect([transformer transformedValue:nil]).to(beNil());
|
||||
expect([transformer reverseTransformedValue:nil]).to(beNil());
|
||||
});
|
||||
|
||||
it(@"should transform strings into dates", ^{
|
||||
expect([transformer transformedValue:@"September 25, 2015"]).to(equal([NSDate dateWithTimeIntervalSince1970:1443164400]));
|
||||
});
|
||||
|
||||
it(@"should transform dates into strings", ^{
|
||||
expect([transformer reverseTransformedValue:[NSDate dateWithTimeIntervalSince1970:1183135260]]).to(equal(@"June 29, 2007"));
|
||||
});
|
||||
|
||||
it(@"should surface date formatter error descriptions", ^{
|
||||
__block NSError *error;
|
||||
__block BOOL success = NO;
|
||||
|
||||
expect([transformer transformedValue:@"September 37, 2015" success:&success error:&error]).to(beNil());
|
||||
expect(@(success)).to(beFalsy());
|
||||
expect(error).notTo(beNil());
|
||||
expect(error.domain).to(equal(MTLTransformerErrorHandlingErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(MTLTransformerErrorHandlingErrorInvalidInput)));
|
||||
expect(error.userInfo[NSLocalizedFailureReasonErrorKey]).notTo(beNil());
|
||||
});
|
||||
|
||||
itBehavesLike(MTLTransformerErrorExamples, ^{
|
||||
return @{
|
||||
MTLTransformerErrorExamplesTransformer: transformer,
|
||||
MTLTransformerErrorExamplesInvalidTransformationInput: NSNull.null,
|
||||
MTLTransformerErrorExamplesInvalidReverseTransformationInput: NSNull.null
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
describe(@"number format transformer", ^{
|
||||
__block NSValueTransformer<MTLTransformerErrorHandling> *transformer;
|
||||
|
||||
beforeEach(^{
|
||||
transformer = [NSValueTransformer mtl_numberTransformerWithNumberStyle:NSNumberFormatterDecimalStyle locale:[NSLocale localeWithLocaleIdentifier:@"en_US"]];
|
||||
expect(transformer).notTo(beNil());
|
||||
expect(@([transformer.class allowsReverseTransformation])).to(beTruthy());
|
||||
expect([transformer transformedValue:nil]).to(beNil());
|
||||
expect([transformer reverseTransformedValue:nil]).to(beNil());
|
||||
});
|
||||
|
||||
it(@"should transform strings into numbers", ^{
|
||||
expect([transformer transformedValue:@"0.12345"]).to(equal(@0.12345));
|
||||
});
|
||||
|
||||
it(@"should transform numbers into strings", ^{
|
||||
expect([transformer reverseTransformedValue:@12345.678]).to(equal(@"12,345.678"));
|
||||
});
|
||||
|
||||
it(@"should surface number formatter error descriptions", ^{
|
||||
__block NSError *error;
|
||||
__block BOOL success = NO;
|
||||
|
||||
expect([transformer transformedValue:@"Apple" success:&success error:&error]).to(beNil());
|
||||
expect(@(success)).to(beFalsy());
|
||||
expect(error).notTo(beNil());
|
||||
expect(error.domain).to(equal(MTLTransformerErrorHandlingErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(MTLTransformerErrorHandlingErrorInvalidInput)));
|
||||
expect(error.userInfo[NSLocalizedFailureReasonErrorKey]).notTo(beNil());
|
||||
});
|
||||
|
||||
itBehavesLike(MTLTransformerErrorExamples, ^{
|
||||
return @{
|
||||
MTLTransformerErrorExamplesTransformer: transformer,
|
||||
MTLTransformerErrorExamplesInvalidTransformationInput: NSNull.null,
|
||||
MTLTransformerErrorExamplesInvalidReverseTransformationInput: NSNull.null
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
QuickSpecEnd
|
||||
SpecEnd
|
||||
|
||||
@ -8,7 +8,6 @@
|
||||
|
||||
#import <Mantle/Mantle.h>
|
||||
|
||||
// Adds a custom key "test" to constructed JSON.
|
||||
@interface MTLTestJSONAdapter : MTLJSONAdapter
|
||||
|
||||
// These property keys are not serialized.
|
||||
|
||||
@ -18,11 +18,4 @@
|
||||
return copy;
|
||||
}
|
||||
|
||||
- (NSDictionary *)JSONDictionaryFromModel:(id<MTLJSONSerializing>)model error:(NSError **)error {
|
||||
NSDictionary *dictionary = [super JSONDictionaryFromModel:model error:error];
|
||||
return [dictionary mtl_dictionaryByAddingEntriesFromDictionary:@{
|
||||
@"test": @YES
|
||||
}];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@ -6,8 +6,6 @@
|
||||
// Copyright (c) 2012 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Mantle/Mantle.h>
|
||||
|
||||
extern NSString * const MTLTestModelErrorDomain;
|
||||
extern const NSInteger MTLTestModelNameTooLong;
|
||||
extern const NSInteger MTLTestModelNameMissing;
|
||||
@ -64,7 +62,7 @@ extern const NSInteger MTLTestModelNameMissing;
|
||||
@interface MTLSubstitutingTestModel : MTLModel <MTLJSONSerializing>
|
||||
@end
|
||||
|
||||
@interface MTLValidationModel : MTLModel <MTLJSONSerializing>
|
||||
@interface MTLValidationModel : MTLModel
|
||||
|
||||
// Defaults to nil, which is not considered valid.
|
||||
@property (nonatomic, copy) NSString *name;
|
||||
@ -82,27 +80,6 @@ extern const NSInteger MTLTestModelNameMissing;
|
||||
|
||||
@end
|
||||
|
||||
@interface MTLURLSubclassModel : MTLURLModel
|
||||
|
||||
// Defaults to http://github.com/Mantle/Mantle.
|
||||
@property (nonatomic, strong) NSURL *otherURL;
|
||||
|
||||
@end
|
||||
|
||||
@interface MTLUUIDModel : MTLModel <MTLJSONSerializing>
|
||||
|
||||
// Defaults to 4A275FBD-8217-4397-964B-403F4C2B8545
|
||||
@property (nonatomic, strong) NSUUID *UUID;
|
||||
|
||||
@end
|
||||
|
||||
@interface MTLUUIDSubclassModel : MTLUUIDModel
|
||||
|
||||
// Defaults to 593246D2-A290-43D5-9070-A299A489AE29
|
||||
@property (nonatomic, strong) NSUUID *otherUUID;
|
||||
|
||||
@end
|
||||
|
||||
// Conforms to MTLJSONSerializing but does not inherit from the MTLModel class.
|
||||
@interface MTLConformingModel : NSObject <MTLJSONSerializing>
|
||||
|
||||
@ -118,21 +95,6 @@ extern const NSInteger MTLTestModelNameMissing;
|
||||
@property (readonly, nonatomic, weak) id weakProperty;
|
||||
@property (readonly, nonatomic, strong) id strongProperty;
|
||||
|
||||
@property (readonly, nonatomic, strong) id shadowedInSubclass;
|
||||
@property (readonly, nonatomic, strong) id declaredInProtocol;
|
||||
|
||||
@end
|
||||
|
||||
@protocol MTLDateProtocol <NSObject>
|
||||
|
||||
@property (readonly, nonatomic, strong) id declaredInProtocol;
|
||||
|
||||
@end
|
||||
|
||||
@interface MTLStorageBehaviorModelSubclass : MTLStorageBehaviorModel <MTLDateProtocol>
|
||||
|
||||
@property (readonly, nonatomic, strong) id shadowedInSubclass;
|
||||
|
||||
@end
|
||||
|
||||
@interface MTLBoolModel : MTLModel <MTLJSONSerializing>
|
||||
@ -141,12 +103,6 @@ extern const NSInteger MTLTestModelNameMissing;
|
||||
|
||||
@end
|
||||
|
||||
@interface MTLStringModel : MTLModel <MTLJSONSerializing>
|
||||
|
||||
@property (readwrite, nonatomic, copy) NSString *string;
|
||||
|
||||
@end
|
||||
|
||||
@interface MTLIDModel : MTLModel <MTLJSONSerializing>
|
||||
|
||||
@property (nonatomic, strong) id anyObject;
|
||||
@ -190,40 +146,3 @@ extern const NSInteger MTLTestModelNameMissing;
|
||||
@property (readwrite, nonatomic, assign) NSUInteger freshness;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
@protocol MTLOptionalPropertyProtocol
|
||||
|
||||
@optional
|
||||
@property (readwrite, nonatomic, strong) id optionalUnimplementedProperty;
|
||||
@property (readwrite, nonatomic, strong) id optionalImplementedProperty;
|
||||
|
||||
@end
|
||||
|
||||
@interface MTLOptionalPropertyModel : MTLModel <MTLOptionalPropertyProtocol>
|
||||
|
||||
@property (readwrite, nonatomic, strong) id optionalImplementedProperty;
|
||||
|
||||
@end
|
||||
|
||||
|
||||
@interface MTLRecursiveUserModel : MTLModel <MTLJSONSerializing>
|
||||
|
||||
@property (nonatomic, copy, readonly) NSString *name;
|
||||
@property (nonatomic, copy, readonly) NSArray *groups;
|
||||
|
||||
@end
|
||||
|
||||
@interface MTLRecursiveGroupModel : MTLModel <MTLJSONSerializing>
|
||||
|
||||
@property (nonatomic, readonly) MTLRecursiveUserModel *owner;
|
||||
@property (nonatomic, readonly) NSArray *users;
|
||||
@end
|
||||
|
||||
@interface MTLPropertyDefaultAdapterModel : MTLModel<MTLJSONSerializing>
|
||||
|
||||
@property (readwrite, nonatomic, strong) MTLEmptyTestModel *nonConformingMTLJSONSerializingProperty;
|
||||
@property (readwrite, nonatomic, strong) MTLTestModel *conformingMTLJSONSerializingProperty;
|
||||
@property (readwrite, nonatomic, strong) NSString *property;
|
||||
|
||||
@end
|
||||
|
||||
@ -170,12 +170,6 @@ static NSUInteger modelVersion = 1;
|
||||
|
||||
@implementation MTLValidationModel
|
||||
|
||||
+ (NSDictionary *)JSONKeyPathsByPropertyKey {
|
||||
return @{
|
||||
@"name": @"name"
|
||||
};
|
||||
}
|
||||
|
||||
- (BOOL)validateName:(NSString **)name error:(NSError **)error {
|
||||
if (*name != nil) return YES;
|
||||
if (error != NULL) {
|
||||
@ -215,60 +209,6 @@ static NSUInteger modelVersion = 1;
|
||||
|
||||
@end
|
||||
|
||||
@implementation MTLURLSubclassModel
|
||||
|
||||
- (instancetype)init {
|
||||
self = [super init];
|
||||
if (self == nil) return nil;
|
||||
|
||||
self.otherURL = [NSURL URLWithString:@"http://github.com/Mantle/Mantle"];
|
||||
return self;
|
||||
}
|
||||
|
||||
+ (NSValueTransformer *)JSONTransformerForKey:(NSString *)key {
|
||||
return @{
|
||||
// Not provided transformer for self.URL
|
||||
@"otherURL": [NSValueTransformer valueTransformerForName:MTLURLValueTransformerName],
|
||||
}[key];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation MTLUUIDModel
|
||||
|
||||
- (instancetype)init {
|
||||
self = [super init];
|
||||
if (self == nil) return nil;
|
||||
|
||||
self.UUID = [[NSUUID alloc] initWithUUIDString:@"4A275FBD-8217-4397-964B-403F4C2B8545"];
|
||||
return self;
|
||||
}
|
||||
|
||||
+ (NSDictionary *)JSONKeyPathsByPropertyKey {
|
||||
return [NSDictionary mtl_identityPropertyMapWithModel:self];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation MTLUUIDSubclassModel
|
||||
|
||||
- (instancetype)init {
|
||||
self = [super init];
|
||||
if (self == nil) return nil;
|
||||
|
||||
self.otherUUID = [[NSUUID alloc] initWithUUIDString:@"593246D2-A290-43D5-9070-A299A489AE29"];
|
||||
return self;
|
||||
}
|
||||
|
||||
+ (NSValueTransformer *)JSONTransformerForKey:(NSString *)key {
|
||||
return @{
|
||||
// Not provided transformer for self.UUID
|
||||
@"otherUUID": [NSValueTransformer valueTransformerForName:MTLUUIDValueTransformerName],
|
||||
}[key];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation MTLBoolModel
|
||||
|
||||
+ (NSDictionary *)JSONKeyPathsByPropertyKey {
|
||||
@ -277,14 +217,6 @@ static NSUInteger modelVersion = 1;
|
||||
|
||||
@end
|
||||
|
||||
@implementation MTLStringModel
|
||||
|
||||
+ (NSDictionary *)JSONKeyPathsByPropertyKey {
|
||||
return [NSDictionary mtl_identityPropertyMapWithModel:self];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation MTLIDModel
|
||||
|
||||
+ (NSDictionary *)JSONKeyPathsByPropertyKey {
|
||||
@ -344,10 +276,6 @@ static NSUInteger modelVersion = 1;
|
||||
return self;
|
||||
}
|
||||
|
||||
- (BOOL)validate:(NSError **)error {
|
||||
return YES;
|
||||
}
|
||||
|
||||
#pragma mark MTLModel
|
||||
|
||||
- (NSDictionary *)dictionaryValue {
|
||||
@ -409,12 +337,6 @@ static NSUInteger modelVersion = 1;
|
||||
|
||||
@end
|
||||
|
||||
@implementation MTLStorageBehaviorModelSubclass
|
||||
|
||||
@dynamic shadowedInSubclass;
|
||||
|
||||
@end
|
||||
|
||||
@implementation MTLMultiKeypathModel
|
||||
|
||||
#pragma mark MTLJSONSerializing
|
||||
@ -522,53 +444,3 @@ static NSUInteger modelVersion = 1;
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation MTLOptionalPropertyModel
|
||||
|
||||
@end
|
||||
|
||||
@implementation MTLRecursiveUserModel
|
||||
|
||||
+ (NSDictionary *)JSONKeyPathsByPropertyKey {
|
||||
return @{
|
||||
@"name": @"name",
|
||||
@"groups": @"groups",
|
||||
};
|
||||
}
|
||||
|
||||
+ (NSValueTransformer *)groupsJSONTransformer {
|
||||
return [MTLJSONAdapter arrayTransformerWithModelClass:MTLRecursiveGroupModel.class];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation MTLRecursiveGroupModel
|
||||
|
||||
+ (NSDictionary *)JSONKeyPathsByPropertyKey {
|
||||
return @{
|
||||
@"owner": @"owner",
|
||||
@"users": @"users",
|
||||
};
|
||||
}
|
||||
|
||||
+ (NSValueTransformer *)ownerJSONTransformer {
|
||||
return [MTLJSONAdapter dictionaryTransformerWithModelClass:MTLRecursiveUserModel.class];
|
||||
}
|
||||
|
||||
+ (NSValueTransformer *)usersJSONTransformer {
|
||||
return [MTLJSONAdapter arrayTransformerWithModelClass:MTLRecursiveUserModel.class];
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation MTLPropertyDefaultAdapterModel
|
||||
|
||||
+ (NSDictionary *)JSONKeyPathsByPropertyKey {
|
||||
return @{
|
||||
@"conformingMTLJSONSerializingProperty": @"conformingMTLJSONSerializingProperty",
|
||||
@"nonConformingMTLJSONSerializingProperty": @"nonConformingMTLJSONSerializingProperty",
|
||||
@"property": @"property"
|
||||
};
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@ -6,8 +6,6 @@
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
extern NSString * const MTLTransformerErrorExamples;
|
||||
|
||||
extern NSString * const MTLTransformerErrorExamplesTransformer;
|
||||
|
||||
@ -6,8 +6,6 @@
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Quick/Quick.h>
|
||||
#import <Nimble/Nimble.h>
|
||||
#import "MTLTransformerErrorExamples.h"
|
||||
|
||||
#import "MTLTransformerErrorHandling.h"
|
||||
@ -18,48 +16,48 @@ NSString * const MTLTransformerErrorExamplesTransformer = @"MTLTransformerErrorE
|
||||
NSString * const MTLTransformerErrorExamplesInvalidTransformationInput = @"MTLTransformerErrorExamplesInvalidTransformationInput";
|
||||
NSString * const MTLTransformerErrorExamplesInvalidReverseTransformationInput = @"MTLTransformerErrorExamplesInvalidReverseTransformationInput";
|
||||
|
||||
QuickConfigurationBegin(MTLTransformerErrorExamplesConfiguration)
|
||||
SharedExampleGroupsBegin(MTLTransformerErrorExamples);
|
||||
|
||||
+ (void)configure:(Configuration *)configuration {
|
||||
sharedExamples(MTLTransformerErrorExamples, ^(QCKDSLSharedExampleContext data) {
|
||||
__block NSValueTransformer<MTLTransformerErrorHandling> *transformer;
|
||||
__block id invalidTransformationInput;
|
||||
__block id invalidReverseTransformationInput;
|
||||
sharedExamplesFor(MTLTransformerErrorExamples, ^(NSDictionary *data) {
|
||||
__block NSValueTransformer<MTLTransformerErrorHandling> *transformer;
|
||||
__block id invalidTransformationInput;
|
||||
__block id invalidReverseTransformationInput;
|
||||
|
||||
beforeEach(^{
|
||||
transformer = data()[MTLTransformerErrorExamplesTransformer];
|
||||
invalidTransformationInput = data()[MTLTransformerErrorExamplesInvalidTransformationInput];
|
||||
invalidReverseTransformationInput = data()[MTLTransformerErrorExamplesInvalidReverseTransformationInput];
|
||||
|
||||
expect(@([transformer conformsToProtocol:@protocol(MTLTransformerErrorHandling)])).to(beTruthy());
|
||||
});
|
||||
beforeEach(^{
|
||||
transformer = data[MTLTransformerErrorExamplesTransformer];
|
||||
invalidTransformationInput = data[MTLTransformerErrorExamplesInvalidTransformationInput];
|
||||
invalidReverseTransformationInput = data[MTLTransformerErrorExamplesInvalidReverseTransformationInput];
|
||||
|
||||
it(@"should return errors occurring during transformation", ^{
|
||||
__block NSError *error;
|
||||
__block BOOL success = NO;
|
||||
|
||||
expect([transformer transformedValue:invalidTransformationInput success:&success error:&error]).to(beNil());
|
||||
expect(@(success)).to(beFalsy());
|
||||
expect(error).notTo(beNil());
|
||||
expect(error.domain).to(equal(MTLTransformerErrorHandlingErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(MTLTransformerErrorHandlingErrorInvalidInput)));
|
||||
expect(error.userInfo[MTLTransformerErrorHandlingInputValueErrorKey]).to(equal(invalidTransformationInput));
|
||||
});
|
||||
|
||||
it(@"should return errors occurring during reverse transformation", ^{
|
||||
if (![transformer.class allowsReverseTransformation]) return;
|
||||
|
||||
__block NSError *error;
|
||||
__block BOOL success = NO;
|
||||
|
||||
expect([transformer reverseTransformedValue:invalidReverseTransformationInput success:&success error:&error]).to(beNil());
|
||||
expect(@(success)).to(beFalsy());
|
||||
expect(error).notTo(beNil());
|
||||
expect(error.domain).to(equal(MTLTransformerErrorHandlingErrorDomain));
|
||||
expect(@(error.code)).to(equal(@(MTLTransformerErrorHandlingErrorInvalidInput)));
|
||||
expect(error.userInfo[MTLTransformerErrorHandlingInputValueErrorKey]).to(equal(invalidReverseTransformationInput));
|
||||
});
|
||||
expect([transformer conformsToProtocol:@protocol(MTLTransformerErrorHandling)]).to.beTruthy();
|
||||
});
|
||||
}
|
||||
|
||||
QuickConfigurationEnd
|
||||
it(@"should return errors occurring during transformation", ^{
|
||||
__block NSError *error;
|
||||
__block BOOL success;
|
||||
|
||||
expect([transformer transformedValue:invalidTransformationInput success:&success error:&error]).to.beNil();
|
||||
expect(success).to.beFalsy();
|
||||
expect(error).notTo.beNil();
|
||||
expect(error.domain).to.equal(MTLTransformerErrorHandlingErrorDomain);
|
||||
expect(error.domain).to.equal(MTLTransformerErrorHandlingErrorDomain);
|
||||
expect(error.code).to.equal(MTLTransformerErrorHandlingErrorInvalidInput);
|
||||
expect(error.userInfo[MTLTransformerErrorHandlingInputValueErrorKey]).to.equal(invalidTransformationInput);
|
||||
});
|
||||
|
||||
it(@"should return errors occurring during reverse transformation", ^{
|
||||
if (![transformer.class allowsReverseTransformation]) return;
|
||||
|
||||
__block NSError *error;
|
||||
__block BOOL success;
|
||||
|
||||
expect([transformer reverseTransformedValue:invalidReverseTransformationInput success:&success error:&error]).to.beNil();
|
||||
expect(success).to.beFalsy();
|
||||
expect(error).notTo.beNil();
|
||||
expect(error.domain).to.equal(MTLTransformerErrorHandlingErrorDomain);
|
||||
expect(error.code).to.equal(MTLTransformerErrorHandlingErrorInvalidInput);
|
||||
expect(error.userInfo[MTLTransformerErrorHandlingInputValueErrorKey]).to.equal(invalidReverseTransformationInput);
|
||||
});
|
||||
});
|
||||
|
||||
SharedExampleGroupsEnd
|
||||
|
||||
@ -6,10 +6,6 @@
|
||||
// Copyright (c) 2013 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Mantle/Mantle.h>
|
||||
#import <Nimble/Nimble.h>
|
||||
#import <Quick/Quick.h>
|
||||
|
||||
@interface TestTransformer : NSValueTransformer
|
||||
@end
|
||||
|
||||
@ -33,29 +29,29 @@
|
||||
|
||||
@end
|
||||
|
||||
QuickSpecBegin(MTLValueTransformerInversionAdditions)
|
||||
SpecBegin(MTLValueTransformerInversionAdditions)
|
||||
|
||||
__block TestTransformer *transformer;
|
||||
|
||||
beforeEach(^{
|
||||
transformer = [[TestTransformer alloc] init];
|
||||
expect(transformer).notTo(beNil());
|
||||
expect(transformer).notTo.beNil();
|
||||
});
|
||||
|
||||
it(@"should invert a transformer", ^{
|
||||
NSValueTransformer *inverted = transformer.mtl_invertedTransformer;
|
||||
expect(inverted).notTo(beNil());
|
||||
expect(inverted).notTo.beNil();
|
||||
|
||||
expect([inverted transformedValue:nil]).to(equal(@"reverse"));
|
||||
expect([inverted reverseTransformedValue:nil]).to(equal(@"forward"));
|
||||
expect([inverted transformedValue:nil]).to.equal(@"reverse");
|
||||
expect([inverted reverseTransformedValue:nil]).to.equal(@"forward");
|
||||
});
|
||||
|
||||
it(@"should invert an inverted transformer", ^{
|
||||
NSValueTransformer *inverted = transformer.mtl_invertedTransformer.mtl_invertedTransformer;
|
||||
expect(inverted).notTo(beNil());
|
||||
expect(inverted).notTo.beNil();
|
||||
|
||||
expect([inverted transformedValue:nil]).to(equal(@"forward"));
|
||||
expect([inverted reverseTransformedValue:nil]).to(equal(@"reverse"));
|
||||
expect([inverted transformedValue:nil]).to.equal(@"forward");
|
||||
expect([inverted reverseTransformedValue:nil]).to.equal(@"reverse");
|
||||
});
|
||||
|
||||
QuickSpecEnd
|
||||
SpecEnd
|
||||
|
||||
@ -6,22 +6,18 @@
|
||||
// Copyright (c) 2012 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
#import <Mantle/Mantle.h>
|
||||
#import <Nimble/Nimble.h>
|
||||
#import <Quick/Quick.h>
|
||||
|
||||
QuickSpecBegin(MTLValueTransformerSpec)
|
||||
SpecBegin(MTLValueTransformer)
|
||||
|
||||
it(@"should return a forward transformer with a block", ^{
|
||||
MTLValueTransformer *transformer = [MTLValueTransformer transformerUsingForwardBlock:^(NSString *str, BOOL *success, NSError **error) {
|
||||
return [str stringByAppendingString:@"bar"];
|
||||
}];
|
||||
|
||||
expect(transformer).notTo(beNil());
|
||||
expect(@([transformer.class allowsReverseTransformation])).to(beFalsy());
|
||||
expect(transformer).notTo.beNil();
|
||||
expect([transformer.class allowsReverseTransformation]).to.beFalsy();
|
||||
|
||||
expect([transformer transformedValue:@"foo"]).to(equal(@"foobar"));
|
||||
expect([transformer transformedValue:@"bar"]).to(equal(@"barbar"));
|
||||
expect([transformer transformedValue:@"foo"]).to.equal(@"foobar");
|
||||
expect([transformer transformedValue:@"bar"]).to.equal(@"barbar");
|
||||
});
|
||||
|
||||
it(@"should return a reversible transformer with a block", ^{
|
||||
@ -29,11 +25,11 @@ it(@"should return a reversible transformer with a block", ^{
|
||||
return [str stringByAppendingString:@"bar"];
|
||||
}];
|
||||
|
||||
expect(transformer).notTo(beNil());
|
||||
expect(@([transformer.class allowsReverseTransformation])).to(beTruthy());
|
||||
expect(transformer).notTo.beNil();
|
||||
expect([transformer.class allowsReverseTransformation]).to.beTruthy();
|
||||
|
||||
expect([transformer transformedValue:@"foo"]).to(equal(@"foobar"));
|
||||
expect([transformer reverseTransformedValue:@"foo"]).to(equal(@"foobar"));
|
||||
expect([transformer transformedValue:@"foo"]).to.equal(@"foobar");
|
||||
expect([transformer reverseTransformedValue:@"foo"]).to.equal(@"foobar");
|
||||
});
|
||||
|
||||
it(@"should return a reversible transformer with forward and reverse blocks", ^{
|
||||
@ -45,11 +41,11 @@ it(@"should return a reversible transformer with forward and reverse blocks", ^{
|
||||
return [str substringToIndex:str.length - 3];
|
||||
}];
|
||||
|
||||
expect(transformer).notTo(beNil());
|
||||
expect(@([transformer.class allowsReverseTransformation])).to(beTruthy());
|
||||
expect(transformer).notTo.beNil();
|
||||
expect([transformer.class allowsReverseTransformation]).to.beTruthy();
|
||||
|
||||
expect([transformer transformedValue:@"foo"]).to(equal(@"foobar"));
|
||||
expect([transformer reverseTransformedValue:@"foobar"]).to(equal(@"foo"));
|
||||
expect([transformer transformedValue:@"foo"]).to.equal(@"foobar");
|
||||
expect([transformer reverseTransformedValue:@"foobar"]).to.equal(@"foo");
|
||||
});
|
||||
|
||||
QuickSpecEnd
|
||||
SpecEnd
|
||||
|
||||
@ -5,13 +5,11 @@
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>en</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>$(EXECUTABLE_NAME)</string>
|
||||
<string>${EXECUTABLE_NAME}</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<string>com.github.${PRODUCT_NAME:rfc1034identifier}</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>$(PRODUCT_NAME)</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>BNDL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
13
MantleTests/MantleTests-Prefix.pch
Normal file
13
MantleTests/MantleTests-Prefix.pch
Normal file
@ -0,0 +1,13 @@
|
||||
//
|
||||
// Prefix header for all source files of the 'MantleTests' target in the 'Mantle' project
|
||||
//
|
||||
|
||||
#ifdef __OBJC__
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <Mantle/Mantle.h>
|
||||
|
||||
#import "Specta.h"
|
||||
|
||||
#define EXP_SHORTHAND
|
||||
#import "Expecta.h"
|
||||
#endif
|
||||
@ -1,19 +0,0 @@
|
||||
//
|
||||
// SwiftSpec.swift
|
||||
// Archimedes
|
||||
//
|
||||
// Created by Justin Spahr-Summers on 2014-10-02.
|
||||
// Copyright (c) 2014 GitHub. All rights reserved.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
import Nimble
|
||||
import Quick
|
||||
|
||||
// Without this, the Swift stdlib won't be linked into the test target (even if
|
||||
// “Embedded Content Contains Swift Code” is enabled).
|
||||
class SwiftSpec: QuickSpec {
|
||||
override func spec() {
|
||||
expect(true).to(beTruthy())
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,26 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<model userDefinedModelVersionIdentifier="" type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" lastSavedToolsVersion="3396" systemVersion="12E55" minimumToolsVersion="Xcode 4.3" macOSVersion="Automatic" iOSVersion="Automatic">
|
||||
<entity name="BadChild" representedClassName="MTLChild" syncable="YES">
|
||||
<attribute name="childID_BROKEN" attributeType="Integer 16" defaultValueString="0" indexed="YES" syncable="YES"/>
|
||||
</entity>
|
||||
<entity name="Child" representedClassName="MTLChild" syncable="YES">
|
||||
<attribute name="childID" attributeType="Integer 16" defaultValueString="0" indexed="YES" syncable="YES"/>
|
||||
<relationship name="parent1" optional="YES" minCount="1" maxCount="1" deletionRule="Nullify" destinationEntity="Parent" inverseName="unorderedChildren" inverseEntity="Parent" syncable="YES"/>
|
||||
<relationship name="parent2" optional="YES" minCount="1" maxCount="1" deletionRule="Nullify" destinationEntity="Parent" inverseName="orderedChildren" inverseEntity="Parent" syncable="YES"/>
|
||||
</entity>
|
||||
<entity name="Empty" syncable="YES"/>
|
||||
<entity name="Parent" representedClassName="MTLParent" syncable="YES">
|
||||
<attribute name="date" optional="YES" attributeType="Date" syncable="YES"/>
|
||||
<attribute name="number" optional="YES" attributeType="Integer 64" defaultValueString="0" syncable="YES"/>
|
||||
<attribute name="string" attributeType="String" syncable="YES"/>
|
||||
<attribute name="url" optional="YES" attributeType="String" syncable="YES"/>
|
||||
<relationship name="orderedChildren" optional="YES" toMany="YES" deletionRule="Nullify" ordered="YES" destinationEntity="Child" inverseName="parent2" inverseEntity="Child" syncable="YES"/>
|
||||
<relationship name="unorderedChildren" optional="YES" toMany="YES" deletionRule="Nullify" destinationEntity="Child" inverseName="parent1" inverseEntity="Child" syncable="YES"/>
|
||||
</entity>
|
||||
<elements>
|
||||
<element name="Child" positionX="0" positionY="0" width="0" height="0"/>
|
||||
<element name="Empty" positionX="0" positionY="0" width="0" height="0"/>
|
||||
<element name="Parent" positionX="0" positionY="0" width="0" height="0"/>
|
||||
<element name="BadChild" positionX="0" positionY="0" width="0" height="0"/>
|
||||
</elements>
|
||||
</model>
|
||||
1
MantleTests/expecta
Submodule
1
MantleTests/expecta
Submodule
@ -0,0 +1 @@
|
||||
Subproject commit fab25820c20cbdac5303d7f43369559cdf439678
|
||||
1
MantleTests/specta
Submodule
1
MantleTests/specta
Submodule
@ -0,0 +1 @@
|
||||
Subproject commit 3019a1c9f61e034d4f43dae2adbf78426d879a83
|
||||
96
README.md
96
README.md
@ -1,4 +1,4 @@
|
||||
# Mantle [](https://github.com/Carthage/Carthage)
|
||||
# Mantle
|
||||
|
||||
Mantle makes it easy to write a simple model layer for your Cocoa or Cocoa Touch
|
||||
application.
|
||||
@ -27,7 +27,6 @@ typedef enum : NSUInteger {
|
||||
@property (nonatomic, copy, readonly) NSString *reporterLogin;
|
||||
@property (nonatomic, copy, readonly) NSDate *updatedAt;
|
||||
@property (nonatomic, strong, readonly) GHUser *assignee;
|
||||
@property (nonatomic, copy, readonly) NSDate *retrievedAt;
|
||||
|
||||
@property (nonatomic, copy) NSString *title;
|
||||
@property (nonatomic, copy) NSString *body;
|
||||
@ -62,7 +61,6 @@ typedef enum : NSUInteger {
|
||||
}
|
||||
|
||||
_title = [dictionary[@"title"] copy];
|
||||
_retrievedAt = [NSDate date];
|
||||
_body = [dictionary[@"body"] copy];
|
||||
_reporterLogin = [dictionary[@"user"][@"login"] copy];
|
||||
_assignee = [[GHUser alloc] initWithDictionary:dictionary[@"assignee"]];
|
||||
@ -81,7 +79,6 @@ typedef enum : NSUInteger {
|
||||
_number = [coder decodeObjectForKey:@"number"];
|
||||
_state = [coder decodeUnsignedIntegerForKey:@"state"];
|
||||
_title = [coder decodeObjectForKey:@"title"];
|
||||
_retrievedAt = [NSDate date];
|
||||
_body = [coder decodeObjectForKey:@"body"];
|
||||
_reporterLogin = [coder decodeObjectForKey:@"reporterLogin"];
|
||||
_assignee = [coder decodeObjectForKey:@"assignee"];
|
||||
@ -114,10 +111,7 @@ typedef enum : NSUInteger {
|
||||
issue->_updatedAt = self.updatedAt;
|
||||
|
||||
issue.title = self.title;
|
||||
issue->_retrievedAt = [NSDate date];
|
||||
issue.body = self.body;
|
||||
|
||||
return issue;
|
||||
}
|
||||
|
||||
- (NSUInteger)hash {
|
||||
@ -136,6 +130,8 @@ typedef enum : NSUInteger {
|
||||
Whew, that's a lot of boilerplate for something so simple! And, even then, there
|
||||
are some problems that this example doesn't address:
|
||||
|
||||
* If the `url` or `html_url` field is missing, `+[NSURL URLWithString:]` will
|
||||
throw an exception.
|
||||
* There's no way to update a `GHIssue` with new data from the server.
|
||||
* There's no way to turn a `GHIssue` _back_ into JSON.
|
||||
* `GHIssueState` shouldn't be encoded as-is. If the enum changes in the future,
|
||||
@ -190,8 +186,6 @@ typedef enum : NSUInteger {
|
||||
@property (nonatomic, copy) NSString *title;
|
||||
@property (nonatomic, copy) NSString *body;
|
||||
|
||||
@property (nonatomic, copy, readonly) NSDate *retrievedAt;
|
||||
|
||||
@end
|
||||
```
|
||||
|
||||
@ -233,27 +227,17 @@ typedef enum : NSUInteger {
|
||||
}
|
||||
|
||||
+ (NSValueTransformer *)assigneeJSONTransformer {
|
||||
return [MTLJSONAdapter dictionaryTransformerWithModelClass:GHUser.class];
|
||||
return [NSValueTransformer mtl_JSONDictionaryTransformerWithModelClass:GHUser.class];
|
||||
}
|
||||
|
||||
+ (NSValueTransformer *)updatedAtJSONTransformer {
|
||||
return [MTLValueTransformer transformerUsingForwardBlock:^id(NSString *dateString, BOOL *success, NSError *__autoreleasing *error) {
|
||||
return [self.dateFormatter dateFromString:dateString];
|
||||
} reverseBlock:^id(NSDate *date, BOOL *success, NSError *__autoreleasing *error) {
|
||||
return [MTLValueTransformer reversibleTransformerWithForwardBlock:^(NSString *str) {
|
||||
return [self.dateFormatter dateFromString:str];
|
||||
} reverseBlock:^(NSDate *date) {
|
||||
return [self.dateFormatter stringFromDate:date];
|
||||
}];
|
||||
}
|
||||
|
||||
- (instancetype)initWithDictionary:(NSDictionary *)dictionaryValue error:(NSError **)error {
|
||||
self = [super initWithDictionary:dictionaryValue error:error];
|
||||
if (self == nil) return nil;
|
||||
|
||||
// Store a value that needs to be determined locally upon initialization.
|
||||
_retrievedAt = [NSDate date];
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
@end
|
||||
```
|
||||
|
||||
@ -264,6 +248,11 @@ implementations for all these methods.
|
||||
|
||||
The problems with the original example all happen to be fixed as well:
|
||||
|
||||
> If the `url` or `html_url` field is missing, `+[NSURL URLWithString:]` will throw an exception.
|
||||
|
||||
The URL transformer we used (included in Mantle) returns `nil` if given a `nil`
|
||||
string.
|
||||
|
||||
> There's no way to update a `GHIssue` with new data from the server.
|
||||
|
||||
`MTLModel` has an extensible `-mergeValuesForKeysFromModel:` method, which makes
|
||||
@ -272,9 +261,9 @@ it easy to specify how new model data should be integrated.
|
||||
> There's no way to turn a `GHIssue` _back_ into JSON.
|
||||
|
||||
This is where reversible transformers really come in handy. `+[MTLJSONAdapter
|
||||
JSONDictionaryFromModel:error:]` can transform any model object conforming to
|
||||
JSONDictionaryFromModel:]` can transform any model object conforming to
|
||||
`<MTLJSONSerializing>` back into a JSON dictionary. `+[MTLJSONAdapter
|
||||
JSONArrayFromModels:error:]` is the same but turns an array of model objects into an JSON array of dictionaries.
|
||||
JSONArrayForModels:]` is the same but turns an array of model objects into an JSON array of dictionaries.
|
||||
|
||||
> If the interface of `GHIssue` changes down the road, existing archives might break.
|
||||
|
||||
@ -294,8 +283,7 @@ XYUser *user = [MTLJSONAdapter modelOfClass:XYUser.class fromJSONDictionary:JSON
|
||||
```
|
||||
|
||||
```objc
|
||||
NSError *error = nil;
|
||||
NSDictionary *JSONDictionary = [MTLJSONAdapter JSONDictionaryFromModel:user error:&error];
|
||||
NSDictionary *JSONDictionary = [MTLJSONAdapter JSONDictionaryFromModel:user];
|
||||
```
|
||||
|
||||
### `+JSONKeyPathsByPropertyKey`
|
||||
@ -311,7 +299,6 @@ properties map to the keys in the JSON representation, for example:
|
||||
@property (readonly, nonatomic, strong) NSDate *createdAt;
|
||||
|
||||
@property (readonly, nonatomic, assign, getter = isMeUser) BOOL meUser;
|
||||
@property (readonly, nonatomic, strong) XYHelper *helper;
|
||||
|
||||
@end
|
||||
|
||||
@ -324,25 +311,15 @@ properties map to the keys in the JSON representation, for example:
|
||||
};
|
||||
}
|
||||
|
||||
- (instancetype)initWithDictionary:(NSDictionary *)dictionaryValue error:(NSError **)error {
|
||||
self = [super initWithDictionary:dictionaryValue error:error];
|
||||
if (self == nil) return nil;
|
||||
|
||||
_helper = [XYHelper helperWithName:self.name createdAt:self.createdAt];
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
@end
|
||||
```
|
||||
|
||||
In this example, the `XYUser` class declares four properties that Mantle
|
||||
In this example, the `XYUser` class declares three properties that Mantle
|
||||
handles in different ways:
|
||||
|
||||
- `name` is mapped to a key of the same name in the JSON representation.
|
||||
- `createdAt` is converted to its snake case equivalent.
|
||||
- `meUser` is not serialized into JSON.
|
||||
- `helper` is initialized exactly once after JSON deserialization.
|
||||
|
||||
Use `-[NSDictionary mtl_dictionaryByAddingEntriesFromDictionary:]` if your
|
||||
model's superclass also implements `MTLJSONSerializing` to merge their mappings.
|
||||
@ -382,17 +359,16 @@ deserializing from JSON.
|
||||
}
|
||||
```
|
||||
|
||||
`key` is the key that applies to your model object; not the original JSON key. Keep this in mind if you transform the key names using `+JSONKeyPathsByPropertyKey`.
|
||||
|
||||
For added convenience, if you implement `+<key>JSONTransformer`,
|
||||
`MTLJSONAdapter` will use the result of that method instead. For example, dates
|
||||
that are commonly represented as strings in JSON can be transformed to `NSDate`s
|
||||
like so:
|
||||
|
||||
```objc
|
||||
return [MTLValueTransformer transformerUsingForwardBlock:^id(NSString *dateString, BOOL *success, NSError *__autoreleasing *error) {
|
||||
return [self.dateFormatter dateFromString:dateString];
|
||||
} reverseBlock:^id(NSDate *date, BOOL *success, NSError *__autoreleasing *error) {
|
||||
+ (NSValueTransformer *)createdAtJSONTransformer {
|
||||
return [MTLValueTransformer reversibleTransformerWithForwardBlock:^(NSString *str) {
|
||||
return [self.dateFormatter dateFromString:str];
|
||||
} reverseBlock:^(NSDate *date) {
|
||||
return [self.dateFormatter stringFromDate:date];
|
||||
}];
|
||||
}
|
||||
@ -472,24 +448,32 @@ in memory at once, Core Data may be a better choice.
|
||||
|
||||
## System Requirements
|
||||
|
||||
Mantle supports OS X 10.9+ and iOS 8.0+.
|
||||
Mantle supports OS X 10.7+ and iOS 5.0+.
|
||||
|
||||
## Importing Mantle
|
||||
|
||||
To add Mantle to your application:
|
||||
|
||||
1. Add the Mantle repository as a submodule of your application's repository.
|
||||
1. Run `git submodule update --init --recursive` from within the Mantle folder.
|
||||
1. Drag and drop `Mantle.xcodeproj` into your application's Xcode project.
|
||||
1. On the "General" tab of your application target, add `Mantle.framework` to the "Embedded Binaries".
|
||||
|
||||
[Carthage](https://github.com/Carthage/Carthage) users can simply add Mantle to their `Cartfile`:
|
||||
```
|
||||
github "Mantle/Mantle"
|
||||
```
|
||||
1. Run `script/bootstrap` from within the Mantle folder.
|
||||
1. Drag and drop `Mantle.xcodeproj` into your application's Xcode project or
|
||||
workspace.
|
||||
1. On the "Build Phases" tab of your application target, add Mantle to the
|
||||
"Link Binary With Libraries" phase.
|
||||
* **On iOS**, add `libMantle.a`.
|
||||
* **On OS X**, add `Mantle.framework`. Mantle must also be added to any
|
||||
"Copy Frameworks" build phase. If you don't already have one, simply add a
|
||||
"Copy Files" build phase and target the "Frameworks" destination.
|
||||
1. Add `"$(BUILD_ROOT)/../IntermediateBuildFilesPath/UninstalledProducts/include" $(inherited)`
|
||||
to the "Header Search Paths" build setting (this is only
|
||||
necessary for archive builds, but it has no negative effect otherwise).
|
||||
1. **For iOS targets**, add `-ObjC` to the "Other Linker Flags" build setting.
|
||||
1. **If you added Mantle to a project (not a workspace)**, you will also need
|
||||
to add the appropriate Mantle target to the "Target Dependencies" of your
|
||||
application.
|
||||
|
||||
If you would prefer to use [CocoaPods](http://cocoapods.org), there are some
|
||||
[Mantle podspecs](https://github.com/CocoaPods/Specs/tree/master/Specs/5/d/c/Mantle) that
|
||||
[Mantle podspecs](https://github.com/CocoaPods/Specs/tree/master/Mantle) that
|
||||
have been generously contributed by third parties.
|
||||
|
||||
If you’re instead developing Mantle on its own, use the `Mantle.xcworkspace` file.
|
||||
@ -498,7 +482,3 @@ If you’re instead developing Mantle on its own, use the `Mantle.xcworkspace` f
|
||||
|
||||
Mantle is released under the MIT license. See
|
||||
[LICENSE.md](https://github.com/github/Mantle/blob/master/LICENSE.md).
|
||||
|
||||
## More Info
|
||||
|
||||
Have a question? Please [open an issue](https://github.com/Mantle/Mantle/issues/new)!
|
||||
|
||||
18
script/LICENSE.md
Normal file
18
script/LICENSE.md
Normal file
@ -0,0 +1,18 @@
|
||||
**Copyright (c) 2013 Justin Spahr-Summers**
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
this software and associated documentation files (the "Software"), to deal in
|
||||
the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
82
script/README.md
Normal file
82
script/README.md
Normal file
@ -0,0 +1,82 @@
|
||||
# objc-build-scripts
|
||||
|
||||
This project is a collection of scripts created with two goals:
|
||||
|
||||
1. To standardize how Objective-C projects are bootstrapped after cloning
|
||||
1. To easily build Objective-C projects on continuous integration servers
|
||||
|
||||
## Scripts
|
||||
|
||||
Right now, there are two important scripts: [`bootstrap`](#bootstrap) and
|
||||
[`cibuild`](#cibuild). Both are Bash scripts, to maximize compatibility and
|
||||
eliminate pesky system configuration issues (like setting up a working Ruby
|
||||
environment).
|
||||
|
||||
The structure of the scripts on disk is meant to follow that of a typical Ruby
|
||||
project:
|
||||
|
||||
```
|
||||
script/
|
||||
bootstrap
|
||||
cibuild
|
||||
```
|
||||
|
||||
### bootstrap
|
||||
|
||||
This script is responsible for bootstrapping (initializing) your project after
|
||||
it's been checked out. Here, you should install or clone any dependencies that
|
||||
are required for a working build and development environment.
|
||||
|
||||
By default, the script will verify that [xctool][] is installed, then initialize
|
||||
and update submodules recursively. If any submodules contain `script/bootstrap`,
|
||||
that will be run as well.
|
||||
|
||||
To check that other tools are installed, you can set the `REQUIRED_TOOLS`
|
||||
environment variable before running `script/bootstrap`, or edit it within the
|
||||
script directly. Note that no installation is performed automatically, though
|
||||
this can always be added within your specific project.
|
||||
|
||||
### cibuild
|
||||
|
||||
This script is responsible for building the project, as you would want it built
|
||||
for continuous integration. This is preferable to putting the logic on the CI
|
||||
server itself, since it ensures that any changes are versioned along with the
|
||||
source.
|
||||
|
||||
By default, the script will run [`bootstrap`](#bootstrap), look for any Xcode
|
||||
workspace or project in the working directory, then build all targets/schemes
|
||||
(as found by `xcodebuild -list`) using [xctool][].
|
||||
|
||||
You can also specify the schemes to build by passing them into the script:
|
||||
|
||||
```sh
|
||||
script/cibuild ReactiveCocoa-Mac ReactiveCocoa-iOS
|
||||
```
|
||||
|
||||
As with the `bootstrap` script, there are several environment variables that can
|
||||
be used to customize behavior. They can be set on the command line before
|
||||
invoking the script, or the defaults changed within the script directly.
|
||||
|
||||
## Getting Started
|
||||
|
||||
To add the scripts to your project, read the contents of this repository into
|
||||
a `script` folder:
|
||||
|
||||
```
|
||||
$ git remote add objc-build-scripts https://github.com/jspahrsummers/objc-build-scripts.git
|
||||
$ git fetch objc-build-scripts
|
||||
$ git read-tree --prefix=script/ -u objc-build-scripts/master
|
||||
```
|
||||
|
||||
Then commit the changes, to incorporate the scripts into your own repository's
|
||||
history. You can also freely tweak the scripts for your specific project's
|
||||
needs.
|
||||
|
||||
To merge in upstream changes later:
|
||||
|
||||
```
|
||||
$ git fetch -p objc-build-scripts
|
||||
$ git merge --ff --squash -Xsubtree=script objc-build-scripts/master
|
||||
```
|
||||
|
||||
[xctool]: https://github.com/facebook/xctool
|
||||
73
script/bootstrap
Executable file
73
script/bootstrap
Executable file
@ -0,0 +1,73 @@
|
||||
#!/bin/bash
|
||||
|
||||
export SCRIPT_DIR=$(dirname "$0")
|
||||
|
||||
##
|
||||
## Configuration Variables
|
||||
##
|
||||
|
||||
config ()
|
||||
{
|
||||
# A whitespace-separated list of executables that must be present and locatable.
|
||||
: ${REQUIRED_TOOLS="xctool"}
|
||||
|
||||
export REQUIRED_TOOLS
|
||||
}
|
||||
|
||||
##
|
||||
## Bootstrap Process
|
||||
##
|
||||
|
||||
main ()
|
||||
{
|
||||
config
|
||||
|
||||
if [ -n "$REQUIRED_TOOLS" ]
|
||||
then
|
||||
echo "*** Checking dependencies..."
|
||||
check_deps
|
||||
fi
|
||||
|
||||
local submodules=$(git submodule status 2>/dev/null)
|
||||
if [ -n "$submodules" ]
|
||||
then
|
||||
echo "*** Updating submodules..."
|
||||
update_submodules
|
||||
fi
|
||||
}
|
||||
|
||||
check_deps ()
|
||||
{
|
||||
for tool in $REQUIRED_TOOLS
|
||||
do
|
||||
which -s "$tool"
|
||||
if [ "$?" -ne "0" ]
|
||||
then
|
||||
echo "*** Error: $tool not found. Please install it and bootstrap again."
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
bootstrap_submodule ()
|
||||
{
|
||||
local bootstrap="script/bootstrap"
|
||||
|
||||
if [ -e "$bootstrap" ]
|
||||
then
|
||||
echo "*** Bootstrapping $name..."
|
||||
"$bootstrap" >/dev/null
|
||||
else
|
||||
update_submodules
|
||||
fi
|
||||
}
|
||||
|
||||
update_submodules ()
|
||||
{
|
||||
git submodule sync --quiet && git submodule update --init && git submodule foreach --quiet bootstrap_submodule
|
||||
}
|
||||
|
||||
export -f bootstrap_submodule
|
||||
export -f update_submodules
|
||||
|
||||
main
|
||||
142
script/cibuild
Executable file
142
script/cibuild
Executable file
@ -0,0 +1,142 @@
|
||||
#!/bin/bash
|
||||
|
||||
export SCRIPT_DIR=$(dirname "$0")
|
||||
|
||||
##
|
||||
## Configuration Variables
|
||||
##
|
||||
|
||||
SCHEMES="$@"
|
||||
|
||||
config ()
|
||||
{
|
||||
# The workspace to build.
|
||||
#
|
||||
# If not set and no workspace is found, the -workspace flag will not be passed
|
||||
# to `xctool`.
|
||||
#
|
||||
# Only one of `XCWORKSPACE` and `XCODEPROJ` needs to be set. The former will
|
||||
# take precedence.
|
||||
: ${XCWORKSPACE=$(find_pattern "*.xcworkspace")}
|
||||
|
||||
# The project to build.
|
||||
#
|
||||
# If not set and no project is found, the -project flag will not be passed
|
||||
# to `xctool`.
|
||||
#
|
||||
# Only one of `XCWORKSPACE` and `XCODEPROJ` needs to be set. The former will
|
||||
# take precedence.
|
||||
: ${XCODEPROJ=$(find_pattern "*.xcodeproj")}
|
||||
|
||||
# A bootstrap script to run before building.
|
||||
#
|
||||
# If this file does not exist, it is not considered an error.
|
||||
: ${BOOTSTRAP="$SCRIPT_DIR/bootstrap"}
|
||||
|
||||
# Extra options to pass to xctool.
|
||||
: ${XCTOOL_OPTIONS="RUN_CLANG_STATIC_ANALYZER=NO"}
|
||||
|
||||
# A whitespace-separated list of default schemes to build.
|
||||
#
|
||||
# Individual names can be quoted to avoid word splitting.
|
||||
: ${SCHEMES:=$(xcodebuild -list 2>/dev/null | awk -f "$SCRIPT_DIR/schemes.awk")}
|
||||
|
||||
export XCWORKSPACE
|
||||
export XCODEPROJ
|
||||
export BOOTSTRAP
|
||||
export XCTOOL_OPTIONS
|
||||
export SCHEMES
|
||||
}
|
||||
|
||||
##
|
||||
## Build Process
|
||||
##
|
||||
|
||||
main ()
|
||||
{
|
||||
config
|
||||
|
||||
if [ -f "$BOOTSTRAP" ]
|
||||
then
|
||||
echo "*** Bootstrapping..."
|
||||
"$BOOTSTRAP" || exit $?
|
||||
fi
|
||||
|
||||
echo "*** The following schemes will be built:"
|
||||
echo "$SCHEMES" | xargs -n 1 echo " "
|
||||
echo
|
||||
|
||||
echo "$SCHEMES" | xargs -n 1 | (
|
||||
local status=0
|
||||
|
||||
while read scheme
|
||||
do
|
||||
build_scheme "$scheme" || status=1
|
||||
done
|
||||
|
||||
exit $status
|
||||
)
|
||||
}
|
||||
|
||||
find_pattern ()
|
||||
{
|
||||
ls -d $1 2>/dev/null | head -n 1
|
||||
}
|
||||
|
||||
run_xctool ()
|
||||
{
|
||||
if [ -n "$XCWORKSPACE" ]
|
||||
then
|
||||
xctool -workspace "$XCWORKSPACE" $XCTOOL_OPTIONS "$@" 2>&1
|
||||
elif [ -n "$XCODEPROJ" ]
|
||||
then
|
||||
xctool -project "$XCODEPROJ" $XCTOOL_OPTIONS "$@" 2>&1
|
||||
else
|
||||
echo "*** No workspace or project file found."
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
parse_build ()
|
||||
{
|
||||
awk -f "$SCRIPT_DIR/xctool.awk" 2>&1 >/dev/null
|
||||
}
|
||||
|
||||
build_scheme ()
|
||||
{
|
||||
local scheme=$1
|
||||
|
||||
echo "*** Cleaning $scheme..."
|
||||
run_xctool -scheme "$scheme" clean >/dev/null || exit $?
|
||||
|
||||
echo "*** Building and testing $scheme..."
|
||||
echo
|
||||
|
||||
local sdkflag=
|
||||
local action=test
|
||||
|
||||
# Determine whether we can run unit tests for this target.
|
||||
run_xctool -scheme "$scheme" run-tests | parse_build
|
||||
|
||||
local awkstatus=$?
|
||||
|
||||
if [ "$awkstatus" -ne "0" ]
|
||||
then
|
||||
# Unit tests aren't supported.
|
||||
action=build
|
||||
fi
|
||||
|
||||
if [ "$awkstatus" -eq "1" ]
|
||||
then
|
||||
# Build for iOS.
|
||||
sdkflag="-sdk iphonesimulator"
|
||||
fi
|
||||
|
||||
run_xctool $sdkflag -scheme "$scheme" $action
|
||||
}
|
||||
|
||||
export -f build_scheme
|
||||
export -f run_xctool
|
||||
export -f parse_build
|
||||
|
||||
main
|
||||
12
script/schemes.awk
Normal file
12
script/schemes.awk
Normal file
@ -0,0 +1,12 @@
|
||||
BEGIN {
|
||||
FS = "\n";
|
||||
}
|
||||
|
||||
/Targets:/ {
|
||||
while (getline && $0 != "") {
|
||||
if ($0 ~ /Test/) continue;
|
||||
|
||||
sub(/^ +/, "");
|
||||
print "'" $0 "'";
|
||||
}
|
||||
}
|
||||
25
script/xctool.awk
Normal file
25
script/xctool.awk
Normal file
@ -0,0 +1,25 @@
|
||||
# Exit statuses:
|
||||
#
|
||||
# 0 - No errors found.
|
||||
# 1 - Wrong SDK. Retry with SDK `iphonesimulator`.
|
||||
# 2 - Missing target.
|
||||
|
||||
BEGIN {
|
||||
status = 0;
|
||||
}
|
||||
|
||||
{
|
||||
print;
|
||||
}
|
||||
|
||||
/Testing with the '(.+)' SDK is not yet supported/ {
|
||||
status = 1;
|
||||
}
|
||||
|
||||
/does not contain a target named/ {
|
||||
status = 2;
|
||||
}
|
||||
|
||||
END {
|
||||
exit status;
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user