Coder Social home page Coder Social logo

objectiverecord's Introduction

ObjectiveRecord CocoaPod Build Status

Objective Record is a lightweight ActiveRecord way of managing Core Data objects. If you've used Ruby on Rails before, it might sound familiar.

No AppDelegate code required. It's fully tested with Kiwi.

Usage

  1. Install with CocoaPods or clone
  2. #import "ObjectiveRecord.h" in your model or .pch file.

Create / Save / Delete

Person *john = [Person create];
john.name = @"John";
[john save];
[john delete];

[Person create:@{ 
    @"name" : @"John",
    @"age" : @12, 
    @"member" : @NO 
}];

Finders

// all Person entities from the database
NSArray *people = [Person all];

// Person entities with name John
NSArray *johns = [Person where:@"name == 'John'"];

// And of course, John Doe!
Person *johnDoe = [Person find:@"name == %@ AND surname == %@", @"John", @"Doe"];

// Members over 18 from NY
NSArray *people = [Person where:@{ 
                      @"age" : @18,
                      @"member" : @YES,
                      @"state" : @"NY"
                  }];

// You can even write your own NSPredicate
NSPredicate *predicate = [NSPredicate
    predicateWithFormat:@"(name like[cd] %@) AND (birthday > %@)",
            name, birthday];
NSArray *results = [Person where:predicate];

Order and Limit

// People by their last name ascending
NSArray *sortedPeople = [Person allWithOrder:@"surname"];

// People named John by their last name Z to A
NSArray *reversedPeople = [Person where:@{@"name" : @"John"} 
                                  order:@{@"surname" : @"DESC"}];

// You can use NSSortDescriptor too
NSArray *people = [Person allWithOrder:[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]];

// And multiple orderings with any of the above
NSArray *morePeople = [Person allWithOrder:@"surname ASC, name DESC"];

// Just the first 5 people named John sorted by last name
NSArray *fivePeople = [Person where:@"name == 'John'"
                              order:@{@"surname" : @"ASC"}
                              limit:@(5)];

Aggregation

// count all Person entities
NSUInteger personCount = [Person count];

// count people named John
NSUInteger johnCount = [Person countWhere:@"name == 'John'"];

Custom ManagedObjectContext

NSManagedObjectContext *newContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
newContext.persistentStoreCoordinator = [[CoreDataManager instance] persistentStoreCoordinator];

Person *john = [Person createInContext:newContext];
Person *john = [Person find:@"name == 'John'" inContext:newContext];
NSArray *people = [Person allInContext:newContext];

Custom CoreData model or .sqlite database

If you've added the Core Data manually, you can change the custom model and database name on CoreDataManager

[CoreDataManager sharedManager].modelName = @"MyModelName";
[CoreDataManager sharedManager].databaseName = @"custom_database_name";

Examples

// find
[[Person all] each:^(Person *person) {
    person.member = @NO;
}];

for(Person *person in [Person all]) {
    person.member = @YES;
}

// create / save
Person *john = [Person create];
john.name = @"John";
john.surname = @"Wayne";
[john save];

// find / delete
[[Person where: @{ @"member" : @NO }] each:^(Person *person) {
    [person delete];
}];

Mapping

The most of the time, your JSON web service returns keys like first_name, last_name, etc.
Your ObjC implementation has camelCased properties - firstName, lastName.

Since v1.2, camel case is supported automatically - you don't have to do anything! Otherwise, if you have more complex mapping, here's how you do it:

// just override +mappings in your NSManagedObject subclass
// this method is called just once, so you don't have to do any caching / singletons
@implementation Person

+ (NSDictionary *)mappings {
  return @{ 
      @"id": @"remoteID",
      @"mmbr": @"isMember",
      // you can also map relationships, and initialize your graph from a single line
      @"employees": @{
          @"class": [Person class]
      },
      @"cars": @{
          @"key": @"vehicles",
          @"class": [Vehicle class]
      }
  };
  // first_name => firstName is automatically handled
}

@end

Testing

ObjectiveRecord supports CoreData's in-memory store. In any place, before your tests start running, it's enough to call

[[CoreDataManager sharedManager] useInMemoryStore];

Roadmap

  • NSIncrementalStore support

License

ObjectiveRecord is available under the MIT license. See the LICENSE file for more information.

