Skip to content

Instantly share code, notes, and snippets.

@neerajgoel82
Last active February 6, 2017 14:03
Show Gist options
  • Save neerajgoel82/0225ea31ab55e1545aba to your computer and use it in GitHub Desktop.
Save neerajgoel82/0225ea31ab55e1545aba to your computer and use it in GitHub Desktop.
This is the gist of using CoreData in iOS
FailedBankInfo.h
-----------------
#import <CoreData/CoreData.h>
@class FailedBankDetails;
@interface FailedBankInfo : NSManagedObject
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSString * city;
@property (nonatomic, retain) NSString * state;
@property (nonatomic, retain) FailedBankDetails *details;
@end
FailedBankInfo.m
-----------------
@implementation FailedBankInfo
@dynamic name;
@dynamic city;
@dynamic state;
@dynamic details;
@end
Inserting and retrieving the data
----------------------------------
NSManagedObjectContext *context = [self managedObjectContext];
FailedBankInfo *failedBankInfo = [NSEntityDescription
insertNewObjectForEntityForName:@"FailedBankInfo"
inManagedObjectContext:context];
failedBankInfo.name = @"Test Bank";
failedBankInfo.city = @"Testville";
failedBankInfo.state = @"Testland";
FailedBankDetails *failedBankDetails = [NSEntityDescription
insertNewObjectForEntityForName:@"FailedBankDetails"
inManagedObjectContext:context];
failedBankDetails.closeDate = [NSDate date];
failedBankDetails.updateDate = [NSDate date];
failedBankDetails.zip = [NSNumber numberWithInt:12345];
failedBankDetails.info = failedBankInfo;
failedBankInfo.details = failedBankDetails;
NSError *error;
if (![context save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}
// Test listing all FailedBankInfos from the store
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"FailedBankInfo"
inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
for (FailedBankInfo *info in fetchedObjects) {
NSLog(@"Name: %@", info.name);
FailedBankDetails *details = info.details;
NSLog(@"Zip: %@", details.zip);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment