initWithCoder and encodeWithEncoder hell. Can this be simplified? - objective-c

With dozens of models with dozens of properties each, all able to be saved to disk using the NSCoder protocol and NSKeyed(Un)archiver, it's a lot of work to create and maintain models for my iOS application. With a dozen of properties for one model, I have to:
define a dozen of properties (which is ok, because they HAVE to be defined somewhere)
fill the initWithCoder: method, that's a dozen lines and two dozen times typing/copy-pasting the property name (or a constant key), 3) some goes for encodeWithCoder:.
The risk of mistakes (either in typing, copying or changing (or not changing) things like encodeObject: to encodeInteger: is huge. Besides, it's simply a lot of manual work, which I prefer not to do. After all, we have computers to do that for us.
First I looked into something like simplifying the work. Something like this:
#define encodeObject(x) [encoder encodeObject:[self valueForKey:x] forKey:x]
#define decodeObject(x) [self setValue:[decoder decodeObjectForKey:x] forKey:x]
But that is still a lot of work. Can't this be done any simpeler?
I do not prefer to do this on runtime using introspection or something.
I am thinking about some Python script that generates/manipulates the model files and adds them to Xcode. This could be based upon some JSON description file.
Having Xcode run this automatically in the pre-build phase would be great. Meaning a single place where I define every model and every property once and never having to worry about mistakes and properties I forgot to encode/decode.
Is the anything like that out there? Are there methods to add files to an Xcode project, without messing with some unreadable Apple "XML" project files? And what about including the headers in the target.. Or maybe some other great method to save me all that work?

Related

What is the purpose of SomeClass+CoreDataClass files?

I'm trying to understand how Core Data works in Objective-C and can't quite get the purpose of categories that have the name SomeClass+CoreDataClass and are created when we want to subclass NSManagedObject.
As far as I know, they should be created only once and not regenerated every time we need to update our entity's structure, so we can add our methods there. However, they are recreated as blank files every time I regenerate a subclass of NSManagedObject.
I think, I'm missing something, so could you explain their purpose?
+CoreDataClass is generated by xcode, you shouldn't edit it, because you can loose changes.
You can edit SomeClass, Xcode will only create it if it isn't exist.
This division was made just for programmers convenience.
You can freely move code from +CoreDataClass to main file and delete category if you wish.

Core data files exported with underscore

When I go to Editor-->CreateNSManagedObjectSubclass, and export my entities, they show up as the entity names... but another person who was working on my project before seems to have exported as their name with an underscorebefore, and these files look totally different on the inside...So I'm confused as to what's going on. Here's a google doc that contains a few relevant screenshots... Check out the second page to the two sections of fields. I'm sort of confused by them:
https://docs.google.com/document/d/1BMBqJME91Njb69JS4x3bvH0-KSmC-KLBl6QglE22jmQ/edit?usp=sharing
Can someone explain what is going on here?
You might want to read up on MOGenerator, since that's apparently what your predecessor used to generate the managed object classes. By default MOGenerator generates base classes prefixed with an underscore and initially generates stub subclasses (the ones without the underscores).
You can then write any custom code in the subclasses. That way, whenever the model changes, you can regenerate the base classes without worrying about clobbering your custom code, since by default MOGenerator won't regenerate the subclasses.

ObjC: Subclass a class whose #interface is inside a .m file

I am trying to subclass a class whose #interface and #implemetation are buried inside of another class' ".m" file in order to restyle some of the views declared within. The superclass is a cocoapod, which I am unable to modify without forking the repo, which I am really trying to avoid doing. Is there any clever/hacky way to pull this off, or is it simply impossible?
In all honesty, I fail to see why forking would be a bad idea or why you would want to avoid it. That's the entire point of forking, modifying the code to fit your need more and perhaps later merge it back if the community finds it useful as well.
You can try to hack around this by redeclaring the class or whatever, but that implementation would be far more fragile than you having a fork which you have full control over (including merging any upstream changes). I think this is more related to a mental block of thinking that a fork becomes "your" code and "your" responsibility, while in reality it is just as much to maintain as it would be to keep the hacky version working across changes to the 3rd party code.

iOS: is there a way to use a single class to hold common variables and not break Object Oriented principles?

I want to separate the data from the implementation in several classes, for many reasons.
One reason, for example, is that I have a few different menu screens that display text. I want to have one class that lists all the text for all the menus in one place, and then have the different menu objects read from that class when they initialize.
That way, whenever I want to make changes, I know exactly where the text variables are, and if I want to, I can change a bunch of them all at once.
I want to use the same principle in a lot of different ways, for example, setting the color and alpha values of various UIViews; having them all in one place would enable me to coordinate their settings and make small adjustments very easily.
Added to these reasons is that I'm working with a small team of other developers, and if we all know we're storing this kind of information in one place it's easier to understand each other's code.
So basically I want one big UberData class that every other class can read from and write to.
As far as I can figure, the only way to do this is make each of the needed variables a property, so I'll basically have a big methodless class with a heck of a lot of properties. But to my understanding, that's kind of bending the OO rules, because as much as possible classes should hide their innards. Not to mention the whole things seems really kludgey.
So the question is: is there a better way to do this than having the class with a million properties, and is it even proper to do it, from an OO perspective, at all?
One big UberData class (and really, if you are thinking properties, you mean one instance of that class) is the wrong approach.
What do menu strings and view colors have to do with each other? Nothing. Therefore they don't belong in the same class.
Strings
For your menu strings, look into the NSLocalizedString macro and creating a strings file. You could create a CommonStrings class that wraps all of your calls to NSLocalizedString:
#interface CommonStrings : NSObject
+ (NSString *)open;
+ (NSString *)save;
// etc.
#end
#implementation CommonStrings
+ (NSString *)open {
return NSLocalizedString(#"open", #"menu item title for opening a file");
}
+ (NSString *)save {
return NSLocalizedString(#"save", #"menu item title for saving a file");
}
// etc.
#end
This approach means you only write #"open" in one place, and then you refer to [CommonStrings open] when you need the (localized) string. The compiler checks that you've spelled [CommonStrings open] correctly, which is nice.
However, it's still probably better to break this into multiple helpers (one for each independent part of your app), rather than one giant helper for your entire app. If you use one giant catch-all class, then compiling your app takes longer because so much has to be recompiled every time you add or remove a method in this class.
UIView colors
First, watch the appearance customization videos from WWDC 2012 and WWDC 2013 and read up on UIAppearance. Maybe you can just use that to customize your app's colors.
If that doesn't suffice, create a category on UIColor for your app's colors:
#interface UIColor (MyApp)
+ (UIColor *)MyApp_menuBackgroundColor;
+ (UIColor *)MyApp_menuTextColor;
// etc.
#end
#implementation UIColor (MyApp)
+ (UIColor *)MyApp_menuBackgroundColor {
return [self colorWithPatternImage:[UIImage imageNamed:#"menuBackgroundPattern"]];
}
+ (UIColor *)MyApp_menuTextColor {
return [self colorWithWhite:0.0 alpha:1.0];
}
// etc.
#end
Again, it may be better to have multiple helper categories for different parts of your app, so you don't have to recompile as much when you add or remove a category method.
First off, forget "propriety". What is proper is what works, works reliably and efficiently, is easy to understand, and easy to maintain. Adhering to "object-oriented principles", while to some degree a worthwhile goal, should not cause you to do awkward, error-prone, and inefficient things. Just about any "programming rule" can be followed too literally.
Having dozens (or hundreds) of properties is clumsy and hard to maintain from several standpoints, so that's basically a non-starter.
More appropriate is having a few queryable interfaces that return the values you want. The "right" scheme often depends on the characteristics of the data, but one can, eg, have a method with a simple switch statement or "if ladder" that returns value Y given value X (where X is, eg, an enumeration value).
One can also have what is either actually or conceptually an NSDictionary which you query with a character "key" value.
A variation of that is a property list, which allows you to describe the data in a data file, vs having to code it into source. You can also put the data in a JSON file, if that suits your design and habits better.
And there are several other schemes that I've used in the past that aren't occurring to me just now.
Added:
OK, I'll give an example of something that is basically impossible with "macros" and "extern variables". In several cases, in some of the code I work on, there are objects that contain information about specific events. There may be 50 different categories of events, each with a different set of properties (sub-category, display color, text for various conditions, etc).
One could, of course, have several hundred declared constants, of the style "kXyzCategoryAbcSubCategory", "kXyzCategoryAbcColorMode", "kXyzCategoryAbcTitleText", etc, but maintaining is a PITA, and typos in use are routine. Plus it's not really usable, since you can't take "category" from the object and "index" the attributes.
Instead, I use one of two schemes:
A set of callable interfaces where you pass in the constant "kXyzCategoryAbc" (or the category value dynamically extracted from the object) and call one of several methods -- xyzSubCategory, xyzColorMode, xyzTitleText -- and the method returns the required data.
A callable interface where you pass in the category value and it returns an NSArray (with keys, eg, of "subCategory", "colorMode", and "titleText").
Both of these techniques work pretty well, though one or the other may be preferred depending on circumstances. Both allow you to maintain the data as a table of some sort, and allow you to use the same constant to fetch multiple values, vs having to introduce 50 new constants when you add one new attribute to one of your category objects.
You shouldn't use a class for this at all. Use macros for code internal constants, and extern variables for values that can change.
Note: User visible strings should be done through localization files -- see the other answers.
When it comes to constants, I usually have a CPConstants.h (CP being my class prefix) file that looks something like this:
#define kCLConstant1 42
#define kCLColorConstant [UIColor blackColor]
And so on.
If you need values to be changeable, first create a CLConstants.m file, like this:
#import "CLConstants.h"
int some_global_var = 42;
UIColor* some_global_changable_color = [UIColor blackColor];
And so on. Then, in CLConstants.h, add a line like this for every variable you declared in CLConstants.m:
extern type varname;
Now all files that include/import CLConstants.h can use and change those variables, and changes will be visible to all other files in the project.
Yes, the common response to a single, shared configuration object is the Singleton pattern. Briefly, a class method knows how to make or return an instance of the class and the instance knows how to configure the needed things. I think you will find many results from stack overflow by searching although What should my Objective-C singleton look like? is one easy example.
Beyond that, I would encourage you to look into how localization works in iOS - the problem you initially reference of having a source for menu titles and things is one that the localization library has solved for you, and in an extensible way.
You may also want to look at property lists (aka, plists) which is a structured data file that can be easily read in iOS applications.
You basically have two choices in sharing data across several controllers:
1) Use a singleton
In this instance, a singleton data model sounds appropriate. (A singleton data model is a single, shared instance of a data model used by several controllers.)
As you mentioned, however, you may indeed wind up with a class that has lots of properties by doing this... there's nothing wrong per se about this, however. Just be choosy in the properties that you have on the singleton... if it's not shared by several controllers, it probably shouldn't be there.
See Apple's documentation on how to create such here.
Here's another SO post about Singletons in iOS.
2) Use a header (.h) file in which you define all your shared variables, then import this wherever you need them (or put into the .pch file to be automatically imported everywhere in your project).
Typically, this is done using static constant variables. I'd imagine you could possibly do this via just static variables so that you can edit them, but at least the last I checked, the compiler may give incorrect unused variable warnings.

What is the best way to solve an Objective-C namespace collision?

Objective-C has no namespaces; it's much like C, everything is within one global namespace. Common practice is to prefix classes with initials, e.g. if you are working at IBM, you could prefix them with "IBM"; if you work for Microsoft, you could use "MS"; and so on. Sometimes the initials refer to the project, e.g. Adium prefixes classes with "AI" (as there is no company behind it of that you could take the initials). Apple prefixes classes with NS and says this prefix is reserved for Apple only.
So far so well. But appending 2 to 4 letters to a class name in front is a very, very limited namespace. E.g. MS or AI could have an entirely different meanings (AI could be Artificial Intelligence for example) and some other developer might decide to use them and create an equally named class. Bang, namespace collision.
Okay, if this is a collision between one of your own classes and one of an external framework you are using, you can easily change the naming of your class, no big deal. But what if you use two external frameworks, both frameworks that you don't have the source to and that you can't change? Your application links with both of them and you get name conflicts. How would you go about solving these? What is the best way to work around them in such a way that you can still use both classes?
In C you can work around these by not linking directly to the library, instead you load the library at runtime, using dlopen(), then find the symbol you are looking for using dlsym() and assign it to a global symbol (that you can name any way you like) and then access it through this global symbol. E.g. if you have a conflict because some C library has a function named open(), you could define a variable named myOpen and have it point to the open() function of the library, thus when you want to use the system open(), you just use open() and when you want to use the other one, you access it via the myOpen identifier.
Is something similar possible in Objective-C and if not, is there any other clever, tricky solution you can use resolve namespace conflicts? Any ideas?
Update:
Just to clarify this: answers that suggest how to avoid namespace collisions in advance or how to create a better namespace are certainly welcome; however, I will not accept them as the answer since they don't solve my problem. I have two libraries and their class names collide. I can't change them; I don't have the source of either one. The collision is already there and tips on how it could have been avoided in advance won't help anymore. I can forward them to the developers of these frameworks and hope they choose a better namespace in the future, but for the time being I'm searching a solution to work with the frameworks right now within a single application. Any solutions to make this possible?
Prefixing your classes with a unique prefix is fundamentally the only option but there are several ways to make this less onerous and ugly. There is a long discussion of options here. My favorite is the #compatibility_alias Objective-C compiler directive (described here). You can use #compatibility_alias to "rename" a class, allowing you to name your class using FQDN or some such prefix:
#interface COM_WHATEVER_ClassName : NSObject
#end
#compatibility_alias ClassName COM_WHATEVER_ClassName
// now ClassName is an alias for COM_WHATEVER_ClassName
#implementation ClassName //OK
//blah
#end
ClassName *myClass; //OK
As part of a complete strategy, you could prefix all your classes with a unique prefix such as the FQDN and then create a header with all the #compatibility_alias (I would imagine you could auto-generate said header).
The downside of prefixing like this is that you have to enter the true class name (e.g. COM_WHATEVER_ClassName above) in anything that needs the class name from a string besides the compiler. Notably, #compatibility_alias is a compiler directive, not a runtime function so NSClassFromString(ClassName) will fail (return nil)--you'll have to use NSClassFromString(COM_WHATERVER_ClassName). You can use ibtool via build phase to modify class names in an Interface Builder nib/xib so that you don't have to write the full COM_WHATEVER_... in Interface Builder.
Final caveat: because this is a compiler directive (and an obscure one at that), it may not be portable across compilers. In particular, I don't know if it works with the Clang frontend from the LLVM project, though it should work with LLVM-GCC (LLVM using the GCC frontend).
If you do not need to use classes from both frameworks at the same time, and you are targeting platforms which support NSBundle unloading (OS X 10.4 or later, no GNUStep support), and performance really isn't an issue for you, I believe that you could load one framework every time you need to use a class from it, and then unload it and load the other one when you need to use the other framework.
My initial idea was to use NSBundle to load one of the frameworks, then copy or rename the classes inside that framework, and then load the other framework. There are two problems with this. First, I couldn't find a function to copy the data pointed to rename or copy a class, and any other classes in that first framework which reference the renamed class would now reference the class from the other framework.
You wouldn't need to copy or rename a class if there were a way to copy the data pointed to by an IMP. You could create a new class and then copy over ivars, methods, properties and categories. Much more work, but it is possible. However, you would still have a problem with the other classes in the framework referencing the wrong class.
EDIT: The fundamental difference between the C and Objective-C runtimes is, as I understand it, when libraries are loaded, the functions in those libraries contain pointers to any symbols they reference, whereas in Objective-C, they contain string representations of the names of thsoe symbols. Thus, in your example, you can use dlsym to get the symbol's address in memory and attach it to another symbol. The other code in the library still works because you're not changing the address of the original symbol. Objective-C uses a lookup table to map class names to addresses, and it's a 1-1 mapping, so you can't have two classes with the same name. Thus, to load both classes, one of them must have their name changed. However, when other classes need to access one of the classes with that name, they will ask the lookup table for its address, and the lookup table will never return the address of the renamed class given the original class's name.
Several people have already shared some tricky and clever code that might help solve the problem. Some of the suggestions may work, but all of them are less than ideal, and some of them are downright nasty to implement. (Sometimes ugly hacks are unavoidable, but I try to avoid them whenever I can.) From a practical standpoint, here are my suggestions.
In any case, inform the developers of both frameworks of the conflict, and make it clear that their failure to avoid and/or deal with it is causing you real business problems, which could translate into lost business revenue if unresolved. Emphasize that while resolving existing conflicts on a per-class basis is a less intrusive fix, changing their prefix entirely (or using one if they're not currently, and shame on them!) is the best way to ensure that they won't see the same problem again.
If the naming conflicts are limited to a reasonably small set of classes, see if you can work around just those classes, especially if one of the conflicting classes isn't being used by your code, directly or indirectly. If so, see whether the vendor will provide a custom version of the framework that doesn't include the conflicting classes. If not, be frank about the fact that their inflexibility is reducing your ROI from using their framework. Don't feel bad about being pushy within reason — the customer is always right. ;-)
If one framework is more "dispensable", you might consider replacing it with another framework (or combination of code), either third-party or homebrew. (The latter is the undesirable worst-case, since it will certainly incur additional business costs, both for development and maintenance.) If you do, inform the vendor of that framework exactly why you decided to not use their framework.
If both frameworks are deemed equally indispensable to your application, explore ways to factor out usage of one of them to one or more separate processes, perhaps communicating via DO as Louis Gerbarg suggested. Depending on the degree of communication, this may not be as bad as you might expect. Several programs (including QuickTime, I believe) use this approach to provide more granular security provided by using Seatbelt sandbox profiles in Leopard, such that only a specific subset of your code is permitted to perform critical or sensitive operations. Performance will be a tradeoff, but may be your only option
I'm guessing that licensing fees, terms, and durations may prevent instant action on any of these points. Hopefully you'll be able to resolve the conflict as soon as possible. Good luck!
This is gross, but you could use distributed objects in order to keep one of the classes only in a subordinate programs address and RPC to it. That will get messy if you are passing a ton of stuff back and forth (and may not be possible if both class are directly manipulating views, etc).
There are other potential solutions, but a lot of them depend on the exact situation. In particular, are you using the modern or legacy runtimes, are you fat or single architecture, 32 or 64 bit, what OS releases are you targeting, are you dynamically linking, statically linking, or do you have a choice, and is it potentially okay to do something that might require maintenance for new software updates.
If you are really desperate, what you could do is:
Not link against one of the libraries directly
Implement an alternate version of the objc runtime routines that changes the name at load time (checkout the objc4 project, what exactly you need to do depends on a number of the questions I asked above, but it should be possible no matter what the answers are).
Use something like mach_override to inject your new implementation
Load the new library using normal methods, it will go through the patched linker routine and get its className changed
The above is going to be pretty labor intensive, and if you need to implement it against multiple archs and different runtime versions it will be very unpleasant, but it can definitely be made to work.
Have you considered using the runtime functions (/usr/include/objc/runtime.h) to clone one of the conflicting classes to a non-colliding class, and then loading the colliding class framework? (this would require the colliding frameworks to be loaded at different times to work.)
You can inspect the classes ivars, methods (with names and implementation addresses) and names with the runtime, and create your own as well dynamically to have the same ivar layout, methods names/implementation addresses, and only differ by name (to avoid the collision)
Desperate situations call for desperate measures. Have you considered hacking the object code (or library file) of one of the libraries, changing the colliding symbol to an alternative name - of the same length but a different spelling (but, recommendation, the same length of name)? Inherently nasty.
It isn't clear if your code is directly calling the two functions with the same name but different implementations or whether the conflict is indirect (nor is it clear whether it makes any difference). However, there's at least an outside chance that renaming would work. It might be an idea, too, to minimize the difference in the spellings, so that if the symbols are in a sorted order in a table, the renaming doesn't move things out of order. Things like binary search get upset if the array they're searching isn't in sorted order as expected.
#compatibility_alias will be able to solve class namespace conflicts, e.g.
#compatibility_alias NewAliasClass OriginalClass;
However, this will not resolve any of the enums, typedefs, or protocol namespace collisions. Furthermore, it does not play well with #class forward decls of the original class. Since most frameworks will come with these non-class things like typedefs, you would likely not be able to fix the namespacing problem with just compatibility_alias.
I looked at a similar problem to yours, but I had access to source and was building the frameworks.
The best solution I found for this was using #compatibility_alias conditionally with #defines to support the enums/typedefs/protocols/etc. You can do this conditionally on the compile unit for the header in question to minimize risk of expanding stuff in the other colliding framework.
It seems that the issue is that you can't reference headers files from both systems in the same translation unit (source file). If you create objective-c wrappers around the libraries (making them more usable in the process), and only #include the headers for each library in the implementation of the wrapper classes, that would effectively separate name collisions.
I don't have enough experience with this in objective-c (just getting started), but I believe that is what I would do in C.
Prefixing the files is the simplest solution I am aware of.
Cocoadev has a namespace page which is a community effort to avoid namespace collisions.
Feel free to add your own to this list, I believe that is what it is for.
http://www.cocoadev.com/index.pl?ChooseYourOwnPrefix
If you have a collision, I would suggest you think hard about how you might refactor one of the frameworks out of your application. Having a collision suggests that the two are doing similar things as it is, and you likely could get around using an extra framework simply by refactoring your application. Not only would this solve your namespace problem, but it would make your code more robust, easier to maintain, and more efficient.
Over a more technical solution, if I were in your position this would be my choice.
If the collision is only at the static link level then you can choose which library is used to resolve symbols:
cc foo.o -ldog bar.o -lcat
If foo.o and bar.o both reference the symbol rat then libdog will resolve foo.o's rat and libcat will resolve bar.o's rat.
Just a thought.. not tested or proven and could be way of the mark but in have you considered writing an adapter for the class's you use from the simpler of the frameworks.. or at least their interfaces?
If you were to write a wrapper around the simpler of the frameworks (or the one who's interfaces you access the least) would it not be possible to compile that wrapper into a library. Given the library is precompiled and only its headers need be distributed, You'd be effectively hiding the underlying framework and would be free to combine it with the second framework with clashing.
I appreciate of course that there are likely to be times when you need to use class's from both frameworks at the same time however, you could provide factories for further class adapters of that framework. On the back of that point I guess you'd need a bit of refactoring to extract out the interfaces you are using from both frameworks which should provide a nice starting point for you to build your wrapper.
You could build upon the library as you and when you need further functionality from the wrapped library, and simply recompile when you it changes.
Again, in no way proven but felt like adding a perspective. hope it helps :)
If you have two frameworks that have the same function name, you could try dynamically loading the frameworks. It'll be inelegant, but possible. How to do it with Objective-C classes, I don't know. I'm guessing the NSBundle class will have methods that'll load a specific class.