I have a basic Core Data model which look like this :
I auto-generated data model files and it's give me something like that :
BSStudent.h
//
// BSStudent.h
//
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#class BSFormation;
#interface BSStudent : NSManagedObject
#property (nonatomic, retain) NSString * firstname;
#property (nonatomic, retain) NSString * lastname;
#property (nonatomic, retain) NSDate * birthdate;
#property (nonatomic, retain) id thumbnail;
#property (nonatomic, retain) NSSet *formations;
#end
#interface BSStudent (CoreDataGeneratedAccessors)
- (void)addFormationsObject:(BSFormation *)value;
- (void)removeFormationsObject:(BSFormation *)value;
- (void)addFormations:(NSSet *)values;
- (void)removeFormations:(NSSet *)values;
#end
BSStudent.m
//
// BSStudent.m
//
#import "BSStudent.h"
#import "BSFormation.h"
#implementation BSStudent
#dynamic firstname;
#dynamic lastname;
#dynamic birthdate;
#dynamic thumbnail;
#dynamic formations;
#end
I tried to simply save a BSStudent object by doing the following :
BSStudent *newStudent = (BSStudent *)[NSEntityDescription entityForName:kBSStudent inManagedObjectContext:self.managedObjectContext];
newStudent.firstname = firstname;
newStudent.lastname = lastname;
newStudent.birthdate = birthdate;
newStudent.thumbnail = thumbnail;
NSError *error;
if (![self.managedObjectContext save:&error]) {
NSLog(#"Error: %#", [error localizedDescription]);
}
But my app always crash with error : [NSEntityDescription setFirstname:]: unrecognized selector sent to instance 0x1f021e00
Someone figuring out what's happening here ?
One possible explanation is that you are using the wrong string in:
BSStudent *newStudent = (BSStudent *)[NSEntityDescription entityForName:kBSStudent inManagedObjectContext:self.managedObjectContext];
Try and check what newStudent actually is:
BSStudent *newStudent = (BSStudent *)[NSEntityDescription entityForName:kBSStudent inManagedObjectContext:self.managedObjectContext];
NSLog(#"New Student: %#", [newStudent description]);
newStudent.firstname = firstname;
maybe it will clarify things...
Related
i class
Collections *tempLocalCollection = [[Collections alloc] init];
the problem is that when I try to promote an attribute in sequent way
tempLocalCollection.id = [f numberFromString:[NSString stringWithFormat:#"%#", #"0"]];
tempLocalCollection.action = #"client_insert";
I should be in error
-[Collections setId:]: unrecognized selector sent to instance 0xff8afb0 2015-09-16 10:25:14.235 App[1042:128375] ***
Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: '-[Collections setId:]:
unrecognized selector sent to instance 0xff8afb0'
where am I wrong ?
Collections.h
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#class Items;
#interface Collections : NSManagedObject
#property (nonatomic, retain) NSNumber * datetime_creation;
#property (nonatomic, retain) NSNumber * datetime_last_update_client;
#property (nonatomic, retain) NSNumber * datetime_last_update_server;
#property (nonatomic, retain) NSString * local_delete;
#property (nonatomic, retain) NSNumber * id;
#property (nonatomic, retain) NSString * action;
#property (nonatomic, retain) NSString * label;
#property (nonatomic, retain) NSString * labelServer;
#property (nonatomic, retain) NSNumber * ref_user;
#property (nonatomic, retain) NSNumber * sorting;
#property (nonatomic, retain) NSNumber * system;
#property (nonatomic, retain) NSSet *collection_item;
#end
#interface Collections (CoreDataGeneratedAccessors)
#end
Collections.m
#import "Collections.h"
#import "Items.h"
#implementation Collections
#dynamic datetime_creation;
#dynamic datetime_last_update_client;
#dynamic datetime_last_update_server;
#dynamic local_delete;
#dynamic action;
#dynamic id;
#dynamic label;
#dynamic labelServer;
#dynamic ref_user;
#dynamic sorting;
#dynamic system;
#dynamic collection_item;
#end
This is the method that uses the class and where it goes wrong.
I think the context is the same right?
-(Collections *) upgrateListCollection:(NSDictionary *) coll{
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
f.numberStyle = NSNumberFormatterDecimalStyle;
NSNumber *id = [f numberFromString:[NSString stringWithFormat:#"%#", coll[#"id"]]];
Collections *tempLocalCollection = [[Collections alloc] init];
NSArray *tmp = [Collections MR_findByAttribute:#"id" withValue:id];
if(tmp.count != 0){
tempLocalCollection = tmp[0];
}
if(!tempLocalCollection.isAccessibilityElement){
tempLocalCollection.id = [f numberFromString:[NSString stringWithFormat:#"%#", #"0"]];
tempLocalCollection.action = #"client_insert";
}else{
if([tempLocalCollection.local_delete isEqual: #"1"]){
tempLocalCollection.action = #"client_delete";
}else{
if([tempLocalCollection.label isEqual:coll[#"label"]]){
if(tempLocalCollection.datetime_last_update_client < coll[#"datetime_last_update_server"]){
tempLocalCollection.action = #"client_update";
}else{
tempLocalCollection.action = #"server_update";
}
}
}
}
if(tempLocalCollection != nil){
tempLocalCollection.labelServer = coll[#"label"];
tempLocalCollection.datetime_last_update_server = coll[#"datetime_last_update_server"];
tempLocalCollection.datetime_creation = coll[#"creation_utc_server"];
}
return tempLocalCollection;
}
NSManagedObject subclass (Collections) properties are dynamic, their setter and getter are generated at runtime
Thus when you create object of Collections using alloc/init in that case the dynamic properties are not created hence you get the exception unrecognized selector sent to instance
The right way of creating a NSManagedObject is
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Collections" inManagedObjectContext:myMOC];
Collections *collection = (Collections *)[[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:myMOC];
And if you want to create a temporary object of Collections then pass nil as manage object context
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Collections" inManagedObjectContext:myMOC];
Collections *tempObj = (Collections *)[[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:nil];
That is a managed object and needs to be created in its managing context.
I'm running into some trouble with a PFObject subclass. I've gone thru all of the proper setup (registering the subclass in the delegate, setting the class name, etc). But for some reason I can't get the object to load without crashing it in the view that it's supposed to be loading in.
Passing the Object
if ([segue.identifier isEqualToString:#"toPostView"])
{
pbPostViewController *postView = [pbPostViewController new];
postView = (pbPostViewController *)segue.destinationViewController;
[postView setPostToLoad:_selectedPost];
}
Receiving View.h
// Copyright (c) 2015 Chris Culos. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <Parse/Parse.h>
#import "PALongTextView.h"
#import "pbPost.h"
#interface pbPostViewController : UIViewController
#property (strong, nonatomic) pbPost *postToLoad;
Receiving View.m
#import "pbPost.h"
#interface pbPostViewController ()
#end
#implementation pbPostViewController
- (void)viewDidLoad {
pbPost *post = [pbPost postWithObject:_objectToLoad];
NSLog(#"post: %#", post);
// _timeStampLabel.text = post.postTimeStamp;
_userNameLabel.text = [post.postOwner valueForKey:#"username"];
_profileImage.image = [post.postOwner valueForKey:#"profileImage"];
_postDescriptionView.text = post.postDescriptionString;
_bookmarkCounterLabel.text= [NSString stringWithFormat:#"%li bookmarks", post.postBookmarkedArray.count];
_postContentView.text = #"POST CONTENT PAGE 123 456 ETC ETC ETC";
[super viewDidLoad];
//
pbPost.h
#interface pbPost : PFObject <PFSubclassing>
{
}
#property (nonatomic, retain) NSDate *postTimeStamp;
#property (nonatomic, retain) NSString *postDescriptionString;
#property (nonatomic, retain) NSString *postContentString;
#property (nonatomic, retain) NSString *postBookmarkString;
#property (nonatomic, retain) NSString *postPageCounterString;
#property (nonatomic, retain) NSArray *postBookmarkedArray;
#property (nonatomic, retain) PFFile *postOwnerProfileImage;
#property (nonatomic, retain) NSNumber *postFontSize, *totalPages;
#property (nonatomic, retain) PFUser *postOwner;
+ (pbPost *) postWithObject: (PFObject *)object;
pbPost.m
#implementation pbPost
#dynamic postContentString, postBookmarkString, postDescriptionString, postPageCounterString, postTimeStamp, commentTableView, commentButton, bookMarkButton, postOwnerProfileImage, optionsButton, postFontSize, totalPages, postBookmarkedArray, postOwner;
+ (void)load
{
[self registerSubclass];
}
+ (NSString *)parseClassName
{
return #"userPosts";
}
+ (pbPost *) postWithObject: (PFObject *)object
{
// NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
// [dateFormat setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
// [dateFormat setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"UTC"]];
pbPost *post = [pbPost postWithObject:object];
[post fetchInBackgroundWithBlock:^(PFObject *object, NSError *error) {
if (!error) {
post.postTimeStamp = [object valueForKey:#"createdAt"];
post.postDescriptionString = [object valueForKey:#"titleSummary"];
post.postFontSize = [object valueForKey:#"fontSize"];
post.postContentString = [object valueForKey:#"postContent"];
post.totalPages = [object valueForKey:#"numPages"];
post.postBookmarkedArray = [object valueForKey:#"bookmarkedBy"];
post.postOwner = [object valueForKey:#"postOwner"];
post.postOwnerProfileImage = [post.postOwner valueForKey:#"profileImage"];
NSLog(#"LOAD THE THING!: %#", post);
}
else
{
NSLog(#"Error Loading Post: %#", error);
}
}];
return post;
}
Under this circumstance; I'm getting an EXC_BAD_ACCESS at + (pbPost *)postWithObject:(PFObject *)object in the implementation file.
I feel like I'm missing something very simple here; what can it be? Thanks in advance for your help again everyone! This has stumped me for a little while and I need to get some outside help.
Since you're passing the pbPost object, you don't need to call the + (pbPost *)postWithObject:(PFObject *)object at all. To create a new instance of your PFObject subclass, you can just call:
pbPost *post = [pbPost object];
I've subclassed the PFObject with the following Class (dynamic properties, and +load & parseClassName Methods in .m file)
#interface DAOpponents : PFObject <PFSubclassing>
#property (nonatomic, strong) PFObject* fromUser;
#property (nonatomic, strong) PFObject* toUser;
#property (nonatomic) BOOL isVisible;
#property (nonatomic) BOOL isPersistent;
+ (NSString *)parseClassName;
#end
In a Unit Test I try to create a Sample DAOpponents-Object:
DAOpponents* follow = [DAOpponents object];
follow.fromUser = user1; // caught "NSInvalidArgumentException", "PFObject values may not have class: PFUser"
follow.toUser = user2;
[follow save];
If I do the same without a subclassed Version of the opponents there's no Exception
PFObject* follow = [[PFObject alloc] initWithClassName:#"DAOpponents"];
[follow setObject:user1 forKey:#"fromUser"]; // no exception!!!
[follow setObject:user1 forKey:#"toUser"];
Why does a subclassed PFObject can not point to a PFUser object?
Any help appreciated! Thanks a lot!
I was able to get around this problem by first subclassing PFUser, then using my subclass called User in my other PFObject subclasses.
My PFUser subclass, User.h:
#import <Parse/Parse.h>
#class Person;
#class Parish;
#interface User : PFUser<PFSubclassing>
//+ (NSString *)parseClassName;
// Return the current user
+ (User *)currentUser;
#property (retain) NSNumber *acceptedAgreements;
#property (retain) NSNumber *isAdmin;
#property (retain) Person *person;
#end
and my User.m:
#import "User.h"
#import <Parse/PFObject+Subclass.h>
#import "Person.h"
#implementation User
#dynamic acceptedAgreements;
#dynamic isAdmin;
#dynamic person;
//+ (NSString *)parseClassName {
// return #"User";
//}
// Return the current user
+ (User *)currentUser {
return (User *)[PFUser currentUser];
}
#end
I have entity:
#class CDCustomItem;
#interface CDCustomItem : NSManagedObject
#property (nonatomic, retain) CDCustomImage *image;
#end
and CDCustomImage entity:
#class CDCustomImage;
#interface CDCustomImage : NSManagedObject
#property (nonatomic, retain) NSString * url;
#property (nonatomic, retain) CDCustomItem *itemParent;
#end
CDCustomImage.image and CDCustomImage.itemParent have types "To One"
After I insert image to CDCustomItem it shows me in NSLog:
image = "0x79e59df0 <x-coredata:///CDCustomImage/t765B46F3-87B1-4C09-A108-6584F4E58DDB214>";
But when I'm trying to NSLog(#"%#", CDCustomItem.image) it returns null
Why its happened? How to fix it? Please help
Edit 1:
All operations are in one thread
Edit 2:
Here is code how inserting image to CDCustomItem:
CDCustomImage *image = [self insertImage:[jsonDict objectForKey:#"image"]];
item.image = image;
- (CDCustomImage *)insertImage:(NSDictionary *)jsonDict {
CDCustomImage *entity = [self insertEntityWithName:[CDCustomImage description]];
[self fillFieldsForImage:entity dict:jsonDict];
return entity;
}
- (void)fillFieldsForImage:(CDCustomImage *)entity dict:(NSDictionary *)jsonDict {
entity.url = [jsonDict valueForKey:#"url"];
}
I am attempting to use this JSONModel library in an app I'm building. I've been following this article, but for some reason I keep getting (null) when attempting to parse the json string. I was told that it is because I'm not creating a json instance; but it seems to me I am. Below is the code, can anyone see what I'm missing? I'm attempting to use this web service, with these inputs:
emailAddress: wufpakjack#yahoo.com;
password: test;
companyId: 2579;
scheduleDate: 20140415.
myShiftModel.h
#import "JSONModel.h"
#interface myShiftModel : JSONModel
#property (assign, nonatomic) NSString *shiftName;
#property (assign, nonatomic) NSString *shiftStartTime;
#property (assign, nonatomic) NSString *shiftPosition;
#end
dailyViewModel.h
#import "JSONModel.h"
#import "myShiftModel.h"
#protocol dailyViewModel #end
#interface dailyViewModel : JSONModel
#property (assign, nonatomic) int numAvailableXChanges;
#property (strong, nonatomic) NSString *todaysForecast;
#property (assign, nonatomic) int todaysTemperature;
#property (strong, nonatomic) myShiftModel *workShift;
#end
dailyFeed.h
#import "JSONModel.h"
#import "dailyViewModel.h"
#interface dailyFeed : JSONModel
#property (strong, nonatomic) NSArray <dailyViewModel> *workShifts;
#end
mainViewController.m
#import "mainViewController.h"
#import "JSONModelLib.h"
#import "JSONModel+networking.h"
#import "dailyFeed.h"
#interface mainViewController () {
dailyFeed *feed;
}
#end
#implementation mainViewController
- (void)viewDidAppear:(BOOL)animated {
NSString *email = [[NSString alloc]initWithFormat:#"wufpakjack#yahoo.com"];
NSString *pass = [[NSString alloc]initWithFormat:#"test"];
NSString *compID = [[NSString alloc]initWithFormat:#"2579"];
NSString *date = [[NSString alloc]initWithFormat:#"20140415"];
NSString *urlString = [NSString stringWithFormat:#"http://qa.shiftzen.com/ws/schedutils.asmx/GetDailyView?emailAddress=%#&password=%#&companyId=%#&scheduleDate=%#", email,pass,compID,date];
NSLog(#"%#", urlString);
[JSONHTTPClient getJSONFromURLWithString:urlString
completion:^(NSDictionary *json, JSONModelError *err) {
NSError* error = nil;
feed = [[dailyFeed alloc] initWithDictionary:json error:&error];
NSLog(#"shifts: %#", feed.workShifts);
}];
}
#end
Any guidance would be greatly appreciated.
Warmest regards,
DB