I've been working with layers for MapKit on the iPhone, and one library that I came across was this one: https://github.com/mtigas/iOS-MapLayerDemo/. It's very helpful, and seems to work fine. However, I'm trying to go through and understand a bit how it works, but I'm having some trouble.
On this page, for example: https://github.com/mtigas/iOS-MapLayerDemo/blob/master/MapLayerDemo/Classes/CustomOverlayView.m,
at the top, there are 4 custom functions defined. I assume these functions are adding on to the normal features of MKOverlayView? The thing is, I can't find where any of these new functions are actually called from, and thus I'm having some trouble understanding how this page works. It doesn't seem to be from any of the other files within the project.
I appreciate any help, thanks.
After some extended discussion with you in comments:
The override-able functions of MKOverlayView, such as canDrawMapRect cannot easily be traced back to their calling code because that code is obfuscated somewhere in the MapKit.framework.
Instead, the typical approach is to re-read their documentation until you get a mental picture of what the framework is using the function for. (There is such a thing as decompiling binaries, although that is generally frowned upon and I do not recommend it.)
canDrawMapRect documentation: http://developer.apple.com/library/ios/documentation/MapKit/Reference/MKOverlayView_class/Reference/Reference.html#//apple_ref/doc/uid/TP40009715-CH1-SW10
After reading their documentation, I inferred this: Somewhere in the MapKit.framework, canDrawMapRect is being called prior to actually drawing the view. If you didn't override that function in your subclass, it calls the super-class's default implementation, which always returns YES and then calls drawMapRect: (Which MUST be overridden if you are subclassing MKOverlayView, or else nothing will draw!)
The class you linked above potentially returns NO. In that particular case, it appears the code in MapKit.framework skips calling drawMapRect: and nothing is displayed (or refreshed).
So, long story short: for this case, you have to play code-detective and hope the documentation is written clearly enough to figure it out without being able to see all of the code.
Edit: Just to further clarify - It appears MKOverlayView must be subclassed to actually generate something visible.
My original answer before getting to your underlying question --
Short answer: Those are private functions for use within that class.
Long answer: Functions declared in an empty-name category at the top
of implementation files are visible only to the class the category is
extending. Thus, those functions can only be called within that
class's implementation. (C++ equivalent would just be declaring the
functions private)
3 of those 4 functions are called within that same .m file. Without
digging around, I'm guessing they wrote the first function and then
later decided to not use it.
Related
I know you can have #private member variables but is there someway to prevent code from calling the default init: method of your class and forcing code that creates and uses your objects to only use another initializer such as initWithOptions:
I have had a flick through some Objective-C books and didn't immediately see anything.
I have seen the stack overflow topic suggesting to throw exception, or assert/abort/whatever in how to prevent usage of other init methods other than my custom method in objective-c
and the use of the depreciated keyword
How do I flag a function as being deprecated in an iPhone Objective C header file?
Both of these seem somewhat less than elegant solutions, there is really no language orientated elegant way to say doesNotImplmentSelector in Objective-C...?
I come from a C++ background and just kind of expected something like the ability to hide the default constructor...
R.
I think the standard thing to do is to have an implementation of init which calls initWithOptions: with a default set of options.
I'm creating an app in which I do the same thing multiple times. I'm going for as little code as possible and I don't want to repeat myself.
I need the PHP equivalant of a reusable function, where I set an input, and the function will return the output.
The app is a URL shortener, so the input as you may assume is a URL, and the output is the short URL.
What's the best way to go about this? I know I can code the same thing twice, but I hate to repeat myself.
Hopefully I'm getting my point across. Any help is greatly appreciated.
-Giles
Apologies if I'm oversimplifying your question, but are you asking how to define an Objective-C method? If so, you're going to have to learn Objective-C, there's no way around it:
The Objective-C Programming Language - Object Messaging
You can do a lot of great things with no code on the iPhone and Mac platforms, but it's hard to imagine completing any useful application without writing some code.
Example
- (float)multiplyThisFloatByTwoPointFive:(float)numberToMultiply
{
return numberToMultiply * 2.5;
}
To call it:
[self multiplyThisFloatByTwoPointFive:3.7];
Libraries
If you mean "I want to put these non-class-specific methods somewhere I can access them universally", eg, a library, you can do this in two ways:
Create some sort of "library" class like "MySpecialMathClass" (not to be confused with "my special education math class") or "MyAppAnimationTricks" and put your methods there (you'd define them as +someMethod: not -someMethod:, class- not instance-method, per Objective-C).
If they only ever deal with primitives (such as int, float, double ...), consider just making them C functions, rather than Objective-C methods.
I am pretty much a newbie at this, but you can certainly write functions (as opposed to methods) in Objective C.
I wrote several utility functions recently. I created an NSObject file to place them in, but it has no ivars or methods declared, just the functions. Then implement the functions in the .m file, and import the .h file into any class file where you want the functions. You can obviously call these from anywhere in any .m file that has imported the function file.
John Doner
I want to create a big file for all cool functions I find somehow reusable and useful, and put them all into that single file. Well, for the beginning I don't have many, so it's not worth thinking much about making several files, I guess. I would use pragma marks to separate them visually.
But the question: Would those unused methods bother in any way? Would my application explode or have less performance? Or is the compiler / linker clever enough to know that function A and B are not needed, and thus does not copy their "code" into my resulting app?
This sounds like an absolute architectural and maintenance nightmare. As a matter of practice, you should never make a huge blob file with a random set of methods you find useful. Add the methods to the appropriate classes or categories. See here for information on the blob anti-pattern, which is what you are doing here.
To directly answer your question: no, methods that are never called will not affect the performance of your app.
No, they won't directly affect your app. Keep in mind though, all that unused code is going to make your functions file harder to read and maintain. Plus, writing functions you're not actually using at the moment makes it easy to introduce bugs that aren't going to become apparent until much later on when you start using those functions, which can be very confusing because you've forgotten how they're written and will probably assume they're correct because you haven't touched them in so long.
Also, in an object oriented language like Objective-C global functions should really only be used for exceptional, very reusable cases. In most instances, you should be writing methods in classes instead. I might have one or two global functions in my apps, usually related to debugging, but typically nothing else.
So no, it's not going to hurt anything, but I'd still avoid it and focus on writing the code you need now, at this very moment.
The code would still be compiled and linked into the project, it just wouldn't be used by your code, meaning your resultant executable will be larger.
I'd probably split the functions into seperate files, depending on the common areas they are to address, so I'd have a library of image functions separate from a library of string manipulation functions, then include whichever are pertinent to the project in hand.
I don't think having unused functions in the .h file will hurt you in any way. If you compile all the corresponding .m files containing the unused functions in your build target, then you will end up making a bigger executable than is required. Same goes for if you include the code via static libraries.
If you do use a function but you didn't include the right .m file or library, then you'll get a link error.
Currently I am making some decisions for my first objective-c API. Nothing big, just a little help for myself to get things done faster in the future.
After reading a few hours about different patterns like making categories, singletons, and so on, I came accross something that I like because it seems easy to maintain for me. I'm making a set of useful functions, that can be useful everywhere.
So what I did is:
1) I created two new files (.h, .m), and gave the "class" a name: SLUtilsMath, SLUtilsGraphics, SLUtilsSound, and so on. I think of that as kind of "namespace", so all those things will always be called SLUtils******. I added all of them into a Group SL, which contains a subgroup SLUtils.
2) Then I just put my functions signatures in the .h file, and the implementations of the functions in the .m file. And guess what: It works!! I'm happy with it, and it's easy to use. The only nasty thing about it is, that I have to include the appropriate header every time I need it. But that's okay, since that's normal. I could include it in the header prefix pch file, though.
But then, I went to toilet and a ghost came out there, saying: "Hey! Isn't it better to make real methods, instead of functions? Shouldn't you make class methods, so that you have to call a method rather than a function? Isn't that much cooler and doesn't it have a better performance?" Well, for readability I prefer the functions. On the other hand they don't have this kind of "named parameters" like methods, a.f.a.i.k..
So what would you prefer in that case?
Of course I dont want to allocate an object before using a useful method or function. That would be harrying.
Maybe the toilet ghost was right. There IS a cooler way. Well, for me, personally, this is great:
MYNAMESPACECoolMath.h
#import <Foundation/Foundation.h>
#interface MYNAMESPACECoolMath : NSObject {
}
+ (float)randomizeValue:(float)value byPercent:(float)percent;
+ (float)calculateHorizontalGravity:(CGPoint)p1 andPoint:(CGPoint)p2;
// and some more
#end
Then in code, I would just import that MYNAMESPACECoolMath.h and just call:
CGFloat myValue = [MYNAMESPACECoolMath randomizeValue:10.0f byPercent:5.0f];
with no nasty instantiation, initialization, allocation, what ever. For me that pattern looks like a static method in java, which is pretty nice and easy to use.
The advantage over a function, is, as far as I noticed, the better readability in code. When looking at a CGRectMake(10.0f, 42.5f, 44.2f, 99.11f) you'll may have to look up what those parameters stand for, if you're not so familiar with it. But when you have a method call with "named" parameters, then you see immediately what the parameter is.
I think I missed the point what makes a big difference to a singleton class when it comes to simple useful methods / functions that can be needed everywhere. Making special kind of random values don't belong to anything, it's global. Like grass. Like trees. Like air. Everyone needs it.
Performance-wise, a static method in a static class compile to almost the same thing as a function.
Any real performance hits you'd incur would be in object instantiation, which you said you'd want to avoid, so that should not be an issue.
As far as preference or readability, there is a trend to use static methods more than necessary because people are viewing Obj-C is an "OO-only" language, like Java or C#. In that paradigm, (almost) everything must belong to a class, so class methods are the norm. In fact, they may even call them functions. The two terms are interchangeable there. However, this is purely convention. Convention may even be too strong of a word. There is absolutely nothing wrong with using functions in their place and it is probably more appropriate if there are no class members (even static ones) that are needed to assist in the processing of those methods/functions.
The problem with your approach is the "util" nature of it. Almost anything with the word "util" it in suggests that you have created a dumping ground for things you don't know where to fit into your object model. That probably means that your object model is not in alignment with your problem space.
Rather than working out how to package up utility functions, you should be thinking about what model objects these functions should be acting upon and then put them on those classes (creating the classes if needed).
To Josh's point, while there is nothing wrong with functions in ObjC, it is a very strongly object-oriented language, based directly on the grand-daddy of object-oriented languages, Smalltalk. You should not abandon the OOP patterns lightly; they are the heart of Cocoa.
I create private helper functions all the time, and I create public convenience functions for some objects (NSLocalizedString() is a good example of this). But if you're creating public utility functions that aren't front-ends to methods, you should be rethinking your patterns. And the first warning sign is the desire to put the word "util" in a file name.
EDIT
Based on the particular methods you added to your question, what you should be looking at are Categories. For instance, +randomizeValue:byPercent: is a perfectly good NSNumber category:
// NSNumber+SLExtensions.h
- (double)randomizeByPercent:(CGFloat)percent;
+ (double)randomDoubleNear:(CGFloat)percent byPercent:(double)number;
+ (NSNumber *)randomNumberNear:(CGFloat)percent byPercent:(double)number;
// Some other file that wants to use this
#import "NSNumber+SLExtensions.h"
randomDouble = [aNumber randomizeByPercent:5.0];
randomDouble = [NSNumber randomDoubleNear:5.0 byPercent:7.0];
If you get a lot of these, then you may want to split them up into categories like NSNumber+Random. Doing it with Categories makes it transparently part of the existing object model, though, rather than creating classes whose only purpose is to work on other objects.
You can use a singleton instance instead if you want to avoid instantiating a bunch of utility objects.
There's nothing wrong with using plain C functions, though. Just know that you won't be able to pass them around using #selector for things like performSelectorOnMainThread.
When it comes to performance of methods vs. functions, Mike Ash has some great numbers in his post "Performance Comparisons of Common Operations". Objective-C message send operations are extremely fast, so much so that you'd have to have a really tight computational loop to even see the difference. I think that using functions vs. methods in your approach will come down to the stylistic design issues that others have described.
Optimise the system, not the function calls.
Implement what is easiest to understand and then when the whole system works, profile it and speed up what's slow. I doubt very much that the objective-c runtime overhead of a static class is going to matter one bit to your whole app.
How would you define "unwanted code"?
Edit:
IMHO, Any code member with 0 active calling members (checked recursively) is unwanted code. (functions, methods, properties, variables are members)
Here's my definition of unwanted code:
A code that does not execute is a dead weight. (Unless it's a [malicious] payload for your actual code, but that's another story :-))
A code that repeats multiple times is increasing the cost of the product.
A code that cannot be regression tested is increasing the cost of the product as well.
You can either remove such code or refactor it, but you don't want to keep it as it is around.
0 active calls and no possibility of use in near future. And I prefer to never comment out anything in case I need for it later since I use SVN (source control).
Like you said in the other thread, code that is not used anywhere at all is pretty much unwanted. As for how to find it I'd suggest FindBugs or CheckStyle if you were using Java, for example, since these tools check to see if a function is used anywhere and marks it as non-used if it isn't. Very nice for getting rid of unnecessary weight.
Well after shortly thinking about it I came up with these three points:
it can be code that should be refactored
it can be code that is not called any more (leftovers from earlier versions)
it can be code that does not apply to your style-guide and way-of-coding
I bet there is a lot more but, that's how I'd define unwanted code.
In java i'd mark the method or class with #Deprecated.
Any PRIVATE code member with no active calling members (checked recursively). Otherwise you do not know if your code is not used out of your scope analysis.
Some things are already posted but here's another:
Functions that almost do the same thing. (only a small variable change and therefore the whole functions is copy pasted and that variable is changed)
Usually I tell my compiler to be as annoyingly noisy as possible, that picks 60% of stuff that I need to examine. Unused functions that are months old (after checking with the VCS) usually get ousted, unless their author tells me when they'll actually be used. Stuff missing prototypes is also instantly suspect.
I think trying to implement automated house cleaning is like trying to make a USB device that guarantees that you 'safely' play Russian Roulette.
The hardest part to check are components added to the build system, few people notice those and unused kludges are left to gather moss.
Beyond that, I typically WANT the code, I just want its author to refactor it a bit and make their style the same as the rest of the project.
Another helpful tool is doxygen, which does help you (visually) see relations in the source tree.. however, if its set at not extracting static symbols / objects, its not going to be very thorough.