Giter Club home page Giter Club logo

realm-json's Introduction

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.

realm-json's People

Contributors

abackys avatar antongaenko avatar chgsantos avatar christianronningen avatar dan2552 avatar dcramps avatar ealeksandrov avatar enricenrich avatar gazsp avatar haswalt avatar inquisitivesoft avatar jallen avatar matthewcheok avatar mpaulsonco avatar nunobaldaia avatar raspu avatar typester avatar viktorasl avatar zeroelink avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

realm-json's Issues

had Error

Json Example
{
mid: 1501,
description: "This what"
}
-----------------
@interface Episode : RLMObjec
@Property NSInteger mid;
@Property NSString *desc;

@EnD

@implementation Episode

  • (NSDictionary *)JSONInboundMappingDictionary {
    return @{
    @"description": @"desc"
    };
    }

@EnD

When I used it, had error

How to convert description property;

One to many using Realm-JSON.

One to many using Realm-JSON. what will be JSONInboundMappingDictionary and JSONOutboundMappingDictionary?

@protocol Person;

@interface Dog : RLMObject
@property NSString *name;
@property NSInteger age;
@end

@implementation Dog
@end

RLM_ARRAY_TYPE(Dog)

@interface Person : RLMObject
@property NSString *name;
@property RLMArray *dogs;
@end

@implementation Person
@end

RLM_ARRAY_TYPE(Person)

Almost similar question has been ask on this issue
#4

Handling of date strings?

I have part of this JSON incoming data:

date_created = "2015-08-26T06:27:36.000Z";

How does Realm-JSON handle parsing of that string into my property of a model:

@property NSDate *dateCreated;

I already have set up

+ (NSDictionary *)JSONInboundMappingDictionary

to recognize the difference in the key names. But it doesn't parse the string into an NSDate.

An example NSValueTransformer to deal with json null values

Suggested as an addition to your existing transformers.

It'll just check if a value is NSNull and convert it to an empty string.

// ---------------------------------------------
@interface MCJSONNonNullStringTransformer : NSValueTransformer
+ (instancetype)valueTransformer;
@end

// ---------------------------------------------
@implementation MCJSONNonNullStringTransformer

+ (instancetype)valueTransformer
{
    return [[self alloc] init];
}


+ (Class)transformedValueClass 
{
    return [NSString class];
}

+ (BOOL)allowsReverseTransformation 
{
    return YES;
}

- (id)transformedValue:(id)value 
{

    if(value && ![value isKindOfClass:[NSNull class]]) {
        return value;
    } else {
        return @"";
    }
}

- (id)reverseTransformedValue:(id)value 
{
    return value;
}

@end

Outbound mapping with keypath into single key

Hi. Please, does Realm+JSON somehow supports outbound object mapping from RLMObject into JSON from keypath object.property into key property?

I have object scheme such like:

@interface MyObject

@property NSString * attr1;
@property NSString * attr2;
@property MySubobject * subobject;

@end
@interface MySubobject

@property NSString * attr3;
@property NSNumber<RLMInt> * attr4;

@end

In one specific case I need to create JSON with structure that attr1, attr2, attr3 and attr4 would be on the same level, therefore something like:

+ (NSDictionary *)JSONOutboundMappingDictionary {
    return @{
             @"attr1" : @"attr1",
             @"attr2" : @"attr2",
             @"subobject.attr3" : @"attr3",
             @"subobject.attr4" : @"attr4"
             };
}

So far it keeps crashing and I can't figure out how to achieve such effect without removing MySubobject ale moving all it's attributes into main object (or creating JSON manually from self-created NSDictionary). Is it even possible with Realm+JSON? I noticed inverse case from JSON keypath to single key in RLMObject is allowed. In advance thanks for any answer.

Custom RLMObject to JSON mapping (symmetric method to +preprocessedJSON needed)

If I want to make any complicated preprocessing on JSON before mapping JSON to RLMObject I can use +preprocessedJSON:, but there is no way for opposite postprocessing of RLMObject to JSON if I want to get the same JSON back from RLMObject.

One way I wanted to achieve that is by overriding -JSONDictionary but it is implemented this way:
- (NSDictionary *)JSONDictionary { return [self mc_createJSONDictionary]; }
and everywhere in the implementation -mc_createJSONDictionary is called. So suddenly to achieve what I want I need to override -mc_createJSONDictionary and mess with guts of implementation because -mc_createJSONDictionary is private.

  1. Why can't -JSONDictionary be called directly in the implementation?
  2. Do you have any plans to introduce a symmetric call to +preprocessedJSON:?
  3. Are there any other ways I can achieve desired behaviour?

