Core Data: Where to put awakeFromFetch and awakeFromInsert? - objective-c

I would like to override awakeFromFetch and awakeFromInsert.
As I leave the auto-generated NSManagedObject subclasses unchanged and put my custom code in categories, my question is:
Where do I put awakeFromFetch and awakeFromInsert in order that these methods get called correctly?

If your managed object subclass files are generated by Xcode, then you can also put the methods in a category of the managed object subclass, so that the code is not overwritten when you re-generate the class files in Xcode.
MyEntity+Extensions.h
#import "MyEntity.h"
#interface MyEntity (Extensions)
#end
MyEntity+Extensions.m
#import "MyEntity+Extensions.h"
#implementation MyEntity (Extensions)
- (void)awakeFromFetch
{
}
- (void)awakeFromInsert
{
}
#end

You might want to also consider mogenerator. It's a command-line tool which generates two classes for each of your managed objects and ensures your custom code is never overwritten when your model changes.

According to NSManagedObject class reference you should put it in a subclass - calling super implementation is necessary:
Important: Subclasses must invoke super’s implementation before performing their own initialization.

You have to implement them in your subclasses. If the code is the same for all of your subclasses and you want to avoid copy-pasting them into each of them, I would suggest to write one subclass of NSManagedObject that implements them and then make your specific entity-classes subclasses of that class.
//MyManagedObject.h
#interface MyManagedObject : NSManagedObject
//...
#end
//MyManagedObject.m
#implementation
- (void)awakeFromFetch
{
//...
}
- (void)awakeFromInsert
{
//...
}
#end
//OneOfMyEntities.h
#interface OneOfMyEntities : MyManagedObject
//...

I feel making an extension is better option than subclass because in subclass you need to change the parent class again n again whenever you generate... i hope thats the better approach....

Related

Objective-C How to force subclass to implement methods?

