• Stars
    star
    663
  • Rank 67,991 (Top 2 %)
  • Language
    Objective-C
  • License
    MIT License
  • Created over 10 years ago
  • Updated almost 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A concise Mantle-like way of working with Realm and JSON.

Realm+JSON License MIT

Badge w/ Version Badge w/ Platform

A concise Mantle-like way of working with Realm and JSON.

Breaking Change

  • Method - deepCopy replaces the previous functionality of - shallowCopy, which no longer maintains an object's primary key
  • Updated to use native primary key support in Realm 0.85.0
  • Update your code to use methods -createOrUpdateInRealm:withJSONArray: or -createOrUpdateInRealm:withJSONDictionary:
  • You must wrap these methods in a write transaction (between [realm beginWriteTransaction]; and [realm commitWriteTransaction];)
  • These methods call -createOrUpdateInRealm:withObject: behind the scenes for performance.

Installation

Add the following to your CocoaPods Podfile

pod 'Realm+JSON', '~> 0.2'

or clone as a git submodule,

or just copy files in the Realm+JSON folder into your project.

Using Realm+JSON

Simply declare your model as normal:

typedef NS_ENUM(NSInteger, MCEpisodeType) {
    MCEpisodeTypeFree = 0,
    MCEpisodeTypePaid
};

@interface MCEpisode : RLMObject

@property NSInteger episodeID;
@property NSInteger episodeNumber;
@property MCEpisodeType episodeType;

@property NSString *title;
@property NSString *subtitle;
@property NSString *thumbnailURL;

@property NSDate *publishedDate;

@end

RLM_ARRAY_TYPE(MCEpisode)

Then pass the result of NSJSONSerialization or AFNetworking as follows:

  [MCEpisode createOrUpdateInRealm:[RLMRealm defaultRealm] withJSONArray:array];

or

  [MCEpisode createOrUpdateInRealm:[RLMRealm defaultRealm] withJSONDictionary:dictionary];

Use the -JSONDictionary method to get a JSON-ready dictionary for your network requests.

Configuration

You should specify the inbound and outbound JSON mapping on your RLMObject subclass like this:

+ (NSDictionary *)JSONInboundMappingDictionary {
  return @{
         @"episode.title": @"title",
         @"episode.description": @"subtitle",
         @"episode.id": @"episodeID",
         @"episode.episode_number": @"episodeNumber",
         @"episode.episode_type": @"episodeType",
         @"episode.thumbnail_url": @"thumbnailURL",
         @"episode.published_at": @"publishedDate",
  };
}

+ (NSDictionary *)JSONOutboundMappingDictionary {
  return @{
         @"title": @"title",
         @"subtitle": @"episode.description",
         @"episodeID": @"id",
         @"episodeNumber": @"episode.number",
         @"publishedDate": @"published_at",
  };
}

JSON preprocessing can be done by implementing jsonPreprocessing: static method:

- (NSDictionary *)jsonPreprocessing:(NSDictionary *)dictionary {
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:dictionary];
    dict[@"releaseCount"] = @(0);
    return dict.copy;
}

Leaving out either one of the above will result in a mapping that assumes camelCase for your properties which map to snake_case for the JSON equivalents.

As you can do with Mantle, you can specify NSValueTransformers for your properties:

+ (NSValueTransformer *)episodeTypeJSONTransformer {
  return [MCJSONValueTransformer valueTransformerWithMappingDictionary:@{
              @"free": @(MCEpisodeTypeFree),
              @"paid": @(MCEpisodeTypePaid)
      }];
}

Working with background threads

Realm requires that you use different RLMRealm objects when working across different threads. This means you shouldn't access the same RLMObject instances from different threads. To make this easier to work with, use - primaryKeyValue to retrieve the wrapped primary key value from an instance and query for it later using + objectInRealm:withPrimaryKeyValue:.

id primaryKeyValue = [episode primaryKeyValue];
dispatch_async(dispatch_get_main_queue(), ^{
    MCEpisode *episode = [MCEpisode objectInRealm:[RLMRealm defaultRealm] withPrimaryKeyValue:primaryKeyValue];

    // do something with episode here
});

Working with (temporary) copies (RLMObject+Copying)

If you need to display UI that may or may not change an object's properties, it is sometimes useful to work with an object not bound to a realm as a backing model object. When it is time to commit changes, the properties can be copied back to the stored model.

Methods - shallowCopy and - mergePropertiesFromObject: are provided. The later of which needs to be performed in a realm transaction.

#import <Realm+Copying.h>

MCEpisode *anotherEpisode = [episode shallowCopy];
anotherEpisode.title = @"New title";

// ...

[episode performInTransaction:^{
    [episode mergePropertiesFromObject:anotherEpisode];
}];

Additionally, method - deepCopy is provided. Unlike - shallowCopy, it maintains the object's primary key.

License

Realm+JSON is under the MIT license.

More Repositories

1

POP-MCAnimate

Concise syntax for the Pop animation framework.
Objective-C
951
star
2

JSONCodable

Hassle-free JSON encoding and decoding in Swift
Swift
602
star
3

MCPanelViewController

Drop-in panel control for iOS with blurring background and screen-edge activation gestures.
Objective-C
325
star
4

Fluent

Swift animation made easy
Swift
300
star
5

MCFireworksButton

Drop-in button control with with particle effects similar to the Like button in Facebook Paper.
Objective-C
233
star
6

Kaleidoscope

Writing a lexer and parser for Kaleidoscope in Swift
Swift
61
star
7

MCBlurredModalController

A sleek way to display your view controller modally.
Objective-C
61
star
8

Brotli

An iOS and OSX wrapper for Google's Brotli project.
C
47
star
9

MCNumberLabel

Drop-in label control with the ability to animate digits.
Objective-C
42
star
10

MCGraphView

A light-weight solution for displaying graphs.
Objective-C
19
star
11

MCNotificationManager

Show your own banners like Notification Center within your app.
Objective-C
17
star
12

MCModalView

UIAlertView/UIActionSheet replacement supporting iPhone/iPad and device rotations.
Objective-C
13
star
13

MCAppRouter

URL routing for iOS made simple.
Objective-C
10
star
14

Layout

Functional layout in Swift
Swift
9
star
15

MCBinaryHeap

An Objective-C wrapper of CFBinaryHeap. Core Foundation priority queue implementation.
Objective-C
9
star
16

MCDynamicObject

Automatic persistence for your next iOS project.
C
8
star
17

MCAdditions

A host of useful utilties for any iOS application.
Objective-C
6
star
18

MCObservation

Easy-to-use, fire-and-forget KVO and notifications.
Objective-C
5
star
19

MCTimeSeriesView

A light-weight solution for displaying time series charts.
Objective-C
5
star
20

JSONSerialization

Natively implemented JSON serialization in Swift
Swift
4
star
21

react-rebels

Flux simplified
JavaScript
2
star
22

polymorphism-with-protocols

Good API design is essential for writing code that scales. In this talk, we look at some characteristics of good design and how to refactor code using the protocol features in Swift.
Swift
2
star
23

react-kit

Boilerplate for project with React and Webpack.
JavaScript
2
star
24

amigo

Swift
1
star
25

Click

Easy window recording for macOS
Swift
1
star