How can I make all Core Data objects inherit from my class rather than NSManagedObject? - objective-c

I created my own class that I want Core Data to use instead of NSManagedObject:
#interface MyManagedObject: NSManagedObject {
id delegate;
}
I can't use a category since this declares an ivar. All of my Core Data objects use concrete classes rather than being instances of NSManagedObject. I use the code generator to generate these files. Here's an example of what a Contact object might look like:
#interface Contact: NSManagedObject {
}
I know that I can manually change NSManagedObject to MyManagedObject in this generated code, but I will need to do this every time I regenerate the code. Is there any way to make it automatically use my own class?
Additionally, the #import in any solution might be a problem. Ideally I want it to use #class MyManagedObject rather than #import "MyManagedObject.h", since MyManagedObject.h is located in a library and the header needs a folder prefix to be accessible (e.g. #import "MyLib/MyManagedObject.h").
I tried creating a dummy object in the .xcdatamodel file with the same name and specifying that all objects inherit from it, but there are two problems. The first is that it is using #import "MyManagedObject.h", which it can't find due to the reason I specified above. The second problem is that I'm not sure it's a good idea to fool Core Data into thinking the class is inheriting from another Core Data object... even if I'm not generating the code file. I'm guessing that Core Data might be doing some unnecessary things behind the scenes because it believes there is an extra class which my classes are inheriting from.
I guess I can solve the first problem using another layer of classes. For example, I would specify that the objects inherit from MyProjectManagedObject and create a MyProjectManagedObject.h file in my project:
#import "MyLib/MyManagedObject.h"
#interface MyProjectManagedObject: MyManagedObject {
}
... and now my auto generated files will look like this:
#import "MyProjectManagedObject.h"
#interface Contact: MyProjectManagedObject {
}
... which will work. The only problem is the second one I mentioned above about extra code running behind the scenes in Core Data. Is this something to worry about or should I ignore it? Are there any other ways to do this which solve both problems mentioned above?