objectiverecord's People

Contributors

alexgaribay avatar alladinian avatar andrewsardone avatar clarissel avatar ellneal avatar iandundas avatar ignazioc avatar jeremymailen avatar justsid avatar kattrali avatar luisobo avatar makadaw avatar mps avatar nanashi avatar nomnel avatar rohan-panchal avatar stephencelis avatar supermarin avatar vfonic avatar xavierjurado 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  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

objectiverecord's Issues

Isolate core better from mappings

We should probably make ObjectiveRecord/Core, sub spec in case someone wants no magic and to stay simple.
This also includes a bit of architectural changes in NSManagedObject+ActiveRecord.m, to check if mappings are present.

custom NSDate format

Hi,
is there a way of setting a date formatter for parsing dates? In the JSON answer I'm getting, the dates are set as milliseconds since 1970 e.g.

"anniversary": 1388646266064

cheers

Support for count queries

Being able to efficiently get the count of all or matching objects would be a useful feature! I can send a pull request.

[Test failure] : Finds in a separate context

I'm getting a test failure on this method :

it(@"Finds in a separate context", ^{
            [newContext performBlock:^{
                Person *found = [Person where:@{ @"firstName": @"Joshua" } inContext:newContext].first;
                [[found.lastName should] equal:@"Jobs"];
            }];
        });

Error message is the following :

[FindersAndCreators FindCreateSaveDeleteSpecs_AllFromAbove_InASeparateContext_FindsAllInASeparateContext] failed: 
'Find / Create / Save / Delete specs, All from above, in a separate context!, Finds all in a separate context' [FAILED], expected subject not to be nil

Swift Example

I have been trying to get ObjectiveRecord to work with swift for the past few hours. It would be nice if there was a swift example.

I think the API of this project is amazing! Especially someone coming from Ruby/Rails world into it.

Time for a new release?

The documentation is mentioning new features (like the count method) that isn't int he current Cocoapods version. Time for a new release?

Initialize with NSManagedObjectContext

Hi, this is a just question rather than a bug report. I'm using a separate core data stack manager that is setup nicely for background operations. Its creates the stack and a foreground and background context and manages the merges, etc. It does a good job and I'd like to keep using it.

I'd also like to use your library for the awesome data access methods and was wondering if there is an easy way to initialize it using just the NSManagedObjectContext and avoid it setting up the stack? Basically just a way to simply create the shared instance on top of a context that already exists? I think there was a method to create a custom context, but I'd really like to have an option for the singleton to be setup for my existing context to keep the syntax short and sweet.

I appreciate all your work thanks for any help you can provide.

Missing #import "ObjectiveSugar.h"

Checked out the project and copied the files to my project. Tried to build the whole thing but got an error on NSManagedObject+ActiveRecord.m: "'ObjectiveSugar.h' file not found".

How to "unmap" unused JSON fields ?

I have a field in my remote JSON object that I don't want to use in my core data object.

How can I "unmap" this field to avoid NSUnknownKeyException ?

Thanks for your help.

importing ObjectiveSugar.h

Hello.
I used methods "each" and "first" from ObjectiveSugar. In previous version of ObjectiveRecord you imported the ObjectiveSugar.h file in NSManagedObject+ActiveRecord.h so "each" and "first" was visible. Now you import ObjectiveSugar.h in "NSManagedObject+ActiveRecord.m" and I can not see and use this two methods. What was the reason for this change and can you make it like it was?

create with dictionary

Hi,
I want to create an managed object from a dictionary as shown in the example

[Person create:@{ @"name" : @"John", @"age" : @12, @"member" : @NO }];

but the dictionary I'm getting from a web service has some more attributes that I'm not interested and are not defines in in my model.

When using the create method, it crashes because it tries to assign all attributes from the dictionary to my object.

Is there a way to ignore those ?

regards,
Jan

custom NSManagedObjectContext crash.

NSManagedObjectContext *newContext = [NSManagedObjectContext new];

Person *john = [Person createInContext:newContext];
Person *john = [Person where:@"name == 'John'" inContext:newContext].first;
NSArray *people = [Person allInContext:newContext];

I use these code, but will crash, reason is:+entityForName: could not locate an NSManagedObjectModel for entity name 'Person'

I think the newContext must setPersistentStoreCoordinator, how do you think about this?

