CoreData attribute access issue - core-data

Today I have added an attribute for the model, but I can't access the attribute:
The model schema:
#implementation NewsContent
#dynamic content;
#dynamic contentId;
#dynamic mediaUrl;
#dynamic peakNum;
#dynamic news;
#end
I just called the NSLog(#"%#", self.news.content.peakNum);, but I got an error:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NewsContent peakNum]: unrecognized selector sent to instance 0x8359490'
*** First throw call stack:
(0x1e72052 0x3a06d0a 0x1e73ced 0x1dd8f00 0x1dd8ce2 0x283c8 0x1ef91 0x93336a 0xa65a5d8 0x934956 0x1dd851d 0x1dd8437 0x1e0349a 0x2274aff 0x1dd90c9 0x1dd8ce2 0x1dd851d 0x1dd8437 0x2e14ae3 0x2e15115 0x1e4697f 0x1da9b73 0x1da9454 0x1da8db4 0x1da8ccb 0x2004879 0x200493e 0x77ca9b 0x34c0 0x2ce5)
terminate called throwing an exceptionCurrent language: auto; currently objective-c:

Did you also add peakNum as a property in the #interface declaration? Did you check if self.news.content refers to a valid object? Are you sure that your error comes from the NSLog line of code?

The problem has been solved.
I have add the new model version, but add the attribute to the old version, so.....

Related

Unable to instantiate NSFetchedResultController with generic type AnyObject in Swift 3

I'm experimenting with CoreData in Swift 3 and have come up against a very bizarre circular compiler error in Xcode 8 beta.
NSFetchedResultsController needs a generic type parameter and AnyObject has worked fine up until now. The compiler throws the error:
Type 'AnyObject' does not conform to protocol 'NSFetchRequestObject'
To make me extra confused, if you delete the type parameter, XCode then says:
Reference to generic type NSFetchedResultsController requires argument in `<...>`
and helpfully suggests a fix using <AnyObject>....and the cycle repeats.
This looks very much like a bug. Any ideas before I report it?
If you take a look into NSFetchedResultsController, you can clearly see that it has a parameter with name ResultType which conforms to NSFetchRequestResult. So you should pass a type which conforms to NSFetchRequestResult.
So if you take a look into NSFetchRequestResult, you can see that it conforms to NSObjectProtocol. Also NSDictionary, NSManagedObject and NSManagedObjectID conforms to NSFetchRequestResult.
public protocol NSFetchRequestResult : NSObjectProtocol {
}
extension NSDictionary : NSFetchRequestResult {
}
extension NSManagedObject : NSFetchRequestResult {
}
extension NSManagedObjectID : NSFetchRequestResult {
}
So it clear that you should pass a type from any of these three NSDictionary or NSManagedObject or NSManagedObjectID.
Create your instance of NSFetchedResultsController like this.
let resultsController : NSFetchedResultsController<NSManagedObject>!
or like this
let resultsController : NSFetchedResultsController<NSManagedObjectID>!
or like this
let resultsController : NSFetchedResultsController<NSDictionary>!
Any entity in your Core Data model maps as a subclass of NSManagedObject generated in your code so they all can be used to replace AnyObject, they all conform indirectly to NSFetchRequestResult protocol. You should see which entity/class is being fetch by your FetchRequest connected to this FetchedResultsController and that's the type you should use there.

KVO notification with Core Data in Swift

When I generate an NSManagedObject subclass with swift, the property types are all #NSManaged, meaning I can't observe them. This is a problem when using bindings in a Cocoa application because updating the property frequently requires other properties to be 'updated'.
For example, if I add this method to my NSManagedObject subclass:
dynamic var ratePerPoint: Double {
guard pointsPerMonth > 0 else { return 0 }
return monthlyRate / Double(pointsPerMonth)
}
Then it's important that whenever I update the pointsPerMonth variable, which is part of the core data object, that I send a didChangeValueForKey("ratePerPoint") message.
If I don't, then the UI bindings don't update properly.
If ratePerPoint is a calculated property you have to implement keyPathsForValuesAffectingRatePerPoint in your NSManagedObject subclass.
+ (NSSet *)keyPathsForValuesAffectingRatePerPoint {
return [NSSet setWithObjects:#"monthlyRate", #"pointsPerMonth", nil];
}
Documentation: Registering Dependent Keys

Using RestKit to map a a naked array of URLs to Core Data Entities

I'm getting back some URLs in a naked JSON array from a web service like so:
[
"https://server1.com",
"https://server2.com"
]
I'd like to map these to separate Core Data Entities, but am getting an assertion failure:
I restkit.network:RKObjectRequestOperation.m:180 GET 'https://server-test.com/Client/Endpoints'
*** Assertion failure in NSDictionary *RKEntityIdentificationAttributesForEntityMappingWithRepresentation(RKEntityMapping *__strong, NSDictionary *__strong)(), /Users/jonukas/MyApp/Pods/RestKit/Code/CoreData/RKManagedObjectMappingOperationDataSource.m:83
An uncaught exception was raised
Expected a dictionary representation
FWIW, setting a breakpoint on RKManagedObjectMappingOperationDataSource.m:83 shows that the representation that should be a NSDictionary is actually an RKMappingSourceObject.
Here is the mapping I made:
RKEntityMapping *mapping = [RKEntityMapping mappingForEntityForName:#"MyURL"
inManagedObjectStore:self.manager.managedObjectStore];
[mapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:nil
toKeyPath:#"url"]];
RKResponseDescriptor *descriptor = [RKResponseDescriptor responseDescriptorWithMapping:mapping
method:RKRequestMethodGET
pathPattern:#"Client/Endpoints"
keyPath:nil
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[self.manager addResponseDescriptor:descriptor];
My Entity has just one attribute (url) of type transformable. Here is the NSManagedObject subclass:
#interface MyURL : NSManagedObject
#property (nonatomic, retain) id url;
#end
Am I doing the mapping incorrectly or is there something wrong with my entity description/object model (forgive me, I'm just starting out with Core Data)?
UPDATE: I tried setting an identification attribute, but it didn't seem to help:
[mapping setIdentificationAttributes:#[#"url"]];
Turning on trace logging for RestKit/ObjectMapping results in:
D restkit.object_mapping:RKMapperOperation.m:377 Executing mapping operation for representation: (
"https://server1.com",
"https://server2.com"
)
and targetObject: (null)
T restkit.object_mapping:RKMapperOperation.m:320 Examining keyPath '<null>' for mappable content...
D restkit.object_mapping:RKMapperOperation.m:297 Found mappable collection at keyPath '<null>': (
"https://server1.com",
"https://server2.com"
)
*** Assertion failure in NSDictionary *RKEntityIdentificationAttributesForEntityMappingWithRepresentation(RKEntityMapping *__strong, NSDictionary *__strong)(), /Users/jonukas/MyApp/Pods/RestKit/Code/CoreData/RKManagedObjectMappingOperationDataSource.m:83
…
I'm guessing the (null) targetObject might be my problem.
UPDATE 2: RestKit 0.21.0 fixed the issue.
Change your url attribute in your Core Data model to be String type. By setting it to transformable RestKit can't properly interpret what data type is should be so it is opting for dictionary and getting rather confused.
I assume you set it to transformable because you want an NSURL. RestKit can't do that for you so you should use a transient attribute to achieve that gaol.

Passing A Delegate In prepareForSegue Method

I am having a problem passing an object from a TableView to a ViewController in an IOS app. I am using storyboard and have elected ARC and passing the delegate in my "prepareForSegue" method.
Here is my code in my TableView which segues via a push to another ViewController:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
NextViewController *vc = (NextViewController *)[segue destinationViewController];
vc.managedObjectContext = managedObjectContext;
if ([[segue identifier] isEqualToString:#"EditCategory"])
{
NSInteger selectedIndex = [[self.tableView indexPathForSelectedRow] row];
// I get a red warning which states "Cast of 'NSInteger' (aka 'int') to 'Entity' is disallowed with ARC" on this line:
[vc setEntity:(Entity *)selectedIndex];
}
}
Does anybody have any suggestions for how I can pass my object from the TableView to the ViewController? I am new to programming and have tried various expressions but nothing seems to work.
The error you're getting has to do with types.
The class NextViewController apparently has a method called -setEntity: that takes an object of type Entity *. The error is because you're trying to give -setEntity: an argument of the wrong type. You're trying to give it an NSInteger (which is a number like 0, 5, -999), but it wants an Entity.
You're on the right track for passing data from the table view to the NextViewController. You just need to do one of the following:
pass an Entity to -setEntity: (does the Entity class perhaps
have a constructor that takes an NSInteger?)
add a method to NextViewController that takes an NSInteger, and call that instead of -setEntity:

Problem with UICustomSwitch,

I am using UICsutomSwitch for my application. When I try to create it, I am getting an exception like,
Terminating app due to uncaught exception 'NSRangeException', reason: '* -[NSArray objectAtIndex:]: index 2 beyond bounds for empty array'
My code is as follows,
UICustomSwitch.h
#import <Foundation/Foundation.h>
#interface UICustomSwitch : UISwitch
{
}
-(void)setLeftLabelText:(NSString *)labelText;
-(void)setRightLabelText:(NSString *)labelText;
#end
UICustomSwich.m
#import "UICustomSwitch.h"
#implementation UICustomSwitch
-(UIView *)slider
{
return [[self subviews ] lastObject];
}
-(UIView *)textHolder
{
return [[[self slider] subviews]objectAtIndex:2];
}
-(UILabel *)leftLabel
{
return [[[self textHolder] subviews]objectAtIndex:0];
}
-(UILabel *)rightLabel
{
return [[[self textHolder] subviews]objectAtIndex:1];
}
-(void)setLeftLabelText:(NSString *)labelText;
{
[[self leftLabel] setText:labelText];
}
-(void)setRightLabelText:(NSString *)labelText
{
[[self rightLabel]setText:labelText];
}
#end
View Controller:
UICustomSwitch* switchView=[[[UICustomSwitch alloc]initWithFrame:CGRectMake(200,5,90,30)]autorelease];
[switchView setLeftLabelText:#"F"];
[switchView setRightLabelText:#"M"];
[switchView addTarget:self action:#selector(genderAction:) forControlEvents:UIControlEventValueChanged];
[elementView addSubview:switchView];
I am getting exception at " return [[[self slider] subviews]objectAtIndex:2];" call. I don't know what is the wrong, Can you guys please suggest me on this.
Thanks in advance,
Sekhar.
I ran across this issue and found the answer here:Custom UISwitch Text
Basically in iOS 4, there were UILabel's in the UISwitch's subviews that represented the "On/Off" labels. In iOS 5, there are no UILabels in the subviews array (hence the array error you're getting). The above link offers an external class you can download and customize. In my opinion, it seems like Apple is discouraging customization of UISwitch. The functionality you're after could be accomplished another way (segmented control, simulated checkbox, etc).
Also, in the given link above, the author proposes that the issue might be with not including armv6. I tried this and it does not fix the problem.
The exception indicates you are attempting to access an element of the array that is out of bounds (in a place that is larger than the actual size of the array).
You can use breakpoints and/or NSLog() calls carefully placed in your code to determine if this array ever is not-empty, and if that is so, you can continue to use these calls to find out just where the array becomes empty.
Clearly if the array is empty then the switch is setup differently than you expect it to be.

Resources