Don't use inheritance in your data model if you're using the SQL backend. Because of the implementation of the SQL backend, it has horrible performance and space characteristics. (This is Apple's recommendation.)
I may be wrong (I'll double-check), but I think you can do what you want using just the class and header files, without messing with the data model. (This is assuming you don't want to actually store your ivar in the data backend.) Just implement MyManagedObject like you did, and make your subclasses inherent from MyManagedObject instead of NSManagedObject (e.g. Contact : MyManagedObject). Note that you only have to do this in the header files, and not the actual data model. The compiler should figure out the rest.

Take a look at MOGenerator. It'll help with the regenerating the managed object class files at least: it makes you two files for each one. one that you edit and one that is automatically generated. When you regenerate the latter, the former is untouched.
http://digitalflapjack.com/blog/2010/mar/26/mogeneratorftw/

Related

Get Coco Class files programmatically

Using the objc/runtime.h we can create classes at runtime. How to export the .h and .m files from that class which is created at runtime?
Creating a .h is conceptually possible, but you'd need to write the code yourself to do it (using ObjC runtime calls to inspect the class and then write the file by hand). I don't know of anyone who has written this code already, but writing it would likely be an excellent introduction to the ObjC runtime functions. Note that the .h probably wouldn't be very friendly. For example, all object types in method signatures will be id. So it's kind of useable, but I can't think of a lot of ways I'd want to.
Creating a .m here doesn't make a lot of sense. The implementation of a runtime-generated class is going to be a bunch of IMP pointers to existing functions (which are themselves already compiled code). I don't know what you'd expect to be in the .m. In principle you could scan the executable to work out the names of the functions, and then write out a .m that looked something like:
- (void)someMethod {
SomeMethod_IMP()
}
This would probably get pretty complicated, and I can imagine several corner cases that would bite you in the general case.
This generally isn't how dynamically-generated classes are used, though, in the fairly rare cases that they are used. They're ubiquitous in KVO (but you'd never want a .h from that), and other uses of them are kind of similar: they usually are some magical subclass of an existing interface, so you never interact with them directly (and they almost always have an identical API to their superclass). What problem are you really trying to solve?
To get the implementation, you'd have to find or write a tool to translate assembly back in to Objective-C.
For just generating a header (interface), there are tools available. Use Google.
You cannot just tell the Objective-C runtime to create a new class from the .h and .m files because it takes a compiler. You need to hard-code the creation inside your project.
Create a subclass with objc_allocateClassPair
Add methods with class_addMethod (and properties with class_addProperty...)
Then you can use the new class.

Inheritance/design advice in Objective-C

Before I begin, I should probably mention that this sort of thing should probably have been implemented using the Core Data framework, but that is out of the question now.
We have data objects that are retrieved from a web service, and I'm trying to build a hierarchy for them, but I'm struggling.
I figured my base class should be called DataEntity, and defines an abstract property called EntityId and implements the hash method based on the entityId.
Any object retrieved from the web service can be implemented in one of two ways: By passing an NSDictionary to an entity, and letting it use that as its data source, or by passing the dictionary to an entity and letting it initialise its own data members from the dictionary. I have called these two types of entities DictionaryBackedDataEntity and ConcretedDataEntity. So my hierarchy would then be:
DataEntity -> DictionaryBackedDataEntity
-> ConcreteDataEntity
Then, consumers of this package/framework would only really care about the data members that are available to it, so I have created a protocol for each data type retrievable from the interface. So, for example, I could have a and an protocol, and these would have the data members that the DataEntity should expose.
So then, my hierarchy would look like this:
DataEntity -> DictionaryBackedDataEntity -> DictionaryBackedPerson <Person>
-> DictionaryBackedAnimal <Animal>
-> ConcreteDataEntity -> ConcretePerson <Person>
-> ConcreteAnimal <Animal>
Now, to be honest, I'm not sure whether I should be doing the above, or something like the below:
DataEntity -> PersonEntity -> DictionaryBackedPerson
-> ConcretePerson
-> AnimalEntity -> DictionaryBackedAnimal
-> ConcreteAnimal
In the above, PersonEntity and AnimalEntity would be abstract classes, and so instances would either be DictionaryBacked or Concrete instances.
Does anyone have any experience or recommendations on how I should approach this? I seem to be going around in circles and can't settle on a decision...
Regards,
N
Why not just have a single class DataEntity that stores it's property values in a dictionary? I think you probably don't need (and probably shouldn't require) to differentiate between ConcreteDataEntity and DictionaryBackedDataEntity.
#interface DataEntity
#property ( nonatomic, retain ) NSMutableDictionary * properties ;
#end
#implementation DataEntity
#synthesize properties ;
#end
#interface Animal : DataEntity
#property (nonatomic) NSUInteger numberOfLegs ;
-(id)initWithDictionary:(NSDictionary*)dict
{
if (( self = [ super init ]))
{
self.properties = dict ;
}
return self ;
}
#end
#implementation Animal
-(void)setNumberOfLegs:(NSNumber*)n
{
[ self.properties setValue:n forKey:#"numberOfLegs" ] ;
}
-(NSNumber*)numberOfLegs
{
return [ self.properties valueForKey:#"numberOfLegs" ] ;
}
#end
As a start...
You can save yourself some typing by using some of the more dynamic features of Obj-C here...
Look here: https://github.com/davedelong/Demos/tree/master/DynamicStorage
I definitely would NOT create the inheritance hierarchy you mentioned. You want to create inheritance based on the behavior of the class, not the underlying implementation for its internal data. You will end up with a class explosion as you add more classes that inherit from those bases and/or add more base implementations. Imagine you later have 3 types of base classes, one using the dictionary, one getting its dictionary passed in but using properties and fields, and a 3rd that uses another object or xml document or something. Then if you needed Person, Animal and Thing classes, you'd end up with 9 different classes total. DictionaryBackedPerson, ConcreteBackedPerson, ObjectXmlBackedPerson, etc. etc.
I would make one base class. Make it always have its own properties, but the ability to dynamically populate them using a dictionary if its passed, or vice versa as nielsbot mentioned. You could loop over a dictionary and call matching property names to set the values if needed.
There is nothing wrong with either approach from the information you have provided. But there are two schools of thought from what I can see.
The first is to take a technical approach which is your first example where you use DictionaryBackedDataEntity and ConcreteDataEntity. This is where your classes are representing how things have been implemented. I've seen a lot of this approach and generally speaking I'm not really a fan. Once your code gets larger and involved more classes this approach can have problems with clarity because it does not represent the application domain, but the implementation domain. ie. you end up with many (hundreds even) classes all built around their implementations, making it hard to discern what they are doing for your program.
The second approach (PersonEntity and AnimalEntity) is I think a more practical approach because it talks about your applications context and simply by looking at the names you immediately understand what they are for. In code, simplicity and clarity make for faster development and easier maintenance.
But the real truth I think is that you are likely to need a mix of both approaches in your code base. Often you need to develop small and abstract classes which don't necessarily manifest in your problem domain directly, but go a long way towards providing infrastructural code that supports other classes. These are good candidates for naming based on their technical aspects. Often too, this is code that can be split out to a separate project and built as a framework for use across multiple applications.
Finally, which design you choose will also come down to implementation code as well. For example, depending on the internals of your entities, you might be able to go with the first approach, but modify it so that that Person and Animal are categories on DataEntry rather than another layer of classes.
My final piece of advice would be to not get too hung up on which to do. Pick the one that feels the most comfortable to you and go with it. If at a later stage it's proves to be less that optimal for some reason, you can refactor to the other design. If nothing else, you will learn a bit about how you relate to code.

impact of core data on existing project iphone

I am starting to have a look at Core Data, as many claiming is the best way to persist data.
I have an already working project with its model and objects, the main purpose of the application is to encapsulate things as attributes (NString,NSObject, Custom Object..ecc) into one main class, give the ability to create many instance of this class then save it to storage, later retrieve and display a table list with all saved instance.
In this case, where my class is already defined (as NSObject extension), what could happen with the introduction of Core Data ? Do I need to rewrite my model ?
For example as a first try I created a model in xcode, then associate my object as entity to it. But some of the attributes that were not using standard such as string, int ...ecc got UNDEFINED as type.
#interface Car {
NSString *name;
WheelsType wtype; <-- undefined
NSDate *buy;
CarColor *color; <-- undefined
}
#end
What does that mean ? Am I able to save just only String,Int,Boolean...ecc but not my Custom Classes ? If not, what the table structure could be ?
thanks
Custom types in CoreData can be declared transformable, meaning that they'll be transformed to and from instances of NSData. The default value transformer works in many cases, but your classes may require a custom NSValueTransformer.
Edit:
Since utilizing CoreData changes how you retrieve your data, it'd be wise to review your model. Read the CoreData documentation and then consider how your objects are accessed and how you can avoid faulting objects and properties that will go unused.

Avoiding #import of header for abstract-only parent class

I develop CHDataStructures, a library of Cocoa data structures to supplement those in Foundation. It includes a fair number of classes (stacks, queues, and dequeues) that share common implementation details, so it makes sense to design them with a common parent class which I treat as abstract (Objective-C doesn't natively enforce this concept). For example, CHAbstractCircularBufferCollection encapsulates nearly all the logic for structures that utilize a circular buffer under the covers. Its child classes inherit the core behaviors, and conform to the appropriate protocol so only the methods that pertain to that protocol are added. (So a queue doesn't expose stack methods, etc.)
This has been working just fine, and correctness and coverage are verifiable via unit tests. However, the downside to the current approach is that each concrete subclass has a #import to include the header for the abstract parent class (see this header and implementation) — this means I have to export the parent class headers so client code will compile. It would be ideal if there is a way to use #class in the header rather than #import, so that calling code doesn't have to know or care about the abstract parent class. (It would also simplify and marginally shrink the size of the framework.) However, when I try this:
// CHCircularBufferQueue.h
#import "CHQueue.h"
#class CHAbstractCircularBufferCollection;
#interface CHCircularBufferQueue : CHAbstractCircularBufferCollection <CHQueue>
#end
I get this error, even if I #import CHAbstractCircularBufferCollection.h in the .m file:
Cannot find interface declaration for 'CHAbstractCircularBufferCollection', superclass of 'CHCircularBufferQueue'
I want the compiler to know about the parent class I'm extending, but not require clients to. Is there a way to accomplish what I want to do, and eliminate irrelevant headers from my distribution?
PS - This framework arose mostly from academic curiosity, but I'm considering making changes to make it more like Foundation collections by using class clusters and private subclasses. That would also solve this problem, but I'm curious whether there is a feasible way to do what I'm asking.
If you want to inherit a class, the superclass's #interface (hence the whole superclass hierarchy) must be known so that the ivar offsets of the subclass can be calculated.
You have to #import the .h file for the superclass. As KennyTM points out, this is so the compiler can calculate ivar offsets for the object struct. You can see this in any Cocoa header file. For example, if you open NSArray.h, the very first non-comment line is:
#import <Foundation/NSObject.h>
This holds true for every other class in Cocoa.

What is the difference between inheritance and Categories in Objective-C

Can some one explain to me the difference between categories and inheritance in Objective C? I've read the entry in Wikipedia and the discussion on categories there doesn't look any different to that of inheritance. I also looked at the discussion on the topic in the book "Open iPhone Development" and I still don't get it.
Sometimes, inheritance just seems like more trouble than it is worth. It is correctly used when you want to add something to an existing class that is a change in the behaviour of that class.
With a Category, you just want the existing object to do a little more. As already given, if you just want to have a string class that handles compression, you don't need to subclass the string class, you just create a category that handles the compression. That way, you don't need to change the type of the string classes that you already use.
The clue is in the restriction that categories only add methods, you can't add variables to a class using categories. If the class needs more properties, then it has to be subclassed.(edit: you can use associative storage, I believe).
Categories are a nice way to add functionality while at the same time conforming to an object oriented principle to prefer composition over inheritance.
Edit January 2012
Things have changed now. With the current LLVM compiler, and the modern, 64-bit runtime, you can add iVars and properties to class extensions (not categories). This lets you keep private iVars out of the public interface. But, if you declare properties for the iVars, they can still be accessed / changed via KVC, because there is still no such thing as a private method in Objective-C.
Categories allow you to add methods to existing classes. So rather than subclass NSData to add your funky new encryption methods, you can add them directly to the NSData class. Every NSData object in your app now has access to those methods.
To see how useful this can be, look at: CocoaDev
One of favorite illustrations of Objective-c categories in action is NSString. NSString is defined in the Foundation framework, which has no notion of views or windows. However, if you use an NSString in a Cocoa application you'll notice it responds to messages like – drawInRect:withAttributes:.
AppKit defines a category for NSString that provides additional drawing methods. The category allows new methods to be added to an existing class, so we're still just dealing with NSStrings. If AppKit instead implemented drawing by subclassing we'd have to deal with 'AppKitStrings' or 'NSSDrawableStrings' or something like that.
Categories let you add application or domain specific methods to existing classes. It can be quite powerful and convenient.
If you as a programmer are given a complete set of source code for a code library or application, you can go nuts and change whatever you need to achieve your programming goal with that code.
Unfortunately, this is not always the case or even desirable. A lot of times you are given a binary library/object kit and a set of headers to make do with.
Then a new functionality is needed for a class so you could do a couple of things:
create a new class whole instead of a stock class -- replicating all its functions and members then rewrite all the code to use the new class.
create a new wrapper class that contains the stock class as a member (compositing) and rewrite the codebase to utilize the new class.
binary patches of the library to change the code (good luck)
force the compiler to see your new class as the old one and hope it does not depend on a certain size or place in memory and specific entry points.
subclass specialization -- create subclasses to add functionality and modify driver code to use the subclass instead -- theoretically there should be few problems and if you need to add data members it is necessary, but the memory footprint will be different. You have the advantage of having both the new code and the old code available in the subclass and choosing which to use, the base class method or the overridden method.
modify the necessary objc class with a category definition containing methods to do what you want and/or override the old methods in the stock classes.
This can also fix errors in the library or customize methods for new hardware devices or whatever. It is not a panacea, but it allows for class method adding without recompiling the class/library that is unchanged. The original class is the same in code, memory size, and entry points, so legacy apps don't break. The compiler simply puts the new method(s) into the runtime as belonging to that class, and overrides methods with the same signature as in the original code.
an example:
You have a class Bing that outputs to a terminal, but not to a serial port, and now that is what you need. (for some reason). You have Bing.h and libBing.so, but not Bing.m in your kit.
The Bing class does all kinds of stuff internally, you don't even know all what, you just have the public api in the header.
You are smart, so you create a (SerialOutput) category for the Bing class.
[Bing_SerialOutput.m]
#interface Bing (SerialOutput) // a category
- (void)ToSerial: (SerialPort*) port ;
#end
#implementation Bing (SerialOutput)
- (void)ToSerial: (SerialPort*) port
{
... /// serial output code ///
}
#end
The compiler obliges to create an object that can be linked in with your app and the runtime now knows that Bing responds to #selector(ToSerial:) and you can use it as if the Bing class was built with that method. You cannot add data members only methods and this was not intended to create giant tumors of code attached to base classes but it does have its advantages over strictly typed languages.
I think some of these answers at least point to the idea that inheritance is a heavier way of adding functionality to an existing class, while categories are more lightweight.
Inheritance is used when you're creating a new class hierarchy (all the bells and whistles) and arguably brings alot of work when chosen as the method of adding functionality to existing classes.
As someone else here put it... If you are using inheritance to add a new method for example to NSString, you have to go and change the type you're using in any other code where you want to use this new method. If, however, you use categories, you can simply call the method on existing NSString types, without subclassing.
The same ends can be achieved with either, but categories seem to give us an option that is simpler and requires less maintenance (probably).
Anyone know if there are situations where categories are absolutely necessary?
A Category is like a mixin: a module in Ruby, or somewhat like an interface in Java. You can think of it as "naked methods". When you add a Category, you're adding methods to the class. The Wikipedia article has good stuff.
The best way to look at this difference is that:
1. inheritance : when want to turn it exactly in your way.
example : AsyncImageView to implement lazy loading. Which is done by inheriting UIView.
2. category : Just want to add a extra flavor to it.
example : We want to replace all spaces from a textfield's text
#interface UITextField(setText)
- (NSString *)replaceEscape;
#end
#implementation UITextField(setText)
- (NSString *)replaceEscape
{
self.text=[self.text stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]];
return self.text;
}
#end
--- It will add a new property to textfield for you to escape all white spaces. Just like adding a new dimension to it without completely changing its way.