Override on Category

Hi Marin

I found the override on category not work on my code base

my subclass's + (NSDictionary *)mappings will not be called if I use ObjetiveRecord by Cocoapods,
and + (NSString *)entityName will return NSManagedObject if this call if from NSManagedObject+Mappings.m

I found some explanation, do you think so?

Obj-C allows you to add methods to an existing class using Categories. So if you add a method to NSString, the categoriesed method is available to NSMutableString and all classes which inherits NSString or any subclasses of NSString.

But you should avoid to Override the category.

You will not be 100% sure which method will be called. It depends on compiler.
http://stackoverflow.com/questions/14259517/override-a-method-in-objective-c-via-category

Nested objects won't get mapped

Does ObjectiveRecord have NSKeyValueCoding support, for using valueForKeyPath instead of objectForKey?

I want to avoid to have an entity for each nested objects in the payload.
This is a map example of what I have, but can't make it work. Any thoughts?

+ (NSDictionary *)mappings {
    return @{
             @"icons.image_48": @"image48"
             @"icons.image_64": @"image64"
             };
}

Possible bug introduced in 1.5

On 1.4, this snippet works:

MMBundleSet *bundleSet= [MMBundleSet create:@{
    @"type": @(1),
}];

NSLog(@"Created bundleSet with type: %i", bundleSet.typeRawValue);

outputting (correctly):

2014-04-24 15:27:09.654 Production 3G[90621:60b] Created bundleSet with type: 1

However on 1.5, it now outputs:

2014-04-24 15:29:47.962 Production 3G[91519:60b] Created bundleSet with type: 0

MMBundleSet has a single attribute typeRaw, shown here:

I use the following method for storing ENUMs in Core Data:

#pragma mark ENUM Type transformers:
- (TTBundleSetUnit)type {
    return (TTBundleSetUnit)[self typeRawValue];
}
- (void)setType:(TTBundleSetUnit)bundleSetUnit {
    [self setTypeRawValue:bundleSetUnit];
}

A Strange problem about [Class where:*];

I have a really strange bug appeared while using ObjectiveRecord. I'm not sure it's a bug of ObjectiveRecord. But I have no idea how to fix it.

Here's the code:

ELStack* stack = (ELStack*)([ELStack where:@{@"type": @(ELStackTypeInbox)}][0]);

This code works fine when the code was executed at the first time. It's fetches the things I want, But failed when I try to call it more than once. It'll return a nil result even I haven't change anything about the Object.

I try to solve the problem on my own. So I NSLog what's happening in my database. While I NSLog(@"%@",[ELStack all]) the database, It's appears there IS something happened.

The first fetch (which works fine), the NSLog return a NSArray of ELStacks, which there are no custom attributes showing in the NSLog. But when I try to fetch them again. The NSLog return ELStacks contains attributes. In this period, There's nothing changing in the database. I have no idea what this mean, no idea how it happen, and absolutely no idea how to fix it.

Please help me figure out what really happen. Thank you.

Integrating ObjectiveRecord with iCloud

I'm new to Core Data and iCloud, and ObjectiveRecord looks promising. As I understand it, I don't need any of my Core Data boilerplate code in my AppDelegate file.

But some of that boilerplate is required to plug in to iCloud, particularly the self.persistentStoreCoordinator which I observer in my iCloud code:

- (void)registerForiCloudNotifications {
  NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];

  [notificationCenter addObserver:self
                         selector:@selector(storesWillChange:)
                             name:NSPersistentStoreCoordinatorStoresWillChangeNotification
                           object:self.persistentStoreCoordinator];

  [notificationCenter addObserver:self
                         selector:@selector(storesDidChange:)
                             name:NSPersistentStoreCoordinatorStoresDidChangeNotification
                           object:self.persistentStoreCoordinator];

  [notificationCenter addObserver:self
                         selector:@selector(persistentStoreDidImportUbiquitousContentChanges:)
                             name:NSPersistentStoreDidImportUbiquitousContentChangesNotification
                           object:self.persistentStoreCoordinator];
}

How do I plug in to ObjectiveRecord's persistent store coordinator for iCloud use?

"Cannot create an NSPersistentStoreCoordinator with a nil model" error message