Another way of phrasing this question: is it possible for a subclass to be a delegate of its super class? I'm trying to make my code reusable within my app and have a situation where the subsclass needs to implement two methods for it to be functional. How can I ensure this occurs? Or what is the proper way of defining these methods?
Update
I didn't mean to imply that I want the compiler to generate flags. I just want a clean way of organizing my code. Currently I override methods of the superclass. Using that approach the superclass can call [super methodToOverride] and it works. However this doesn't feel very clean to me as there's no way to specify "these are the methods you should override" aside from putting a comment somewhere.
In obj-c, it is not possible to force subclasses to overwrite methods of its superclass. But you can raise an exception in the superclass, should it ever be called because the subclass did not implement a certain method.
But a subclass can be a delegate of its superclass, if the superclass does not implement certain methods, and you can enforce that the delegate implements these methods, if the superclass specifies the protocol, i.e. required methods, and the subclass adopts it.
If you want to force your subclass to implement methods from super class, you can do this as below:
//In super class
- (id)someMethod:(SomeObject*)bla
{
[self doesNotRecognizeSelector:_cmd];
return nil;
}
Your app will crash if subclass will not implement this method and you don't need to call
[super someMethod:bla];
There is no way to do this in compile time. However you can raise an exception in the base class.
Something like this:
#throw [NSException exceptionWithName:NSInternalInconsistencyException
reason:[NSString stringWithFormat:#"You must override %# in a subclass", NSStringFromSelector(_cmd)]
userInfo:nil];
If your question is "how can I get the compiler to flag that a certain class doesn't implement a certain function" then I would say
Define a protocol with non-optional methods -- "By default, all methods declared in a protocol are required methods. This means that any class that conforms to the protocol must implement those methods."
Define a class ("stub") that declares it implements the protocol
Now when a subclass of your stub class is written, the compiler will flag it as an error if the mandatory method(s) aren't implemented
I know that it's awful, but supposed that you need to do this since your 3rdParty SDK requires this design pattern, you could use a Factory pattern:
Supposed then to have the base class MyParentAPIClient and two sub classes like MyFacebookAPIClient and MyGooglePlusAPIClient and that you do something like
self.myAPIClient = [MyParentAPIClient alloc] initWithAPIKey:apiKey];
and that you have defined
##interface MyParentAPIClient : NSObject {
}
-(void)callAPI;
#end
and you have override this in the two subclasses
#implementation MyFacebookAPIClient
-(void)callAPI {
[super callAPI];
// do something specific for this api client
}
#end
and
#implementation MyGooglePlusAPIClient
-(void)callAPI {
[super callAPI];
// do something specific for this api client
}
#end
Then you are doing in your controller
[self.myAPIClient callAPI];
but the super class MyParentAPIClient method is being called.
Now you could do a factory in the base class like:
-(void)callAPI {
if([self isKindOfClass:[MyFacebookAPIClient class]]) {
[((MyFacebookAPIClient*)self) callAPI];
} else if([self isKindOfClass:[MyGooglePlusAPIClient class]]) {
[((MyGooglePlusAPIClient*)self) callAPI];
}
}
Of course this have a downside that is to do not call the super in the sub classes that now become:
#implementation MyFacebookAPIClient
-(void)callAPI {
// [super callAPI]; the factory method called that
// do something specific for this api client
}
#end
and
#implementation MyGooglePlusAPIClient
-(void)callAPI {
// [super callAPI]; being called in the factory
// do something specific for this api client
}
#end
The good news is that there is no change in the methods calls since as soon as you call from the controller:
[self.myAPIClient callAPI];
You will have the calls
[MyParentAPIClient callAPI]; // parent class
[MyFacebookAPIClient callAPI]; // sub class
The other downside is that the parent class must known the subclass instances.
Now if we take a look at the factory:
if([self isKindOfClass:[MyFacebookAPIClient class]]) {
[((MyFacebookAPIClient*)self) callAPI];
} else if([self isKindOfClass:[MyGooglePlusAPIClient class]]) {
[((MyGooglePlusAPIClient*)self) callAPI];
}
}
we could make it better like in several way. Take a look at Dynamic type cast from id to class in objective c and Is there an equivalent to C++'s dynamic cast in Objective-C? or Objective-C dynamic_cast?
Good luck!
The UIGestureRecognizerSubclass.h pattern from UIKit is worth a look, that has all the protected methods that should be overridden and that header is not in the framework include, it is only included in subclasss' .m files. Also, nowadays you can tag methods with NS_REQUIRES_SUPER to require overrides to call super, however it can only be used in interfaces, not protocols so that might influence your design.
For super advanced code, NSAccessibilityProtocols.h in AppKit uses a protocol tag to require subclasses to re-implement methods, even if already implemented by a superclass. Here is an example of that you can paste right into in header in your currently open Xcode project:
NS_PROTOCOL_REQUIRES_EXPLICIT_IMPLEMENTATION
#protocol Protocol
#property (readonly) id theWorstOfTimes;
// -(void)testMethod; // uncomment to test problem
#end
// In this example, ClassA adopts the protocol.
#interface ClassA : NSObject <Protocol>
#property (readonly) id theWorstOfTimes;
#end
#implementation ClassA
- (id)theWorstOfTimes{
return nil; // default implementation does nothing
}
-(void)testMethod{}
#end
// This class subclasses ClassA (which also adopts 'Protocol').
#interface ClassB : ClassA <Protocol>
#end
#implementation ClassB // expected-warning {{property 'theWorstOfTimes' requires method 'theWorstOfTimes' to be defined - use #synthesize, #dynamic or provide a method implementation in this class implementation}}
#end
In Xcode you'll see a yellow line at ClassB's expected-warning that the property method is missing. NS_PROTOCOL_REQUIRES_EXPLICIT_IMPLEMENTATION is just a macro for __attribute__((objc_protocol_requires_explicit_implementation)) and this code sample is modified from the test harness of that feature here.
Although this looks great there is a slight problem. Currently this only works for methods that implement protocols, it used to work also for methods but a bug has been introduced in 2014 via a misunderstanding on the purpose of this feature and thus now it is limited to property methods. I have emailed the author to make them aware so hopefully it changed back to its original and proper behavior. To test the bug you can uncomment the method in the protocol and you will see there is no warning in ClassB. Hopefully you can change some of your methods to read-only properties to at least get some use out of it. On the plus side when Xcode offers to "Fix" the issue it does add stubs for the missing methods.
Here is some documentation on NS_PROTOCOL_REQUIRES_EXPLICIT_IMPLEMENTATION:
ImplementingAccessibilityforCustomControls
nsaccessibilitybutton
If you used this then pat yourself on the back for becoming an ObjC expert if you weren't already!

