C# style class extension in objective-c - objective-c

I'm just learning objective-c after a fair amount of experience with C#. One of the things I sorely miss is the ability to write extension methods in a separate project that I could reference in all of my projects. Here's some naive c#:
public static bool IsShortString(this string s) {
return s.length <= 3;
}
In Visual Studio, I could just add a reference, an using, and bam myString.IsShortString() would be a, rather useless, method.
So I think I want to write a static library, but I'm not sure where I'm going from there.
One additional question, if I do write this static library, will I be able to use all of the methods throughout various files in the library using one #import directive, or will I have to import each header individually?

What you are looking for is called Category, and it allows you to add some additional methods to existing classes. Check the reference http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/objectivec/chapters/occategories.html
You can create your own toolkit which is a static library containing categories you made. Common practice is to create one header file containing imports for all the headers in the lib, so when using it, you just do
#import "libName.h"
Also, when creating a static library containing categories it is important to include -all_load and -ObjC linker flags to your project.

The closest thing in objective-c is categories.
This is also a good tutorial on categories.

Related

What is a way to simplify linking multiple libraries in CMake?

I'm new to CMake and trying to learn to use it for a simple project. If I have a CMakeLists.txt file that looks like this:
add_executable(alpha alpha.cpp)
add_executable(beta beta.cpp)
add_library(one STATIC one.cpp)
add_library(two STATIC two.cpp)
target_link_libraries(alpha one)
target_link_libraries(alpha two)
target_link_libraries(beta one)
target_link_libraries(beta two)
Is there a way to simplify this sort of pattern? What I would like is to define something like all_libraries that contains both one and two, and then only have to do one linking per binary. Is there a way to do it?
You can use interface libraries:
add_library(all_libraries INTERFACE)
target_link_libraries(all_libraries
INTERFACE
one
two
)
... then later ...
target_link_libaries(alpha PUBLIC all_libraries)
You can use variable:
set(all_libraries one two)
.. then later ..
target_link_libraries(alpha PUBLIC ${all_libraries})
Notes:
I would advise to always explicit specify the the PUBLIC, PRIVATE and INTERFACE keywords.
I would go with interface libraries. It's nice to have a big project, expose different mix of libraries as a single interface library, than you only link another big project against that interface. Gives nice control and look of it.

Compile-time warning about missing category method implementation