I'm using Xcode 5.0.2 and iOS 7. I followed the instructions from the readme file and got the error below. I then tried without using CocoaPods by just copy-pasting the ObjectiveRecord and ObjectiveSugar files into the project directory. I get the same error. (When I try with CocoaPods, I see a missing (red) libPods.a in the projects settings / linked library page.

I'm on a clean, new project. Have I done something wrong or is there some issue with the current version of ObjectiveRecord? Or why else won't it work with a clean project?

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Cannot create an NSPersistentStoreCoordinator with a nil model'
*** First throw call stack:
(
0 CoreFoundation 0x01ab05e4 exceptionPreprocess + 180
1 libobjc.A.dylib 0x018338b6 objc_exception_throw + 44
2 CoreData 0x00025b0e -[NSPersistentStoreCoordinator initWithManagedObjectModel:] + 398
3 asdf 0x00007831 -[CoreDataManager persistentStoreCoordinatorWithStoreType:storeURL:] + 193
4 asdf 0x00007299 -[CoreDataManager persistentStoreCoordinator] + 169
5 asdf 0x00006f5a -[CoreDataManager managedObjectContext] + 106
6 asdf 0x00008086 +[NSManagedObjectContext(ActiveRecord) defaultContext] + 86
7 asdf 0x000088da +[NSManagedObject(ActiveRecord) create] + 58
8 asdf 0x0000256d -[ViewController viewDidLoad] + 93
9 UIKit 0x006b5318 -[UIViewController loadViewIfRequired] + 696
10 UIKit 0x006b55b4 -[UIViewController view] + 35
11 UIKit 0x005dd9fd -[UIWindow addRootViewControllerViewIfPossible] + 66
12 UIKit 0x005ddd97 -[UIWindow _setHidden:forced:] + 312
13 UIKit 0x005de02d -[UIWindow _orderFrontWithoutMakingKey] + 49
14 UIKit 0x005e889a -[UIWindow makeKeyAndVisible] + 65
15 UIKit 0x0059bcd0 -[UIApplication _callInitializationDelegatesForURL:payload:suspended:] + 1851
16 UIKit 0x005a03a8 -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] + 824
17 UIKit 0x005b487c -[UIApplication handleEvent:withNewEvent:] + 3447
18 UIKit 0x005b4de9 -[UIApplication sendEvent:] + 85
19 UIKit 0x005a2025 _UIApplicationHandleEvent + 736
20 GraphicsServices 0x02ea22f6 _PurpleEventCallback + 776
21 GraphicsServices 0x02ea1e01 PurpleEventCallback + 46
22 CoreFoundation 0x01a2bd65 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION
+ 53
23 CoreFoundation 0x01a2ba9b __CFRunLoopDoSource1 + 523
24 CoreFoundation 0x01a5677c __CFRunLoopRun + 2156
25 CoreFoundation 0x01a55ac3 CFRunLoopRunSpecific + 467
26 CoreFoundation 0x01a558db CFRunLoopRunInMode + 123
27 UIKit 0x0059fadd -[UIApplication _run] + 840
28 UIKit 0x005a1d3b UIApplicationMain + 1225
29 asdf 0x0000aafd main + 141
30 libdyld.dylib 0x02b4270d start + 1
31 ??? 0x00000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)

Option to delete without saving context.

Currently, the delete method marks the object for deletion and saves the context. When iterating through a large number of objects and deleting this could be expensive. Perhaps a method such as the following would be a good solution:

- (void)deleteAndCommit:(BOOL)doCommit;

Rethink mappings