Doesn't work with Swift

Currently this doesn't work with Swift because when the class is matched by string it doesn't take into account Swift's module prefix. It doesn't necessarily seem like a complicated fix to me - just wondering if it's on your radar?
Thanks

Memory management issues with createOrUpdateInRealm:withJSONArray

This might be a bug or just some extra documentation for a particular use case.

I have a dataset in the tens of thousands of json objects my app is batch-downloading at the first install of the app (thereafter it updates with changed content only). For network performance I like to take batches of 2500-5000, but i find that if I give that array to Realm all at once using createOrUpdateInRealm:withJSONArray it takes too much RAM (especially on older devices) and I get a memory warning.

Maybe this could be dealt with internally to Realm+JSON, but my solution externally is to iteratively feed subarrays to Realm. The key is @autoreleasepool; that frees the memory on each loop so that it doesn't climb beyond what is allocated to write kItemsPerRun of the dataset.

    int ct = props.count;
    if (ct > 0) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
                int kItemsPerRun = 1000;
                int runIndex = 0;
                NSArray *tmpArr = nil;
                while (runIndex < ct) {
                    int length = MIN( ct - runIndex, kItemsPerRun );
                    tmpArr = [props subarrayWithRange: NSMakeRange( runIndex, length )];
                    runIndex += kItemsPerRun;
                    @autoreleasepool {
                        RLMRealm * realm = [RLMRealm defaultRealm];
                        [realm beginWriteTransaction];
                        [VProperty createOrUpdateInRealm:realm withJSONArray:tmpArr];
                        [realm commitWriteTransaction];
                    }
                }
        });

Transforming ID from JSON to create object

Hello, I'm having trouble transforming an id key which is returned as a string in JSON and mapping it to an NSInteger type called ID which I use as my primary key. Any suggestions? I crash with a null exception for ID.

Trouble understanding inner code

hi I'm considering using this source on my project
but I have trouble understanding under the code

- (id)mc_createJSONDictionary {
...
            id currentDictionary = result;
            for (NSString *component in keyPathComponents) {
                if ([currentDictionary valueForKey:component] == nil) {
                    [currentDictionary setValue:[NSMutableDictionary dictionary] forKey:component];
                }
                currentDictionary = [currentDictionary valueForKey:component];
            }
...
}

what is that for?

How to map array of strings

Part of the JSON response Im trying to model is an array of strings. How do I map this with Realm-JSON?

I tried using RLMArrays with another class, but am unsure how to map the string values. Here is a sample JSON model:

....
"currency":"USD", "genres":["Games", "Entertainment", "Action", "Adventure"], "genreIds":["6014", "6016", "7001", "7002"]
....

Inheritance issue

Mantle has the +classForParsingJSONDictionary: method to handle models subclassed from a root model. What about Realm-JSON? How to address inheritance?

Realm Object JSONDictionary method not working in Swift

I have been trying to implement this on my current Swift project, but cannot get it working. Here is my model:

//
//  RealmComment.swift
//  phefeed
//
//  Created by Mark Brenneman on 11/25/15.
//  Copyright © 2015 Mark Brenneman. All rights reserved.
//

import Foundation
import RealmSwift

class RealmComment: Object {
    dynamic var text: String?
    dynamic var id: String?
    dynamic var createdAt: Double = 0.00
    dynamic var updatedAt: Double = 0.00
    dynamic var user: RealmUser?
    dynamic var post: RealmPost?

    override static func primaryKey() -> String? {
        return "id"
    }

    func JSONOutboundMappingDictionary() -> NSDictionary {
        return [
            "id": "objectId",
            "createdAt": "createdAt",
            "updatedAt": "updatedAt",
            "user":"user",
            "post":"post",
            "text":"text"
        ]
    }

    func JSONInboundMappingDictionary() -> NSDictionary {
        return [
            "id": "objectId",
            "createdAt": "createdAt",
            "updatedAt": "updatedAt",
            "user":"user",
            "post":"post",
            "text":"text"
        ]
    }    
}