In our Xcode project we have multiple targets which share some common code. Each target includes only sources which are actually used by it. So when we use some category methods inside classes which are shared between targets we need to make sure that this category implementation is also included in all targets. Xcode doesn't show any warnings during compile time or link time if we forget to include category implementation to some of the targets. And it is troublesome to do it by hand.
Is there any automated way to ensure that category implementations are included to the targets which use them?
Categories are not automatically linked to the final binary.
They are linked if the linker finds the file where they are defined is used (which was a source of constant bug some times ago).
What you can do is use a special flag on the linker: '-all_load' and '-ObjC' in Build Settings/Linking/Other Linker flags
-ObjC Loads all members of static archive libraries that implement an Objective-C class or category.
And from this discussion:
-all_load and -force_load tell the linker to link the entire static archive in the final executable, even if the linker thinks that parts
of the archive are unused.
Another way I use to force link the module is to put a C function in the file:
void _linkWithNBLogClass(void)
{
NSLog(#"%s", __FUNCTION__);
}
and call it at the start of my application:
linkWithNBLogClass();
This way, by the console feedback, I'm sure my module is loaded and ready to be used.
The described behavior is as intended and much existing code would break, if it is changed.
Prior to formal protocols there was a need to declare methods without defining them. This was for optional methods, i. e. for declaring a delegate API. The usual technique was to declare a so-called informal protocol, consisting of a category on NSObject that is never implemented.
But if you have a category implementation, of course the completeness of it is checked against the category interface. (Otherwise you get a "Method definition for X is not found" error.) So you do not have a missing method in the category implementation, but a missing category implementation.
I do not think that this is a big deal. You will get a runtime error instead of a compile time error and simply add the category implementation to the target.

How to make sure my reusable static library doesn't force my project to include multiple frameworks?

I try to put some reusable functions into my own static library but i noticed one problem.
Let's say the static library has many functions and some requires quartz core framework, some requires messgeUI etc.
When I build a new project, I include this static library project into my code so that I can reuse those functions.
Now even if I only use a simple function that doesn't require any frameworks, I am forced to include all the quartzcore, message UI frameworks or I will face build errors because the static library requires them- but I do not need all of them!
How can I design a better general purpose static library that doesn't force people to include frameworks that is not used by them at all?
You can use weak linking - if weak linkage is used, unused symbols (functions, methods, global variables) don't have to be present at linking time.

Using Objective-C Metadata to Generate Class Dependency Graph

This guy came up with a pretty neat tool to generate a class dependency graph - however, it relies on parsing your source code and looking for #import directives.
http://seriot.ch/blog.php?article=20110124
https://github.com/nst/objc_dep/blob/master/objc-dep.py
This is neat, but I have a number of problems with this. Not least of which is it doesn't take into account imports of imports nor prefix headers nor whether-or-not the class(es) in the file referenced by the import are actually being used.
I'd like to do something more akin to class-dump and examine the Objective-C metadata stored in the Mach-O file to generate an in-memory representation of the class dependencies.
I'd rather not do this from scratch, so I'm wondering:
Has it already been done?
Is there an open-source library which would provide me with the foundational tools I need to extract this information (a library which examines the Mach-O file and creates a façade of the Objective-C information contained within - such that I could iterate over all of the classes, their methods, properties, ivars, etc and scan for references to other classes) I figure class-dump's source would be a good place to start.
If you have experience in this sort of thing, is what I'm trying to accomplish feasible?
What roadblocks will I need to overcome?
Has it already been done?
Not that I know of.
Is there an open-source library which would provide me with the
foundational tools I need to extract this information?
At the core of class-dump is libMachObjC which does exatly what you want, i.e. parse all classes/methods/ivars and more. The API is very clean, it should be very easy to use.
If you have experience in this sort of thing, is what I'm trying to
accomplish feasible?
Unfortunately, no because some classes don't declare the real class but use id instead. For example, here is the information that can be extracted from a class-dump of UIKit:
#interface UITableView : UIScrollView <NSCoding>
{
int _style;
id <UITableViewDataSource> _dataSource;
id _rowData;
...
The _rowData ivar type information is id but if you check at runtime you will see that _rowData is an instance of the UITableViewRowData class. This information is not present in the Mach-O binary so you have no way to find the relation between UITableView and UITableViewRowData. The same applies for method parameters.
Here's a solution that relies on information in mach.o files, and generates graph dependency based on that information: https://github.com/PaulTaykalo/objc-dependency-visualizer
Has it already been done?
yes - but i can't recommend a good public implementation
Is there an open-source library which would provide me with the foundational tools I need to extract this information (a library which examines the Mach-O file and creates a façade of the Objective-C information contained within - such that I could iterate over all of the classes, their methods, properties, ivars, etc and scan for references to other classes) I figure class-dump's source would be a good place to start.
most use cases would benefit by using the objc runtime facilities objc/... rather than examining the binary.
If you have experience in this sort of thing, is what I'm trying to accomplish feasible?
yes. i've done something similar using the objc runtime.
What roadblocks will I need to overcome?
that depends largely on the level of detail you want... implementation time if you find no such implementation, but i figure you will find a few options if you google the more esoteric functions in the objc runtime; perhaps you would find one in an (open) language binding or bridge?
if you do end up writing one yourself, you can get registered objc classes using objc_getClassList, then access the properties/information you want from there.

Xcode and objective c shenanigans

Baby new to Xcode, Cocoa touch and iOS development in general. And am taking the Stanford walkthrough for their iPhone class. I am a little confused at a couple of places and need to shoot my doubts to you guys:
I have two classes that I have created for my model, essentially CalculatorBrain.m and CalculatorBrain.h.
From what I gather, in Objective C, creating a class essentially consists of two functions, one is to declare the class which contains the method/messages and other variables while the other is the actual implementation for the same. From this stems two questions:
Why must I declare a class without implementing it's methods at first? (the concept seems to be borrowed from interfaces) and only then move on to implementing it .
From the above question, as I go through the walkthrough, I notice that the class declaration took place in CalculatorBrain.h whereas the methods were actually implemented in CalculatorBrain.m. I am unable to grasp the nuances of why this was done so if anybody is willing to shed some light on this, it would really help
Thanks again,
Parijat Kalia!!!
These are traditions from the C world, and they're just common practice to avoid some problems. They aren't two classes, they are the definition (in the .h file) and the implementation (in the .c or .cc file).
If you defined the class in the .c file, you couldn't refer to it elsewhere because it wouldn't be defined. You could include your .c file, but then you'd have two copies of the code. You could also use the "extern" keyword, but at this point it's kind of odd.
If you put code in the .h file, then when it's included the code gets included. This means you can get compiler errors that you have three "getMyThing" functions.
This means you can give out your headers to others without giving away your top-secret implementation (useful for making libraries), include your header without worrying about the possible multiple definitions, etc. You can also add variables and functions in the .c file which people using the header (like your other code) can't see or use, so you don't have to worry about changing it later and having compilation break.