Simulate multiple inheritance in Objective-C

I have kind of an abstract class for my UIViewControllers (lets call it MyViewController) which overrides some basic methods like viewDidLoad or viewDidDisappear. In this methods some preparations are made, like setting up colors for the navigation bar, or preparing the bar buttons or something like that.
Now I want this basic behaviour for my UITableViewControllers also. So I made a new class that inherits UITableViewController (lets call it MyTableViewController) and copied 99% of the code from MyViewController.
In this image you see my current architecture. Listed are the overriden methods, in which other private methods are called. Again, MyViewController and MyTableViewController share 99% codebase (only difference is the name of the class and the super class).
For obvious reasons this is crap.
Is there an elegant solution to make MyTableViewController a subclass of both MyViewController and UITableViewController?
This is one suggestion, but I don't know how useful it is because I don't know your code.
You could implement a bunch of methods in a category for the UIViewcontroller class. For example:
#implementation UIViewController (myCategory)
- (void)setupColors;
...
#end
Since both MyViewcontroller and MyTableViewcontroller inherit from UIViewController, they would inherit your methods.
The only thing that you would copy in both implementation is the invocation of those functions, but the duplicate code would be much less.
- viewDidLoad...
{
[self setupColors];
}
Just be careful if you override methods, because you can't call [super ... ] on a category as you can in an inherited class
Shared implementation for your common methods could be done either with a category or with composition. Since a category can't be used to directly override existing interface (e.g. viewDidLoad:) you would need to put your private methods into the category and call them from your subclass overrides. Another option would be to put your shared implementation in a separate class (which might be a singleton) and compose an instance of that as a property of both MyViewController and MyTableViewController, e.g.:
#interface MyViewController : UIViewController
#property (nonatomic, strong) MyControllerStyler *controllerStyler;
#end
#implementation MyViewController
- (void)viewDidLoad {
[super viewDidLoad];
[controllerStyler viewDidLoad];
}
...etc...
The composed class's methods could reference the controller if needed, e.g.:
#interface MyControllerStyler : NSObject
- (void)viewDidLoadInController: (UIViewController *)controller;
...etc...
While a category seems perfectly fine for this example, if your extensions collectively represent a meaningful unit of your design (such as a collection of visual styling attributes) that might argue for a separate object (or objects) to better represent your intent.

How to implement Objective-C Category on several custom classes