I see a few issues with the way mappings are currently implemented:

  1. They are automatically, categorically added to all NSManagedObject classes.
  2. They are coupled to the NSManagedObject+ActiveRecord category.
  3. They are unidirectional (there's no way to cast local properties back into remote ones).
  4. They are declarative (and with @kattrali's #66, the dictionary can become quickly bloated).
  5. They do a lot by default (auto-camelizing, for example).
  6. They are a memory leak (we cache every unique remote key that we check for).

Let's explore ways to address these issues.

Proposal 1: Protocol-based Mappings

One thought is that we could provide a protocol, like NSCoding, that could be used to serialize/deserialize these mappings. E.g.,

@protocol ORCoding <NSObject>
+ (NSDictionary *)dictionaryFromRemoteDictionary:(NSDictionary)dict;
- (NSDictionary *)remoteDictionaryRepresentation;
@end
  1. One would have to manually opt-in to the protocol.
  2. Looser coupling, using conformsToProtocol:.
  3. It would enforce bidirectional mappings.
  4. Method logic is more imperative.
  5. It's not included by default, so there are no defaults.
  6. No memory leaks (that are our fault, anyway)!

Dictionaries nested more than 1 level deep break findOrCreate:

Right now OR handles creating nested entity objects during update: using the classes specified in an entity's mappings block. However, when a dictionary contains multiple levels of objects, the nested dictionaries aren't processed recursively, and are treated like values for entity property keys, so -[NSManagedObject predicateForDictionary:] returns a format like: id == 4 AND type == Cajun AND owner == { id = 6 }, resulting in a crash, since the owner value is not in a valid format.

Example

Given I have a Restaurant class, an Owner class, and a Car class, where a Restaurant has an Owner and an Owner has a Car

@implementation Restaurant
+ (NSDictionary *)mappings {
        return @{ @"id" : @"restaurantID",
                          @"owner" : @{ @"class" : [Owner class]}};
}
@end

@implementation Owner
+ (NSDictionary *)mappings {
        return @{ @"id" : @"ownerID",
                          @"car" : @{ @"class" : [Car class]}};
}
@end

@implementation Car
+ (NSDictionary *)mappings {
        return @{ @"id" : @"carID" };
}
@end

When I want to update my Restaurant instance with a dictionary that looks like so:

[restaurant update:@{
        @"id" : @4, 
        @"type" : @"Cajun",
        @"owner" : @{ 
                @"id" : @6, 
                @"full_name" : @"Rory Hill"
                @"car" : @{ @"id" : @43, @"model" : @"3"}}}];

Then I should have one Restaurant, one Owner, and one Car when the update is complete.

CoreDatamanager sharedInstance managedObjectContext init as a MainContext type ?

Hello,

This is really more a question than an issue, I was wondering how you were using this method [[CoreDatamanager sharedInstance] managedObjectContext], I always use it as the main context, so I was wondering if it was meant to be used like that and if it is, then maybe it would make sense to create it like that :

_managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];

instead of simply "init" ?

Sort Methods missing from Pod Version

Hi guys, first up GREAT work with this project, thank you!

It may be me, but I'm not seeing any of the sort methods in the version coming down from CocoaPods:

#pragma mark - Default Context

- (BOOL)save;
- (void)delete;
+ (void)deleteAll;

+ (id)create;
+ (id)create:(NSDictionary *)attributes;
- (void)update:(NSDictionary *)attributes;

+ (NSArray *)all;
+ (NSArray *)where:(id)condition;
+ (NSArray *)whereFormat:(NSString *)format, ...;
+ (instancetype)findOrCreate:(NSDictionary *)attributes;

My pod entry is:

platform :ios, '7.0'

pod 'ObjectiveRecord'

and when I run pod install I get:

Using ObjectiveRecord (1.4.0).

Advice appreciated and thanks again.

Mappings are instance method?

Why is that the mappings are overridden as instance methods of NSManagedObject? Probably they should be a class method of NSManagedObject.

I would not expect different mappings for different instances of the same model class. And additionally I have seen that the mappings are cached as a class method. Is there a particular reason for this? Or maybe just a bug?

Errors on Managed Object

One thing I love above ActiveRecord is getting errors on the object. Of course, you can get the errors on the MOC but it gives you errors of EVERY object in the context.
I'm thinking after an [object save] operation, you can go object.errors and it filters only the relevant errors. It could even be spiced up with a special errors class that can respond to messages like toString or toWhatever.

Thoughts?

Support for ordering/sorting.

It would be great to be able to sort the collection. Perhaps add a method such as:

+(NSArray*) where:(id)condition order:(id)sorting;

That could accept a sorting object such as:

@{
  @"createdAt" : @"desc",
  @"group"     : @"asc"
}

NSManagedObject+ActiveRecord finds and creates objects in different contexts

Method

+ (instancetype)findOrCreate:(NSDictionary *)properties inContext:(NSManagedObjectContext *)context {
    NSManagedObject *existing = [self where:properties inContext:context].first;
    return existing ?: [self create:properties];
}

finds object in the provided context but creates in default context. I think it would be better also create object in the provided context

Add support for generic value transformation in mappings

Right now OR supports value transformation for dates in a common format, or (implicitly) dates in other formats by overriding defaultFormatter in NSManagedObject subclasses.

It would be convenient to support a more generic kind of value transformation. Two ideas:

Option 1 - Formatter Classes

Add a mappings property for formatter that takes an NSFormatter subclass as a value. When a formatter is present, the value for that key is processed through -[FormatterInstance getObjectValue:forString:errorDescription:] before updating the record. Here's an example usage:

+ (NSDictionary *)mappings
{
    return @{
             @"id" : PRIMARY_KEY,
             @"sandwich" : @{
                     @"class": [Sandwich class]
                     @"formatter": [SandwichFormatter class] },
             @"timestamp" : @{
                     @"formatter": [SuperSpecialAPIDateFormatter class] }
             };
}

A caveat would be that we'd presumably need to store any instances of formatters in thread dictionaries, as they may not be threadsafe.

Option 2 - Inline Blocks

Add a transform block to mappings, for inline value formatting. Example:

+ (NSDictionary *)mappings
{
    return @{
             @"id" : PRIMARY_KEY,
             @"sandwich" : @{
                     @"class": [Sandwich class]
                     @"transform": ^(id value) { 
                           return [SandwichFormatter sanitizeParams:value] } },
             @"timestamp" : @{
                     @"transform": ^(id value) { 
                           return [[SuperSpecialAPIDateFormatter sharedFormatter] dateForString:value];  } 
             }
             };
}

Managing thread safety would be up to the user (and therefore NMP), though this way would probably have more code duplication.

Unrecognized selector sent to class

Hi, I've a project build a time ago and was working fine, but now with the updated ios 7 sdk it stop working, seems that the category is not adding the custom methods. In the xcode recognizes the methods in the autocomplete dropdown. I made no change, it was installed via cocoapods (version 1.4.0) and it doesn't recognize the ObjectiveRecord methods.

In the Prefix.pch added

#import "ObjectiveRecord.h"

And then my model

// Version.h
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>


@interface Version : NSManagedObject

@property (nonatomic, retain) NSString * objectId;
@property (nonatomic, retain) NSString * database;
@property (nonatomic, retain) NSNumber * version;

@end

// Version.m
#import "Version.h"

@implementation Version

@dynamic objectId;
@dynamic database;
@dynamic version;

@end

Then I call it

NSArray *versions = [Version where:@{@"database": database}];

And got

+[Version where:]: unrecognized selector sent to class 0x1ee73c

Even if I import ObjectiveRecord in the .m file I got the error

Regards

pod installs old version

Hello,
pod search shows as '~> 1.3.1' but installs old version which does not have -

  • (instancetype)sharedManager;

Thanks!

Proper thread-safe way to use ObjectiveRecord

Since CoreDataManager is a singleton with a managedObjectContext and Apple recommends thread confinement (separate context for each thread) for Core Data, what is the proper way to use ObjectiveRecord in a multi threaded app? For example when some of the data processing occurs on background threads.

I see that most enhanced methods on NSManagedObject have custom context versions. Is this the recommendation?

Save Only the Object

This can be achieved by having exactly one MOC per object but I'm not sure of the implications in both using it and coding it. Would there be huge memory implications? Would this have to be a special condition, like fetching an object with a hasOwnManagedObjectContext flag set to yes? Are there alternatives to this, perhaps when calling save creating a child MOC, saving that, and merging back into the original MOC?

Cocoapods project is outdated

pods version of ObjectiveRecord is outdated and there are few missing methods which are used in SampleProject.

eg.
find in NSManagedObject+ActiveRecord.h

Find or create?

Firstly, I would like to say that your lib is lovely. It really empowers CD and wish that iOS SDK has bundled something like this in their framework.

Being on ror for quite some time, I tend to thing in a interface from rails.

After I use ObjectiveRecord for a while, I find myself using

Person* p = [[Person where:@{ @"id", @5}] first];
if (p) {
    [p update:data];
} else {
    p = [Person create:data];
}

all the time. My question is simple, do you have interface like 'findOrCreate' just to avoid this boring check?

New instances created when update.

Hi, thanks for all your great work. This repo works like a charm.

But I found there may be something wrong when trying to update a existing record.
I have a entity called Post and another one called Author. The Post has a simple to one relationship with Author.
When I do the following:

Post *post = [Post whereFormat:@"postId == %d", postId].firstObject;
if (post != nil) {
    // if we already got the post, just update.
    [post update:attributes];
}
else {
    [Post create:attributes];
}

It seems send update message to post always create a new author instance. So after update the post, I got two same author records in sqlite.
This could be caused by the following code in NSManagedObject+ActiveRecord (line 188)

- (void)hydrateObject:(id)properties ofClass:(Class)class forKey:(NSString *)key {
    [self setSafeValue:[self objectOrSetOfObjectsFromValue:properties ofClass:class]
                forKey:key];
}

objectOrSetOfObjectsFromValue:ofClass: will always create a new instance of class.

I have no idea how to solve this, Please help me out.

Find an entity which there is only one entity

Hi,

I just begin to use ObjectiveRecord and I want to say big thanks to those which made this amazing library !

I've a question about find entities from a context. I've an entity named "Basket" which contains the current basket of an user. There will be only one Basket entity.

If I call the method [Basket all] I will have an array of Basket with all the time only one entity inside.

Is there a method which permits to get only the instance of my entity without returning an array ?

Because if I use method with order parameter I will still have an array.

Any suggestions ?

Consider making NSPredicates API public?

First of all, thanks for really awesome framework, it looks much better than monstrous MagicalRecord.

I'm using ObjectiveRecord in one of my project, and it takes advantage of NSFetchedResultsController to display data in UITableView and UICollectionView. Now most ActiveRecord style methods allow to fetch data from CoreData, but we don't need that with NSFetchedResultsController.

I could, of course, define private category, and just use private method of ObjectiveRecord, but that's probably not good. It could be great, if ObjectiveRecord provided a way to get NSPredicates from fancy where: methods.

Mappings in findOrCreate

I'm trying to import JSON data into CoreData using ObjectiveRecord:

  for( id eventData in results ) {
    [Event findOrCreate: eventData ];
  }

Next, I have defined the mappings as followed:

- (NSDictionary *)mappings
{
  return @{ @"id"          : @"eventID",
            @"business_id" : @"businessID",
            @"description" : @"detail" };
}

However, I'm getting the following error message:

reason: 'keypath description not found in entity <NSSQLEntity Event id=2>'

I'm guessing that this has something to do with the mappings because it's not 100% certain how this mappings work. Does it work as follows:

@{  @"id_from_json" : @"id_in_core_data_model" }

or

@{ @"id_in_core_data_model" : @"id_from_json" }

In any case, it doesn't appear that this method is ever called when I run the application.

+ (NSDictionary *)mappings never called

error:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSDictionaryI managedObjectContext]: unrecognized selector sent to instance 0x16e5e880'

