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*.
Related
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
I am having two classes or objects: User and Medicine. Here is my User class:
#interface User : NSManagedObject
#property (nonatomic, retain) NSString * name;
#property (nonatomic, retain) NSSet *medicine;
#end
#interface User (CoreDataGeneratedAccessors)
- (void)addMedicineObject:(Medicine *)value;
- (void)removeMedicineObject:(Medicine *)value;
- (void)addMedicine:(NSSet *)values;
- (void)removeMedicine:(NSSet *)values;
#end
and then the Medicine class
#interface Medicine : NSManagedObject
#property (nonatomic, retain) NSString * medName;
#property (nonatomic, retain) NSString * medType;
#property (nonatomic, retain) Dose *dose;
#property (nonatomic, retain) User *user;
#end
As my interfaces clearly show that user may have multiple medicines. (I am from database background thats why I am interpreting it like this).
When I add new object in User, it is easily done, but when I try to add new Medicine for existing object of user, I feel that my Xcode has a deep wish to shoot me at that time (vice versa).
Now here is the code that describes what I am doing:
Medicine *object = [[self fetchedResultsController] objectAtIndexPath:indexPath];
User *user = [NSEntityDescription insertNewObjectForEntityForName:#"User" inManagedObjectContext:self.managedObjectContext];
if(![self checkUser])
{
object.user = user;
[user setName:self.userName];
NSLog(#"%# %#",object, user);
self.detailViewController.detailItem = object;
}
else
{
Medicine *medicine = [NSEntityDescription insertNewObjectForEntityForName:#"Medicine" inManagedObjectContext:self.managedObjectContext];
user = [self getUser:self.userName];
medicine.medName = object.medName;
medicine.medType = object.medType;
[medicine setUser:user];
self.detailViewController.detailItem = medicine;
}
I am having a simple logic: if name entered by user in text field, already exist in DB, then return the User object. Then just add another Medicine record for the same User. Other wise add new User and a Medicine object as well.
but I get error at:
[medicine setUser:user];
I also tried this one: (as I got it in another question like mine)
[user addMedicineObject:medicine];
Now I think that I have to override addMedicineObject method or something else.
Oh I forgot the error. I get this error: (the real villain)
[__NSArrayM managedObjectContext]: unrecognized selector sent to instance 0x8136bf0
Now any suggestion?
It is because you trying to mutate NSSet object. You need to create a mutable copy before you edit it.
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...
This question already has an answer here:
why is my code outputting *nil description*
(1 answer)
Closed 10 years ago.
Here is my custom class:
ClassA.h
#interface ClassA : NSObject<RKRequestDelegate>{
NSString *uri;
NSString *folderUri;
NSInteger idFolder;
NSString *kind;
bool isMine;
CustomUser *owner;
NSMutableArray *usersAdministrators;
NSMutableArray *usersContributors;
NSMutableArray *usersReaders;
NSString *visibility;
NSString *name;
NSString *description;
NSMutableArray *comments;
}
#property (nonatomic,copy) NSString *uri;
#property (nonatomic,copy) NSString *folderUri;
#property (nonatomic,assign) NSInteger idFolder;
#property (nonatomic,copy) NSString *kind;
#property (nonatomic,assign) bool isMine;
#property (retain) DMIUser *owner;
#property (nonatomic,copy) NSMutableArray *usersAdministrators;
#property (nonatomic,copy) NSMutableArray *usersContributors;
#property (nonatomic,copy) NSMutableArray *usersReaders;
#property (nonatomic,copy) NSString *visibility;
#property (nonatomic,copy) NSString *name;
#property (nonatomic,copy) NSString *description;
#property (nonatomic,copy) NSMutableArray *comments;
#end
ClassA.m
#implementation ClassA
#synthesize uri,folderUri,idFolder,kind,isMine,owner,usersAdministrators,usersContributors,usersReaders,visibility,name,description,comments;
-(NSString*)description {
return #"ClassA";
}
#end
Quite simple. But when i try to create new instance of this, like this:
datas = [NSMutableArray array]; // Tried with [[NSMutableArray alloc] init] => same thing
ClassA *classA = [[ClassA alloc] init];
[datas addObject:classA];
NSLog(#"classA = %#",classA);
NSLog(#"datas = %#",datas);
First NSLog returns "ClassA".
Second NSLog returns "datas = ()"
What's wrong here? I always created class like this and i've never had problem like this.
Thanks!
Ok guyzzz i found the problem. It's my attribute:
NSString *description;
Seems that iOs doesn't love that. It conflict with the -description method in NSObject...
After that, i found a similar question here:
Why can't I use "description" as an attribute name for a Core Data entity?
Cheers
if your want to return some value implement method description in the ClassA
- (NSString *)description {
return #"ClassA";
}
You've got everything you need. Are you sure the variable you're assigning to isn't a weak one? All delegate properties are weak, therefore not retaining the object. My guess is that you're doing something like this
someObject.delegate = [[ClassA alloc] init];
NSLog(#"%#", someObject.delegate);
Because the delegate property is weak it doesn't hold onto the variable.
Edit:
This whole answer assumes you are using ARC. If not, disregard.
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