I have several subclasses of UIViewController that I want to use a single category to give them all a couple of methods. The thing is I only want my classes not the base UIViewController to have that categories methods.
Say I have:
PanelAViewController
PanelBViewController
...
That I want to implement and respond to a class:
PanelAnimations
-(void)animateIn;
-(void)animateOut;
I could use a protocol and insert the methods each time but they use the same methods and values, so wouldn't a category suit?
I am just not sure how to define the category for these custom classes.
Why you didn't consider subclassing, instead of using categories or protocols? Here here you can simply create an AbstractViewController class (which heritates from UIViewController) that defines the panel animations methods, and then derive your own concrete controllers (PanelAViewController, PanelBViewController, etc.) from the abstract one.
The abstract class will define the methods and eventually some stubs in the implementation (is up to you if you want that PanelA and PanelB should call super or not). This depends on the abstraction degree you want to give to the abstract class. See the code example below.
Sometimes it is not clear if it is better to use a protocol or subclass or delegate mechanism. Most of the times the boundary is not clear and the final decision is more dependent on the programmer preference than a "codified" architectural rule. Typically you use protocol when you want different objects to have a common behavior for certain tasks (e.g.: you have a complex set of entities and one of these entities should be used as a map annotation: in such case you must simply provide this specific entity the MKAnnotation protocol compatibility); delegate is mostly used when you want to extend a class without subclassing it or without given the final user the possibility to subclass it. In your case I think subclassing is the most appropriate choice as all classes are strictly part of the same class hierarchy, they share a common code (or common interface) and provide each a specialized implementation.
//
// AbstractViewController.h
//
#import
#interface AbstractViewController : UIViewController
-(void)doAnimate;
-(void)didAnimate;
#end
//
// AbstractViewController.m
//
#import "AbstractViewController.h"
#interface AbstractViewController ()
#end
#implementation AbstractViewController
-(void)doAnimate {
NSLog(#"Abstract do animate");
}
-(void)didAnimate {
NSLog(#"Abstract did animate");
}
//
// ConcreteViewController.h
//
#import "AbstractViewController.h"
#interface ConcreteViewController : AbstractViewController
#end
//
// ConcreteViewController.m
//
#import "ConcreteViewController.h"
#interface ConcreteViewController ()
#end
#implementation ConcreteViewController
-(void)doAnimate {
[super doAnimate];
NSLog(#"Subclass do animate");
}
Seems like your best bet would be to derive a custom class from UIViewController, call it say "MyUIViewControllerBase". Add your custom methods to that class, then derive the rest of your view controllers from it. No category needed and it solves your problem.
Suppose you have control over all your custom ViewControllers, the easiest way would be creating a subclass of NSViewController - like MyViewController - and subclass every other of your own ViewControllers from it. This way you would not even have to write a category for them. You could simply implement your wanted features within the MyViewController.
NSViewController
|
MyViewController -- implement your shared methods here
/ \
MyViewControllerA MyViewControllerB

Does Objective-C have something like C++ virtual functions?

In objective-c it is possible to add a #dynamic to a property.
Is this also possible for normal instance methods?
EDIT
I think i wasn't clear enough.
I want to do the following:
#interface MyClass
#property (retain) NSObject *somePropertyObject;
- (void) myMethod;
#end
#implementation MyClass
#dynamic somePropertyObject;
//Make myMethod dynamic. I do not want to implement it. Like C++ Virtual
#end
If you mean "How can I declare a method, but not provide a definition which I will subsequently provide at runtime?" Then it's easy, just use a category. Like this:
#interface MyObject : NSObject
// Methods I'll define
- (void)doFoo;
#end
#interface MyObject (DynamicallyProvidedMethods)
// Methods I won't
- (void)myDynamicMethod;
#end
#implementation MyObject
// Methods I'll define
- (void)doFoo
{
}
#end
The compiler will not complain, however if you call -myDynamicMethod at runtime, unless you have provided an implementation for it somehow, it will crash with "unrecognized selector." You can, of course, test for that at runtime by calling respondsToSelector:.
Relatedly, if you're looking to do a near-equivalent of a base class pure virtual method, I would recommend providing an empty implementation that asserts when called if it has not been overridden by a subclass. You can do that like so:
NSAssert((class_getInstanceMethod([self class], _cmd) == class_getInstanceMethod([MyObject class], _cmd)),
#"Subclass of %# must override -%#",
NSStringFromClass([MyObject class]),
NSStringFromSelector(_cmd));
// ...where overridesSelector:ofBaseClass: looks like:
//
// return ;
Of course, that won't alert you to problems at compile time, but it's better than nothing.
HTH
I think you might be asking how to declare a method that will be implemented some time later somewhere else.
The Objective-C way to do that is to use Protocols.
You declare a protocol like this, usually in a header file
#protocol MyProtocol <NSObject> {
#optional
- (void)optionalMethod;
#required
- (void)requiredMethod;
}
#end
This declares two methods, one which is optional and one is required. To use this protocol you declare the conformance when declaring the class that will implement the protocol
#interface MyConformingClass : NSObject <MyProtocol> {
}
// you don't have to redeclare methods that are declared in the protocol
#end
This new class is checked at compile time for the implementation of requiredMethod so it has to implement it, but it can choose whether or not to implement the optionalMethod
Now, any class that requires instances of objects to conform to the protocol can declare this, for example, in the interface
#interface RequiringClass : NSObject {
MyConformingClass <MyProtocol> *conformingClassObject;
}
…
#end
Again, this is checked at compile time
To make sure that the conforming class implement the #optional methods, we can use this handy structure
if [conformingClassObject respondsToSelector:#selector(optionalMethod)] {
[conformingClassObject optionalMethod];
} else {
// Do something here because the optional method isn't provided
}
Examples of this are all over Cocoa - it's a class can provide a list of actions that it would like to farm out to it's delegate, the delegate adopts the protocol and provides the implementations of those delegate methods. The calling object can then check if this delegate responds to those methods at runtime as I've described above, and call those methods to perform actions, or provide information where ever it needs to.
This is used quite a lot in Objective-C, where classes provide a list of methods that they would like some other class to perform, unlike virtual functions, where a class declares functions it wants subclasses to provide implementations for. Particularly as Composition is favoured over inheritance in the language. Rather than create a subclass to provide an implementation, you just create another class that can do the same thing, and add a reference to that in the class instead.
No.
#dynamic is just an instruction to the compiler that says: "Don't bother generating accessors for this property, I'm going to provide my own."
Using #dynamic with other methods wouldn't be helpful because the compiler doesn't generate any methods other than accessors for you, and of course you're supplying the other methods anyway.
What are you trying to accomplish?

