What is the standard way of incorporating helper/utility functions in Obj-C classes?
I.e. General purpose functions which are used throughout the application and called by more than 1 class.
Can an Obj-C method exist outside of a class, or does it need to be a C function for it to have this kind of behaviour?
I would group similar functions as static methods in a helper class. These can then be called using the classname rather the instance name. Static methods are defined with a + instead of the usual -.
like so:
#interface HelperClass: superclassname {
// instance variables - none if all methods are static.
}
+ (void) helperMethod: (int) parameter_varName;
#end
This would be called like so.
[HelperClass helperMethod: 10 ];
As this is static you do not init/alloc the class. This has the advantage of clearly grouping like Helper functions. You could use standalone C functions but as your Application gets larger it can become a right mess! Hope this helps.
Tony
I don't see why people are avoiding creating functions. Objective-C is a superset of C, which means that C is part of it. Moreover, it's completely integrated—there's no wall between them.
Create functions! It's fine! Foundation does it. Application Kit does it. Core Animation does it. Core Media does it.
I see no reason not to.
There are a number of options for this in Objective-C. First, since Obj-C is a strict superset of C, you can define all your library functions in a separate module (source file) and happily call them from any Obj-C object/code you already have. If you create an obj-c source file (.m file) you can then call back into/use objects.
If your generic functions are logically manipulating other, established objects (for instances, operates on an NSString), you can use categories to graph your functions on already existing classes (where that makes sense).
Finally, as Tony points out, you can create classes with static methods (although I like this option the least, personally). I tend to use a mix of one an two... adding categories where appropriate and using standard functions for others. I generally only make a new class where it makes sense to design a class.
Related
I need to find a way to tell the C compiler of my program that a certain structure is the same as the other structure (they are identical in definition). I figured casting would be decent enough, but maybe its not a good idea?
The reason that I am not just using one struct is because the structs are defined in very heavy framework classes and I have a lot of different classes of my own importing the class that requires the use of the structure in it's .h.
So, how can I tell the compiler that Struct A can be used for a function requiring Struct B, given that they are identical, if it is even possible?
To make this very specific, in my case, I have a singleton that is accessed and utilized by around 14 classes. Some of the functions in the singleton work alongside the other classes and provide resources and data for their specific imports. One of which is the MapKit framework. There are a number of structs within the MapKit framework that I have been utilizing (especially MKUserLocation.h), but will import a number of other classes and add on a lot to the definition.
A specific example for me is using CLLocationCoordinate2D, which I have had to recreate in my singleton so that not all 14 classes import from the MapKit framework. It just seems excessive.
I know how to make this all work, but there should be a good solution to this other than casting or importing to everything.
Can you simply write a global function to convert from one struct to another?
void OneStructToAnotherStruct( struct FromStruct* from, struct ToStruct* to )
{
to->x = from->x;
to->y = from ->y;
to->z = from->z;
}
I left the original, so people can understand the context for the comments. Hopefully, this example will better help explain what I am after.
Can I create a class in Obj-C that has file-scope visibility?
For example, I have written a method-sqizzling category on NSNotificationCenter which will automatically remove any observer when it deallocs.
I use a helper class in the implementation, and to prevent name collision, I have devised a naming scheme. The category is NSNotificationCenter (WJHAutoRemoval), so the private helper class that is used in this code is named...
WJH_NSNotification_WJHAutoRemoval__Private__BlockObserver
That's a mouthful, and currently I just do this...
#define BlockObserver WJH_NSNotification_WJHAutoRemoval__Private__BlockObserver
and just use BlockObserver in the code.
However, I don't like that solution.
I want to tell the compiler, "Hey, this class is named Bar. My code will access it as Bar, but I'm really the only one that needs to know. Generate a funky name yourself, or better yet, don't even export the symbol since I'm the only one who should care."
For plain C, I would is "static" and for C++ "namespace { }"
What is the preferred/best/only way to do this in Obj-C?
Original Question
I want to use a helper class inside the implementation of another. However, I do not want external linkage. Right now, I'm just making the helper class name painfully unique so I will not get duplicate linker symbols.
I can use static C functions, but I want to write a helper class, with linker visibility only inside the compilation unit.
For example, I'd like to have something like the following in multiple .m files, with each "Helper" unique to that file, and no other compilation unit having linker access. If I had this in 10 different files, I'd have 10 separate classes.
#interface Helper : NSObject
...
#end
#implementation Helper : NSObject
...
#end
I have been unable to find even a hint of this anywhere, and my feeble attempts at prepending "static" to the interface/implementation were wrought with errors.
Thanks!
I don't believe you will be able to do what you want because of the Objective-C Runtime. All of your classes are loaded into the runtime and multiple classes with the same name will conflict with each other.
Objective-C is a dynamic language. Unlike other languages which bind method calls at compile time, Objective-C does method resolution at invocation (every invocation). The runtime finds the class in the runtime and then finds the method in the class. The runtime can't support distinct classes with the same name and Objective-C doesn't support namespaces to seperate your classes.
If your Helper classes are different in each case they will need distinct class names (multiple classes with the same name sounds like a bad idea to me, in any language). If they are the same then why do you want to declare them separately.
I think you need to rethink your strategy as what you are trying to do doesn't sound very Objective-C or Cocoa.
There's no way to make a class "hidden." As mttrb notes, classes are accessible by name through the runtime. This isn't like C and C++ where class are just symbols that are resolved to addresses by the linker. Every class is injected into the class hierarchy.
But I'm unclear why you need this anyway. If you have a private class WJHAutoRemovalHelper or whatever, it seems very unlikely to collide with anyone else any more than private Apple classes or private 3rdparty framework classes collide. There's no reason to go to heroic lengths to make it obscure; prefixing with WJHAutoRemoval should be plenty to make it unique. Is there some deeper problem you're trying to fix?
BTW as an aside: How are you implementing the rest of this? Are you ISA-swizzling the observer to override its dealloc? This seems a lot of tricky code to make a very small thing slightly more convenient.
Regarding the question of "private" classes, what you're suggesting is possible if you do it by hand, but there really is no reason for it. You can generate a random, unique classname, call objc_allocateClassPair() and objc_registerClassPair on it, and then assign that to a Class variable at runtime. (And then call class_addMethod and class_addIvar to build it up. You can then always refer to it by that variable when you need it. It's still accessible of course at runtime by calling objc_getClassList, but there won't be a symbol for the classname in the system.
But this is a lot of work and complexity for no benefit. ObjC does not spend much time worrying about protecting the program from itself the way C++ does. It uses naming conventions and compiler warning to tell you when you're doing things wrong, and expects that as a good programmer you're going to avoid doing things wrong.
What advantage is there, if any, to using Modules rather than classes in VB? How do they differ, and what advantages/disadvantages are there in using modules? In VB or VB.NET, I use both.
(A) Modules
and
(B) Classes with only Shared functions
solve the same problem: Both allow you to logically group a set of functions.
Advantages of using a module:
It allows you to define extension methods.
For someone reading your code, it is immediately obvious that this is not a class representing a group of stateful objects but just a "function container".
Advantages of using a class with shared functions:
It's easy to extend it with instance (= non-shared) variables, functions and properties later on.
So, if you are writing a set of helper functions and want to logically group them (where the concept of a state of this group just doesn't make sense), use a module -- this is exactly what they are here for. On the other hand, if you have a function that conceptually fits to an already existing class, add it as a shared function to that class.
A major difference is that methods in modules can be called globally whereas methods in classes can't. So instead of ModuleName.MyMethod() you can just call MyMethod(). Whether that is an advantage or disadvantage depends on the circumstances.
Module are come earlier and now VB.NET just let it for backward compatibility. Modules and Class are nearly same. You can call Module.Function() directly as it treat as Shared Function in a class. Class you can define Shared Function/Method and additionally can create an instance like Dim c as Class = New Class().
Avoid use of Module, instead use Class. it is good for you to write a better OOP programming.
This question already has answers here:
What is reflection and why is it useful?
(23 answers)
Closed 6 years ago.
I was just curious, why should we use reflection in the first place?
// Without reflection
Foo foo = new Foo();
foo.hello();
// With reflection
Class cls = Class.forName("Foo");
Object foo = cls.newInstance();
Method method = cls.getMethod("hello", null);
method.invoke(foo, null);
We can simply create an object and call the class's method, but why do the same using forName, newInstance and getMthod functions?
To make everything dynamic?
Simply put: because sometimes you don't know either the "Foo" or "hello" parts at compile time.
The vast majority of the time you do know this, so it's not worth using reflection. Just occasionally, however, you don't - and at that point, reflection is all you can turn to.
As an example, protocol buffers allows you to generate code which either contains full statically-typed code for reading and writing messages, or it generates just enough so that the rest can be done by reflection: in the reflection case, the load/save code has to get and set properties via reflection - it knows the names of the properties involved due to the message descriptor. This is much (much) slower but results in considerably less code being generated.
Another example would be dependency injection, where the names of the types used for the dependencies are often provided in configuration files: the DI framework then has to use reflection to construct all the components involved, finding constructors and/or properties along the way.
It is used whenever you (=your method/your class) doesn't know at compile time the type should instantiate or the method it should invoke.
Also, many frameworks use reflection to analyze and use your objects. For example:
hibernate/nhibernate (and any object-relational mapper) use reflection to inspect all the properties of your classes so that it is able to update them or use them when executing database operations
you may want to make it configurable which method of a user-defined class is executed by default by your application. The configured value is String, and you can get the target class, get the method that has the configured name, and invoke it, without knowing it at compile time.
parsing annotations is done by reflection
A typical usage is a plug-in mechanism, which supports classes (usually implementations of interfaces) that are unknown at compile time.
You can use reflection for automating any process that could usefully use a list of the object's methods and/or properties. If you've ever spent time writing code that does roughly the same thing on each of an object's fields in turn -- the obvious way of saving and loading data often works like that -- then that's something reflection could do for you automatically.
The most common applications are probably these three:
Serialization (see, e.g., .NET's XmlSerializer)
Generation of widgets for editing objects' properties (e.g., Xcode's Interface Builder, .NET's dialog designer)
Factories that create objects with arbitrary dependencies by examining the classes for constructors and supplying suitable objects on creation (e.g., any dependency injection framework)
Using reflection, you can very easily write configurations that detail methods/fields in text, and the framework using these can read a text description of the field and find the real corresponding field.
e.g. JXPath allows you to navigate objects like this:
//company[#name='Sun']/address
so JXPath will look for a method getCompany() (corresponding to company), a field in that called name etc.
You'll find this in lots of frameworks in Java e.g. JavaBeans, Spring etc.
It's useful for things like serialization and object-relational mapping. You can write a generic function to serialize an object by using reflection to get all of an object's properties. In C++, you'd have to write a separate function for every class.
I have used it in some validation classes before, where I passed a large, complex data structure in the constructor and then ran a zillion (couple hundred really) methods to check the validity of the data. All of my validation methods were private and returned booleans so I made one "validate" method you could call which used reflection to invoke all the private methods in the class than returned booleans.
This made the validate method more concise (didn't need to enumerate each little method) and garuanteed all the methods were being run (e.g. someone writes a new validation rule and forgets to call it in the main method).
After changing to use reflection I didn't notice any meaningful loss in performance, and the code was easier to maintain.
in addition to Jons answer, another usage is to be able to "dip your toe in the water" to test if a given facility is present in the JVM.
Under OS X a java application looks nicer if some Apple-provided classes are called. The easiest way to test if these classes are present, is to test with reflection first
some times you need to create a object of class on fly or from some other place not a java code (e.g jsp). at that time reflection is useful.
Most likely an OO concept question/situation:
I have a library that I use in my program with source files available. I've realized I need to tailor the library to my needs, say I need to modify the behavior of a single functions F in class C, while leaving the original library's source intact, to be able to painlessly upgrade it when needed.
I realize I can make my own class C1 inherited from C, place it in my source tree, and write the function F how I see it fit, replacing all occurrences of
myObj = new C();
with
myObj = new C1();
throughout my code.
What is the 'proper' way of doing this? I suspect the inheritance method I described has problems, as the library in its internals would still use C::F instead of my C1::F, and it would be way cooler if I could still refer to C::F not some strange C1::F in my code.
For those that care - the language is PHP5, and I'm kinda OOP newbie :)
I think subclassing is pretty much the best way to add functionality to an external library.
The alternative is the decorator pattern whereby you have to wrap every method of the C class. (There is a time and place for the decorator pattern, but I think this isn't it)
You say:
as the library in its internals would still use C::F instead of my C1::F
Not necessarily true. If you pass an instance of the C1 class to a library function, then any calls to method F of that object would still go through your C1::F method. The same also happens when the C class accesses its own method by calling $this->F() -- because it's still a C1 object. This property is called polymorphism
Of course this does not apply when the library's code itself instantiates a new object of class C.