I am then trying to convert an object to JSON Dictionary using this (to convert a comment from one RealmComment (Realm+JSON) to an MBComment (ObjectMapper)

    class func realmCommentToMbComment(realmComment: RealmComment) -> MBComment {
        var newMbComment = MBComment()
        let realm = try! Realm()
        try! realm.write {

            let JSONString = realmComment.JSONDictionary
            newMbComment = Mapper<MBComment>().map(JSONString)! //this is using ObjectMapper

        }
        return newMbComment

    }

However, this will not compile and gives me an error "Value of type RealmComment has no member JSONDictionary".

Give support for 0.91

It seems that in Realm 0.91 RLMObjectSchema does not have a properties property anymore.

Crash on processing nil date

Realm can handle nil objects if you provide a default value with defaultPropertyValues.

MCJSONDateTransformer crashes at [self.formatter dateFromString:value]; if value is nil.

Missing primary Key leads to trouble

It's checking if there's a primary key by calling primaryKeyValueFromJSONDictionary:, but that method has an Assert to make sure there's a primary key. So as far as I can tell, you can't run without one.

Is this correct?

+ (instancetype)mc_createOrUpdateInRealm:(RLMRealm *)realm withJSONDictionary:(NSDictionary *)dictionary {
    if (!dictionary || [dictionary isEqual:[NSNull null]]) {
        return nil;
    }

    id object = nil;
    id primaryKeyValue = [self primaryKeyValueFromJSONDictionary:dictionary];

    if (primaryKeyValue) {
        object = [self objectInRealm:realm withPrimaryKeyValue:primaryKeyValue];
    }

    if (object) {
        [object mc_setValuesFromJSONDictionary:dictionary inRealm:realm];
    }
    else {
        object = [[self alloc] init];
        [object mc_setValuesFromJSONDictionary:dictionary inRealm:realm];
        [realm addObject:object];
    }

    return object;
}

Unchecked NSNull condition for RLMArray

mc_createObjectFromJSONDictionary crashes whenever var propertyClass is a subclass of RLMArray and var value is NSNull. There should be the same check that in the RLMObject case.

if (!value || [value isEqual:[NSNull null]]) {
    continue;
}

By the way, why testing (!value) in a if (value) condition block ? It seems kinda useless.

setObjectForKey: key cannot be nil

Running the code below causes setObjectForKey: key cannot be nil in Swift. I'm not sure if I'm actually using this correctly or not, but I can't seem to get any of the category functionality working.

    var grp = GroupRLMObject()
    grp.name = "David Foster Wallace"

    // Get the default Realm
    let realm = RLMRealm.defaultRealm()
    // You only need to do this once (per thread)

    // Add to the Realm inside a transaction
    realm.beginWriteTransaction()
    realm.addObject(grp)
    realm.commitWriteTransaction()

    let results: NSDictionary = grp.JSONDictionary() as NSDictionary

Realm-JSON doesn't work on a device

The Realm+JSON0.2.3 build installed via CocoaPods project throws this error when attempting to run on a device.

ld: library not found for -lc++
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I'm not sure if this is tied to Realm or the Realm+JSON category. Just create a basic project, add pod 'Realm+JSON', '~> 0.2' to your Podfile and try to run on a device.

Custom value transformer

Is there a way I can use different date formatter? the demo app doesn't parse published_date correctly.

can we have something like Mantle:

+ (instancetype)reversibleTransformerWithForwardBlock:(MTLValueTransformerBlock)forwardBlock reverseBlock:(MTLValueTransformerBlock)reverseBlock

EXC BAD ACCESS when calling createOrUpdateInRealm:withJSONArray: second time.

+ (NSDictionary *)mc_inboundMapping {
    static NSMutableDictionary *mappingForClassName = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        mappingForClassName = [NSMutableDictionary dictionary];
    });
    @synchronized(mappingForClassName) {
        NSDictionary *mapping = mappingForClassName[[self className]];//<----EXC BAD ACCESS here
        if (!mapping) {
            SEL selector = NSSelectorFromString(@"JSONInboundMappingDictionary");
            if ([self respondsToSelector:selector]) {
                mapping = MCValueFromInvocation(self, selector);
            }
            else {
                mapping = [self mc_defaultInboundMapping];
            }
            mappingForClassName[[self className]] = mapping;
        }
        return mapping;
    }
}

When I attempt to call createOrUpdateInRealm:withJSONArray: multiple time in loop for multiple RLMObjects, the first RLMObject works OK, but the second RLMObject(no matter what class is) fails with EXC BAD ACCESS code1 on static variable. I think autorelease pool deallocate pointing NSMutualDictionary. Anybody got this issue? I'm using xcode 6.3.2 and Realm 0.96.3.

