CoreData存储字典数组
WeChat6ea51eb9612f19a81dd99b1e790626eb.png1:在Entity Attribute中属性类型选择Transformable
2: 然后右侧Transformer写上一个类名,之后创建类文件需要用这个类名和属性对应上
3: 创建一个继承NSValueTransformer的类FloderIds 在类里写上归档的代码
+ (Class)transformedValueClass
{
return [NSArray class];
}
+ (BOOL)allowsReverseTransformation
{
return YES;
}
- (id)transformedValue:(id)value {
//转换成NSData保存到数据库
return [NSKeyedArchiver archivedDataWithRootObject:value requiringSecureCoding:YES error:nil];
}
- (id)reverseTransformedValue:(id)value
{
return [NSKeyedUnarchiver unarchivedObjectOfClass:[NSArray class] fromData:value error:nil];
}
之后可以正常使用了
- (void)insertFlodersEntity
{
for (int i = 0; i < 50; i++) {
UserFloderEntity *floderEntity = [NSEntityDescription insertNewObjectForEntityForName:@"UserFloderEntity" inManagedObjectContext:self.context];
floderEntity.id = 200000 + I;
floderEntity.uid = 100000 + I;
NSArray *fids = @[@(200000+i),@(200000+i+1),@(200000+i+2),@(200000+i+3),@(200000+i+4),@(200000+i+5)];
floderEntity.fids = fids;
floderEntity.status = NO;
}
[self saveContext];
}
- (void)fetchFloderEntity
{
NSFetchRequest *floderEntityRequest = [UserFloderEntity fetchRequest];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"id > %d",0];
[floderEntityRequest setPredicate:predicate];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]initWithKey:@"id" ascending:YES];
[floderEntityRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor,nil]];
NSError *error = nil;
NSArray *fetchedObjects = [_context executeFetchRequest:floderEntityRequest error:&error];
UserFloderEntity *floder = [fetchedObjects lastObject];
NSArray *arr = (NSArray*)floder.fids;
NSLog(@"%d %@",floder.id,arr);
}
CoreData生成实体类文件
需要在CoreData.storyboard中需要生成的实体,右边属性栏里Codegen中选择Manual/none 不然系统生成一份代码,自己生成一份代码会重复
Relationships
关联实体 WeChate7388b394418abbcd5317c097c5b4e07.png图中红框1
Destination:代表关联的实体,
Inverse:代表被关联的实体中反向关联的数据
红框2中
Delete Rule:代表删除规则,即在一个实体中删除,会不会在关联的实体中表现出来,一般选Nullify,会自动管理,如果一个关联属性是一对多,或者多对多。往一个实体中的属性添加值,另一个属性也会体现出来。
WeChat1d0bc8750d56da4459bcfd7b5b874b89.png
如果Codegen中选择Manual/None,不自动生成代码,则需要我们在Editor中选择Create ManagerObject subclass 手动生成实体文件,并且实现几个添加属性和删除属性的方法, WeChat012e0e5e4273b715dd4d84498b26bcd1.png
其中红框的几个方法是没有实现的,需要在m文件中实现如下
#import "FileEntity+CoreDataProperties.h"
@implementation FileEntity (CoreDataProperties)
+ (NSFetchRequest<FileEntity *> *)fetchRequest {
return [NSFetchRequest fetchRequestWithEntityName:@"FileEntity"];
}
@dynamic id;
@dynamic name;
@dynamic length;
@dynamic star;
@dynamic data;
@dynamic last_read_position;
@dynamic last_open_time;
@dynamic create_time;
@dynamic status;
@dynamic infloder;
@end
@implementation FileEntity (CoreDataGeneratedAccessors)
- (void)addInfloderObject:(FloderEntity *)value
{
NSMutableSet *inFloder = [self.infloder mutableCopy];
[inFloder addObject:value];
self.infloder = inFloder;
}
- (void)removeInfloderObject:(FloderEntity *)value
{
NSMutableSet *inFloder = [self.infloder mutableCopy];
[inFloder removeObject:value];
self.infloder = inFloder;
}
- (void)addInfloder:(NSSet<FloderEntity *> *)values
{
NSMutableSet *inFloder = [self.infloder mutableCopy];
for (FloderEntity *floderEntity in values) {
[inFloder addObject:floderEntity];
}
self.infloder = inFloder;
}
- (void)removeInfloder:(NSSet<FloderEntity *> *)values
{
NSMutableSet *inFloder = [self.infloder mutableCopy];
for (FloderEntity *floderEntity in values) {
[inFloder removeObject:floderEntity];
}
self.infloder = inFloder;
}
@end
然后测试代码如下
#import "AppDelegate.h"
#import <CoreData/CoreData.h>
#import "FloderEntity+CoreDataClass.h"
#import "FloderEntity+CoreDataProperties.h"
#import "FileEntity+CoreDataClass.h"
#import "FileEntity+CoreDataProperties.h"
@interface AppDelegate ()
@property (nonatomic,readwrite,strong)NSManagedObjectModel *managedObjectModel;
@property (nonatomic,readwrite,strong)NSPersistentStoreCoordinator *persistentStoreCoordinator;
@property (nonatomic,readwrite,strong)NSManagedObjectContext *context;
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[self managedObjectModel];
[self persistentStoreCoordinator];
[self context];
// [self loadFiles];
[self fetchEntity];
return YES;
}
- (NSManagedObjectModel *)managedObjectModel
{
if (!_managedObjectModel)
{
NSURL *modelURL = [[NSBundle mainBundle]URLForResource:@"CSCoreDataDemo02" withExtension:@"momd"];
_managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
}
return _managedObjectModel;
}
- (NSPersistentStoreCoordinator*)persistentStoreCoordinator
{
if (!_persistentStoreCoordinator) {
_persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc]initWithManagedObjectModel:self.managedObjectModel];
NSURL *sqlURL = [[self documentDirectoryURL] URLByAppendingPathComponent:@"CSCoreDataDemo.sqlite"];
NSError *error;
[_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:sqlURL options:nil error:&error];
if (error) {
NSLog(@"falied to create persistentStoreCoordinator %@",error.localizedDescription);
}
}
return _persistentStoreCoordinator;
}
- (NSManagedObjectContext*)context
{
if (!_context) {
_context = [[NSManagedObjectContext alloc]initWithConcurrencyType:NSMainQueueConcurrencyType];
_context.persistentStoreCoordinator = self.persistentStoreCoordinator;
}
return _context;
}
- (NSError*)saveContext
{
NSError *error = nil;
if ([self.context hasChanges])
[self.context save:&error];//使操作生效
if (error) return error;
else return nil;
}
- (NSURL*)documentDirectoryURL
{
return [[NSFileManager defaultManager]URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask].lastObject;
}
- (void)loadFiles
{
NSMutableArray *fileArray = [[NSMutableArray alloc]init];
for (int i = 0; i < 50; i++) {
FileEntity *fileEntity = [NSEntityDescription insertNewObjectForEntityForName:@"FileEntity" inManagedObjectContext:self.context];
fileEntity.id = 10000 + i;
fileEntity.name = [NSString stringWithFormat:@"OFD_%d",10000 + i];
[fileArray addObject:fileEntity];
}
for (int i = 0; i < 10; i++) {
FloderEntity *floderEntity = [NSEntityDescription insertNewObjectForEntityForName:@"FloderEntity" inManagedObjectContext:self.context];
floderEntity.id = 1000 + i;
floderEntity.name = [NSString stringWithFormat:@"floder_%d",1000 + i];
NSMutableSet *files = [[NSMutableSet alloc]init];
for (int j = 0; j<5; j++) {
[files addObject:[fileArray objectAtIndex:(i*5 + j)]];
}
[floderEntity addFiles:files];
}
[self saveContext];
}
- (void)fetchEntity
{
NSFetchRequest *floderRequest = [NSFetchRequest fetchRequestWithEntityName:@"FloderEntity"];
NSSortDescriptor *floderSort = [[NSSortDescriptor alloc]initWithKey:@"id" ascending:YES];
[floderRequest setSortDescriptors:[NSArray arrayWithObjects:floderSort,nil]];
NSArray *floders = [_context executeFetchRequest:floderRequest error:nil];
for (int i = 0; i<floders.count; i++) {
FloderEntity *floderEntity = [floders objectAtIndex:i];
NSSet *files = floderEntity.files;
for (FileEntity *file in files) {
NSLog(@"file %d %@\r\n",file.id,file.name);
}
}
NSFetchRequest *fileRequest = [NSFetchRequest fetchRequestWithEntityName:@"FileEntity"];
NSArray *files = [_context executeFetchRequest:fileRequest error:nil];
for (int i = 0; i<files.count; i++) {
FileEntity *fileEntity = [files objectAtIndex:i];
NSSet * floders = fileEntity.infloder;
for (FloderEntity *floder in floders) {
NSLog(@"floder %d %@\r\n",floder.id,floder.name);
}
}
}
@end
网友评论