How to get data by using CoreData model? - ios

I'm trying to get data by using core data,but something wrong happen.Here's the picture of my data model:
And code of Feed.h
#interface Feed (CoreDataProperties)
#property (nullable, nonatomic, retain) NSString *rssURL;
#property (nullable, nonatomic, retain) NSString *summary;
#property (nullable, nonatomic, retain) NSString *title;
#property (nullable, nonatomic, retain) NSSet *feedItems;
#end
Firstly,I'm sure I get the data of Feed Table in My FeedList TableViewController.When I tap one row of the table,it should push to the FeedItem TableViewController which contains the data of FeedItem.Here's the code of First Controller:
- (void)cellDidPress:(NSIndexPath *)atIndexPath{
if (atIndexPath.row < self.allFeeds.count) {
RSFeedItemsViewController *itemsVC = [[RSFeedItemsViewController alloc] init];
itemsVC.feed = self.allFeeds[atIndexPath.row];
[self.navigationController pushViewController:itemsVC animated:YES];
}
}
I try to get the FeedItem in my FeedItemsViewController
NSMutableArray *allItems = [[[self.feed feedItems] allObjects] mutableCopy];
And I'm getting the following exception:
po [self.feed feedItems]
<FeedItem: 0x7fe95a484540> (entity: FeedItem; id: 0xd000000007f40002 <x-coredata://918D3499-5129-4D78-8F37-3D8D478FE482/FeedItem/p509> ; data: <fault>)
2016-07-10 14:17:33.176 RSFeedReader[98980:14910776] -[FeedItem allObjects]: unrecognized selector sent to instance 0x7fe95a484540
Should I execute another fetch request to get the data of FeedItem?
Any help is appreciated.
Thanks

Related

Using JSQMessages framework with Core-data

This is just the Core-Data object for message:
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#class Account;
#interface Message : NSManagedObject
#property (nonatomic, retain) NSNumber * read;
#property (nonatomic, retain) NSDate * sentDate;
#property (nonatomic, retain) NSString * text;
#property (nonatomic, retain) NSString * receiver;
#property (nonatomic, retain) NSString * sender;
#property (nonatomic, retain) Account *account;
#end
Then this is the Messages ViewController, load messages code:
- (void)loadMessages
messages = [[NSMutableArray alloc]initWithArray:_fetchedResultsController.fetchedObjects];
//------------------------------------------------------------------------------------------------------------------------------------------------- Demo message just demo an incoming message.
static NSString *senderId = #"2";
static NSString *senderDisplayName = #"a";
JSQMessage *message = [[JSQMessage alloc] initWithSenderId:senderId
senderDisplayName:senderDisplayName
date:[NSDate distantPast]
text:#"helloloo"];
messages = [[NSMutableArray alloc]initWithObjects:message, nil];
//------------------------------------------------------------------------------------------------------------------------------------------------- Demo message just demo an incoming message.
Now I'm new to this framework https://github.com/jessesquires/JSQMessagesViewController , I went all over the framework docs and didn't find answer for my problem which is:
Can I use (NSFetchedResultsController) with this framework?
If so how can I use the (NSFetchedResultsController) in the JSQMessages CollectionView DataSource in the right way and return all my Messages from my core data?. I know how to use (NSFetchedResultsController) but not so sure how to use it with the CollectionView and with this framework.
It seem like the CollectionView data source/delegate methods only work with NSmutableArray and the app crashes when I do staff with (NSFetchedResultsController).
For example:
return [_fetchedResultsController.fetchedObjects objectAtIndex:indexPath.item];
VS:
return messages[indexPath.item];
When I use the _fetchedResultsController.fetchedObjects my app crashes.
So after thinking what to do I said ok what if I will convert my .fetchedObjects (NSarray) to be my (NSmutablearray) of the messages and then I got stack I just don't know how to do this the right way I need help.
All I need is just a way to return all my messages from my SQlite database to my app.
I also have looked at Parse example https://github.com/relatedcode/RealtimeChat , here but I want my own Code without having to pay to Parse.com and to be able to use Core-Data.
When I call this : JSQMessage I need some how to tell it to return all my objects in my fetch result controller *.fetechedobjects*.

How to filter & fetch records with MagicalRecord?

I've two classes like this,
#class Songs;
#interface Album : NSManagedObject
#property (nonatomic, retain) NSNumber * albumID;
#property (nonatomic, retain) NSString * name;
#property (nonatomic, retain) NSSet *songs;
#end
#interface Album (CoreDataGeneratedAccessors)
- (void)addSongsObject:(Songs *)value;
- (void)removeSongsObject:(Songs *)value;
- (void)addSongs:(NSSet *)values;
- (void)removeSongs:(NSSet *)values;
#end
#class Album;
#interface Songs : NSManagedObject
#property (nonatomic, retain) NSString * name;
#property (nonatomic, retain) NSNumber * length;
#property (nonatomic, retain) Album *owner;
#end
Suppose, I've 10 albums created and each album have some random (positive) number of songs. Now I want to find & fetch top 5 albums which has the maximum number of songs.
How do I do that with MagicalRecords?
Currently, I'm doing it like this,
NSLog(#"%#",[Album MR_findAllSortedBy:#"albumID" ascending:YES withPredicate:[NSPredicate predicateWithFormat:#"#max.#count.songs"]]);
//NSLog(#"%#",[Album MR_findAllSortedBy:#"albumID" ascending:YES]); //works fine
but its crashes with following message:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format
string "#max.#count.songs"'
Is my predicate string invalid? If yes, what is the correct way to achieve this.
According to this post, you can not sort by count on fetch. You need to fetch all items and than sort and trim them:
NSArray* array = [Album MR_findAll];
array = [array sortedArrayUsingDescriptors:#[ [NSSortDescriptor sortDescriptorWithKey:#"songs.#count" ascending:NO] ] ];
array = [array subarrayWithRange:NSMakeRange(0, MIN( array.count, 5) )];

coredata NSFetchRequest one to many relationship Relationship fault on managed object

I have a coredata project with the following entities:
I'm trying to get the list of the content base on the category:
here is my coredata clasess .h:
#interface Content : NSManagedObject
#property (nonatomic, retain) NSString * contenido;
#property (nonatomic, retain) NSNumber * index;
#property (nonatomic, retain) NSString * titulo;
#property (nonatomic, retain) NSNumber * uploadCloudKit;
#property (nonatomic, retain) Categories *category;
---
#class Content;
#interface Categories : NSManagedObject
#property (nonatomic, retain) NSString * categoryName;
#property (nonatomic, retain) NSSet *content;
#end
NSEntityDescription *categoryDescription = [ NSEntityDescription entityForName:#"Categories" inManagedObjectContext:moc];
NSFetchRequest *categoRequest = [NSFetchRequest new];
categoRequest.entity = categoryDescription;
NSPredicate *categoPredicate = [NSPredicate predicateWithFormat:#"categoryName like %#", category];
categoRequest.predicate = categoPredicate;
NSArray *results = [moc executeFetchRequest:categoRequest error:&error];
but when I try to access the content on the result for the category I get:
po [results valueForKey:#"content"]
<__NSArrayI 0x6080000243a0>(
Relationship 'content' fault on managed object (0x6080000a2220) <Categories: 0x6080000a2220> (entity: Categories; id: 0x40002b <x-coredata://FDBA3FB2-F1F8-498E-9071-3A5D1ABE66F0/Categories/p1> ; data: {
categoryName = movies;
content = "<relationship fault: 0x610000030fa0 'content'>";
})
)
Any of you knows how can I get the content items of the result?
I'll really appreciate your help
It's a normal behaviour for CoreData. You should read Apple Documentation. There you can read about fault objects for CoreData. In two words - fault means that CoreData has this object but know (for some reason CoreData won't print you all fields of the object).
In order to see all vields you should do this:
[categoRequest setReturnsObjectsAsFaults:NO];
But I recomend you to do this only for debug, because CoreData smarter and know what to do with memory managment)

NSDictionary custom object store and retrieve

Trying to store value in NSDictionary and retrieve it
Objects
#import <Foundation/Foundation.h>
#class ATTTEstOBJ;
#interface ATTTEst : NSObject
#property (nonatomic, retain) NSString *string1;
#property (nonatomic, retain) NSString *string2;
#property (nonatomic, retain) ATTTEstOBJ *obj1;
#end
#interface ATTTEstOBJ : NSObject
#property (nonatomic, retain) NSString *string3;
#property (nonatomic, retain) NSString *string4;
#property (nonatomic, retain) NSString *array1;
#end
I know it needs to be encoded properly to save and retrieve values.but In this case it is a composite object and I have no idea, how to deal it with.
- (void) encodeWithCoder: (NSCoder *)coder
So TLDR , How to save the composite value into dictionary and retrieve it back
I want to store ATTTest into a dictionary and retrieve it back.
EDIT : Detailed explanation
ATTTEst *test=[[ATTTEst alloc]init];
test.string1=#"a";
test.string2=#"b";
ATTTEstOBJ *obj=[[ATTTEstOBJ alloc]init];
obj.string3=#"c";
obj.string4=#"d";
test.obj1=obj;
NSMutableDictionary *dict=[[NSMutableDictionary alloc]initWithCapacity:3];
[dict setObject:test forKey:#"test"];
NSLog(#"%#",dict);
ATTTEst *tester=[dict objectForKey:test];
NSLog(#"%#",tester.obj1.string3);
IT shows null.as output I want to get the value as c for tester.obj1.string3
ATTTEst *tester=[dict objectForKey:test];
should be
ATTTEst *tester=[dict objectForKey:#"test"];
You have used the object test (instead of the string #"test") as key when retrieving the object. I don't think that
was intentionally.
In order to store them into NSDictionary, you don't need to encode them.
Just do:
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:, attestObject,#"attestObject", attest2Object,#"atttest2" nil];
Where attestObject and attest2Object are the objects you want to store, and strings are their keys.
This has nothing to do with encoding...

Get related / associated entities from NSSet - CoreData

I have 2 autogenerated entities :
#interface ContactEntity : Entity
#property (nonatomic, retain) NSString *caption;
#property (nonatomic, retain) NSString *image;
#property (nonatomic, retain) NSString *name;
#property (nonatomic, retain) NSString *text;
#property (nonatomic, retain) NSSet *pointLink;
#end
#interface PointEntity : Entity
#property (nonatomic, retain) NSNumber *latitude;
#property (nonatomic, retain) NSNumber *longitude;
#property (nonatomic, retain) NSSet *entityLink;
#property (nonatomic, retain) EntityEntity *entityTypeLink;
#end
They are linked between each other as ManyToMany, i.e. one contact has many points, one point has many contacts inside.
Then a i get first entity :
ContactModel *contact = [[[ContactModel alloc] init] autorelease];
// this is FetchRequest, returns array of all entities
self.items = [contact list:contact];
// i get only one, all is OK here, this entity has related PointEntity in DB
ContactEntity *contactEntity = [self.items objectAtIndex:self.selection];
And when i try to get related PointEntity using NSSet in selected ContactEntity i always get NULL or empty array. Neither of this works :
NSArray *points = [contactEntity.pointLink allObjects];
PointEntity *pointEntity = [contactEntity.pointLink anyObject];
NSInteger x1 = [points count]; // always 0
id x2 = pointEntity.latitude; // always 0
for (PointEntity *x in contactEntity.pointLink) // isn't enumerated because count = 0
{
id x3 = x.latitude;
}
Any thoughts are appreciated. Did i miss something, maybe i need to use NSPredicate to select entities from PointEntity that are related to ContactEntity?
Thanks.
P.S. My question is similar to this but that suggestion does not work for me, i cannot get loaded associated entities using NSSet of main entity :(
CoreData: many-to-many relationship
Answer is found ... i tried to use property of the autogenerated entities when created new records in CoreData, in the meantime the correct way is to use generated methods like - addPointLinkObject, addEntityLinkObject, etc
Example, i have 3 tables :
Contacts (one person may have many locations)
<< - >>
Points (one location can contain many people)
<< - >
EntityTypes (just a type of a location, in this case type is CONTACT)
One of the entities autogenerated by xCode :
#interface PointEntity : Entity
#property (nonatomic, retain) NSNumber *latitude;
#property (nonatomic, retain) NSNumber *longitude;
#property (nonatomic, retain) NSSet *entityLink; // reference to Contacts table (ManyToMany)
#property (nonatomic, retain) EntityEntity *entityTypeLink; // reference to EntityType table (OneToMany)
#end
#interface PointEntity (CoreDataGeneratedAccessors)
- (void)addEntityLinkObject:(ContactEntity *)value;
- (void)removeEntityLinkObject:(ContactEntity *)value;
- (void)addEntityLink:(NSSet *)values;
- (void)removeEntityLink:(NSSet *)values;
#end
I tried to do the following :
// create 3 new instances - one for each entity
ContactEntity *contactEntity = [model create:model];
PointEntity *pointEntity = [point create:point];
EntityModel *entity = [[[EntityModel alloc] init] autorelease];
entity.name = model.table;
EntityEntity *entityEntity = [[entity list:entity] objectAtIndex:0];
// then i tried to use entity's properties directly to bind entities
// it works, but it works only on DB level when we add new records, but somehow something was missed and thus such selection did not work later - [pointEntity allObjects]
//pointEntity.entityTypeLink = entityEntity; // WRONG !!!
//pointEntity.entityLink = contactEntity.pointLink;
//contactEntity.pointLink = pointEntity.entityLink;
// then i replaced 3 lines above with these ones
[pointEntity addEntityLinkObject:contactEntity]; // CORRECT !!!
[contactEntity addPointLinkObject:pointEntity];
[entityEntity addPointLinkObject:pointEntity];
[context save]; // save changes made with entities in current CoreData context
// now [pointEntity allObjects] and [pointEntity anyObject] work as expected
Useful links -
Coredata and Generated subclass for NSManagedObject with relations
https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CoreData/Articles/cdAccessorMethods.html#//apple_ref/doc/uid/TP40002154

Resources