+ (NSArray *)createOrUpdateInRealm:(RLMRealm *)realm withJSONArray:(NSArray *)array {
    NSInteger count = array.count;
    NSMutableArray *result = [NSMutableArray array];

    for (NSInteger index=0; index*kCreateBatchSize<count; index++) {
        NSInteger size = MIN(kCreateBatchSize, count-index*kCreateBatchSize);
        @autoreleasepool
        {
            for (NSInteger subIndex=0; subIndex<size; subIndex++) {
                NSDictionary *dictionary = array[index*kCreateBatchSize+subIndex];
                id object = [self createOrUpdateInRealm:realm withJSONDictionary:dictionary];
                [result addObject:object];
            }
        }
    }

    return [result copy];
}

Error with mergePropertiesFromObject if Primary Key is Merged

Using mergePropertiesFromObject in RLMObject+Copying
causes error when mergin objects with primary keys.

I have solved the problem like this

First add this to RLMObject+Copying

  // only update non primary keys
            if (!property.isPrimary){
                id value = [object valueForKeyPath:property.name];
                [self setValue:value forKeyPath:property.name];
            }

And make isPrimary property public in Realm/RLMProperty.h


/**
 Indicates if this property is indexed.

 @see RLMObject
 */
@property (nonatomic, readonly) BOOL indexed;

/*!
 *    Indicates if this property is primary
 */
@property (nonatomic, assign) BOOL isPrimary;

And comment it out in Realm/RLMProperty.m


// private properties
@property (nonatomic, assign) char objcType;
//@property (nonatomic, assign) BOOL isPrimary;
@property (nonatomic, assign) Ivar swiftListIvar;

Is there a way for knowing if a property is primary
with out hacking realm core files?

Thanks :D

Lack of documentation

Please, add in documentation fact, that person can make in JSONInboundMappingDictionary link like dictionary to RLMObject, because it's not clearly: in mantle you have to do transport for it and I didn't see that transport in Realm-JSON, but you can do it, link it by default.

Sorry for my bad English.

Can't compile Realm.h with CocoaPods

I'm using CocoaPods and I'm assuming (haven't checked the podspec) that Realm is not listed as a dependency or something but I can't compile using Realm-JSON because of the following line:

#import <Realm/Realm.h>

Throwing the following message:

'Realm/Realm.h' file not found

And here's my Podfile definition:

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

'Realm/Realm.h' file not found

/Pods/Realm+JSON/Realm+JSON/RLMObject+JSON.h:9:9: 'Realm/Realm.h' file not found

I have updated to 0.1.2 ad now it's not able to find that...

any idea?

Validation

What do you think about optional data validation? For example, validate null values of properties and skip creating realm object, that is not valid.
Template:

+ (BOOL)isValidParsingData:(NSDictionary *)data;

or

+ (BOOL){propertyName}IsValidWithData:(NSDictionary *)data;

Strange Property Crash

JSON:

     {
        "id": 318729,
        "name": "Testing",
        "waitingTime": 2114
    }

Model.h:

     #import <Realm/Realm.h>

     @interface LineTest : RLMObject
     @property NSInteger id;
     @property NSString *name;
     @property NSInteger waitingTime;   // Crash When Uncommented
     @end

If I comment the waitingTime property, REALM is importing the jSON without error. But if not, the app crashs.

Success Output:

    2015-09-24 02:12:40.454 Get In Manager[2119:5308745] result: (
        "Model {\n\tid = 318729;\n\tname = Testing;\n}"
    )

Crash (with waitingTime uncommented):

    2015-09-24 02:06:45.464 MyApp1777:5299422] *** Terminating app due to uncaught exception 'RLMException', reason: 'Missing property value'

Can it be happen due the capital letters in the middle of the property name? (waitingTime)

crash with the following json

json

{
    "list": [
        {
            "liveid": "23",
            "name": "CCTV1",
            "catid": "1",
            "currentlive": {
                "id": "227670",
                "channelid": "23"
            },
            "nextlive": {
                "id": "227671",
                "channelid": "23"
            }
        },
        {
            "liveid": "73",
            "name": "cctv1-2m",
            "catid": "1",
            "currentlive": "",
            "nextlive": ""
        }
    ]
}