I have imported the model objects and the categories like:

#import "Person.h"
#import "Address.h"
#import "Person+Mappings.h" 
#import "Address+Mappings.h"

dictionary:

NSDictionary *aPerson = @{@"name": @"Peter",
                              @"home":@{@"latitude": @37.12323123,
                                        @"longitude": @141.232323 }

Person *peter = [Person create:aPerson];

"Address+Mappings":

+ (NSDictionary *)mappings{
    //I put a breakpoint here and it never get called
    return @{@"owner": @{@"class": [Person class]}};   
}

"Person+Mappings":

+ (NSDictionary *)mappings{
    //I put a breakpoint here and it never get called
    return @{@"home": @{@"class": [Address class]}};
}

Release 1.5

@stephencelis just opening this so we can keep track of the release blockers:

  • Add sorting with strings only, not just nested dicts (@"surname ASC" instead of @{@"surname" @"ASC"})
  • See if we can merge #60 without decreasing performance significantly

Feel free to edit the issue if I've left out something

NSInvalidArgumentException when trying to create a new object

I have a very basic setup. When I try to call [ModelName create] I get an exception at line 120 in CoreDataManager.m

2013-12-02 20:54:10.674 LDLN[1362:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Cannot create an NSPersistentStoreCoordinator with a nil model'

The problem seems to be that the code can't find a valid resource with the extension "momd" at line 69 of the same file. This function returns nil which causes the crash when nil is trying to be accessed.

Is this a setup issue that is undocumented or an outlier?

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.