How to provide additional custom implementation of accessor methods when using #synthesize?

I want to fire some code when a property is accessed and changed. I use #property and #synthesize in my code for my ivars. The properties are retained, so I'd like to keep that memory management stuff automatically generated by #synthesize.
However, I assume that #synthesize tells the compiler to generate the accessor methods code right where #synthesize is, so most of the cases at the top of the code, right?
And when I have a property foo, I get -setFoo and -foo methods. Could I then just make a method like this, to execute some more custom code when a property is changed?
-(void)setFoo {
// custom stuff
}
Now that's a problem. How to execute the first one? I wouldn't love to have a different name here. Is there maybe a way to let the #synthesize directive create other names for getter and setter methods, which I then call easily? And I would still be able to use the dot syntax then to access them?
You can use #property and #synthesize just like you normally would, but provide a custom setter or getter (or both) and those will be used instead. Typically I will do something like this:
// Override the setter
- (void)setName:(NSString *)aName
{
if (name == aName)
return;
[name release];
name = [aName retain];
//custom code here
}
When I use the set property, it will invoke my custom method. However, the get will still be synthesized.
If you provide an implemnetation for the setters or getters it will use that instead of the generated implementation. Its not hard to implement the "retaining" aspect of the getters and setters that are generated for you by the compiler when u synthesize, so you can just write your own getters and setters i would say and go with that.
One wacky solution is to create an abstract super class that does gives you the normal property synthesis.
Then create a concrete subclass that you will actually use, and that simply implements and override method (same signature) and calls super to do the actual setting.
This allows you to do whatever you want to do before or after the call to super's implementation.
Example:
#interface ALTOClassA : NSObject
#property NSString *catName;
#end
Nothing else needed in the .m beyond the stubbed file for this test.
Create the subclass, nothing needed specially in the #interface
#import "ALTOClassA.h"
#interface ALTOClassAJunior : ALTOClassA
#end
In the #implementation we do our override.
#import "ALTOClassAJunior.h"
#implementation ALTOClassAJunior
- (void)setCatName:(NSString*)aCatName {
NSLog(#"%#",NSStringFromSelector(_cmd));
[super setCatName:aCatName];
NSLog(#"after super: self.catName %#", self.catName);
}
#end
In use:
ALTOClassAJunior *aCAJ = [ALTOClassAJunior new];
NSLog(#"aCAS.catName %#", aCAJ.catName);
NSLog(#"set it to George.");
[aCAJ setCatName:#"George"];
NSLog(#"aCAS.catName %#", aCAJ.catName);
This allows you to leverage the autogenerated code, and still do stuff you want to do with your class. Abstract Super Class is often a useful solution for many things.
Yes, in your #property declaration, you can specify the getter and setter methods.
#property (readwrite,getter=privateGetFoo,setter=privateSetFoo:) NSObject * foo;
In your foo and setFoo: methods, call [self privateGetFoo] or [self privateSetFoo:f] then your custom code.
The object can also set an observer on itself with addObserver:forKeyPath:options:context:.
That said, I don't think either of these are very clean ways to do things. Better to write your own getter/setter as others have suggested.