Model:LiveChannelList

@interface LiveChannelList : RLMObject

@property NSString * catid;
@property LiveChannelInfo * currentlive;
@property NSString * liveid;
@property NSString * name;
@property LiveChannelInfo * nextlive;

@end

RLM_ARRAY_TYPE(LiveChannelList)

@implementation LiveChannelList

+(NSString *)primaryKey{

    return @"liveid";
}

+ (NSDictionary *)JSONInboundMappingDictionary {

    return @{
             @"liveid": @"liveid",
             @"name": @"name",
             @"catid": @"catid",
             @"currentlive": @"currentlive",
             @"nextlive": @"nextlive"
             };
}
@end

Model:LiveChannelInfo

@interface LiveChannelInfo : RLMObject

@property  NSString * idField;
@property  NSString * channelname;

@end

@implementation LiveChannelInfo

+ (NSDictionary *)JSONInboundMappingDictionary {

    return @{
             @"id": @"idField",
             @"channelid": @"channelid"
             };
}

@end

crash ,because the second data in json , currentlive and nextlive ,their valus is ""
I try to resolve ,but ...

RLMObject without PK

It seems to me that it is currently impossible to use the API for an RLMObject without a primary key as it exclusively relies on the underlying createOrUpdate Realm API, which throws an exception in such case.

Would it be possible for you to either expose a new API to do so and/or expose the "private" APIs that do the dictionary mapping ?

Improve documentation by commendign to use try/catch

I've been dealing with an invisible error in this code

RLMRealm *realm = [RLMRealm defaultRealm];
[realm beginWriteTransaction];
[self createOrUpdateInRealm:realm withJSONDictionary:serverResponse];
[realm commitWriteTransaction];

until i used try/catch for receive the "Invalid value" exception like this:

RLMRealm *realm = [RLMRealm defaultRealm];
[realm beginWriteTransaction];
@try
{
    [self createOrUpdateInRealm:realm withJSONDictionary:serverResponse];
}
@catch(NSException *exception)
{
    NSLog(@"Couldn't import due to exception: %@", exception.description);
}
@finally
{
    [realm commitWriteTransaction];
}

Maybe it has been due to, for some reason, that during testing some RLMExceptions do not raise, i don't know, but i'll asume this as a best practice.

merging two field into one

hello,

is there any way to merge two field into one?
for example, if the dictionary contains the following:
{ street 1 : "xxx",
street 2 : "yyy" }

I want merge it to just "street" property.

thanks!

How to parse an array of string

Does anyone know how to parse an array of string. Like this:

"zoneInfo": {
    "tariffInfoLines": [
        "In this city you pay per minute."
    ]
}

We have a zoneInfo object that contains a tariffInfoLines array. This tariffInfoLines array contains strings. To store in Realm, i define RealmString object and store it in RLMArray

@interface RealmString : RLMObject
@property NSString *stringValue;
@end
@implementation RealmString
@end

RLM_ARRAY_TYPE(RealmString)

@interface TariffInfo : RLMObject
@property RLMArray<RealmString> *storedTariffInfoLines;
@end

But i dont know how to parse it from JSON using Realm-JSON. The application will crash if you try to. So i really need some help to solve this problem!

Custom date format in MCJSONDateTransformer

Why in MCJSONDateTransformer are there only three date's formats? For some reasons i'm getting date like "yy.MM.dd' 'hh:mm", and I can't parse it by this transport. Maybe should add method like valueTransformerWithDateFormat:(NSString ) or (NSDateFormat)? If you accept it, i'll write it.

relationships not working when using swift

I defined my RLMObject-Models in Swift and defined a relationship like the following:

dynamic var children = RLMArray(objectClassName: MYCategory.className())

With this, I get nil for modelClass in RLMObject+JSON.mh#145:

Class modelClass = NSClassFromString([[self class] className]);

which works as soon as I add

@objc(MyCategory)

above my swift class implementation. But then, I get the following error:

RLMArray properties require a protocol defining the contained type - example: RLMArray<Person>

thrown in RLMProperty.mm#151

Is there a way to map relationships for models defined in Swift?

Integration with Realm Swift

Hi, just wondering if it's possible to integrate this with Realm Swift added to a project as per http://realm.io/docs/cocoa/0.83.0/ (swift).

I've tried adding the source and using a bridging header but had no luck getting the extension to be visible :(

Would love to use Realm-JSON in an upcoming project.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.