I'm on a project doing an iPhone application. We had a Cocoa consultant come in for a few weeks. He showed me an interesting idiom of Cocoa, dealing with interfaces, but there was a difficult language barrier between us, and he wasn't really able to explain why this was done or where it was documented so I could learn more on my own. I went into monkey see mode, and just used the style he prefers. But it's been bugging the hell out of me that I don't know more about the history of this style. It's certainly NOT an informal protocol. Sure enough, looking at some of the Cocoa API headers, I sometimes see the style he asserted was the 'Cocoa' way. Here's an example (note accessors, mutators, etc., each have their own interface declaration without the funny braces):
#interface AViewController : UIViewController <UITextViewDelegate> {
#public
UITableView *tableView;
#private
NSUInteger someIndex;
}
#property (nonatomic, retain) ...
#end
#interface AViewController (AViewControllerCreation)
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil withController:(id)controller;
#end
#interface AViewController (AViewControllerMutator)
- (void) doSomeSettingStuff;
#end
#interface AViewController (AViewControllerAccessor)
- (NSString *)doSomeAccessorStuff;
#end
#interface AViewController (AViewControllerAction)
- (IBAction)cancel:(id)sender;
#end
#interface AViewController (AViewControllerTableViewDelegate) <UITableViewDelegate, UITableViewDataSource>
#end
You can see this style of setting up the interface in NSButton, NSControl, etc. Interestingly, corresponding classes like UIButton, UIControl DON'T use this idiom. Hmm, these probably came after as I assume UIKit was done after AppKit. So is this idiom 'old hat'? Also, is there any reason for it other then style? Is it good style? Bad? Any docs that go over this? Thanks all.
These are what's known in Objective-C as "categories". Categories make it possible to have multiple #interface and #implementation blocks for the same class. This works even to the extent that you can add methods on classes in the standard Apple frameworks, e.g. adding a category on NSString to add new methods to it. Categories can add methods but not instance variables, so in your example the first #interface is the core class declaration and all of the others are categories on the AViewController class.
It's not "old hat" by any means but your example takes the use of categories to a rather bizarre extreme. Categories make sense wherever it makes logical sense to break up a class's implementation into multiple blocks, for example if the class has a bunch of methods that logically fall into two or more groups. They're also sometimes used to declare pseudo-private methods by putting a category #interface named "private" in the same file as the #implementation. ObjC's dynamic dispatch means there's no such thing as a private method but this approach avoids publishing the names of methods you'd prefer people not to use.
The example above is not actually wrong but it's kind of ridiculous. It suggests that the contractor got the idea that every new method should always have its own category for some reason, which is just not true.
That example is very strange and would definitely raise a red flag for any experienced Cocoa programmer.
It is a common practice to use categories in the same way to separate private methods from the public implementation, and I've done the same thing in the past to separate private threaded methods from code that runs on the main thread. I can't see any good that would come from separating out all your public methods like that though.
What is a good tool for this situation is the #pragma mark <label> keyword. which allows you to group similar methods in an implementation. I think that's what you're aiming for, although you don't need to go overboard in creating groups. For example, in a window controller class I would have #pragma mark API, #pragma mark NSWindowController Overrides, #pragma mark NSObject Overrides, #pragma mark NSWindow Delegate Methods, and so on. That helps me find and jump to the method I'm looking for very quickly in Xcode, although it's just a matter of style so you can really use it however you see fit.
One really good reason for having a public category, and one that Apple uses often, is for extending a class with functionality that exists in the category's framework, but which doesn't exist in the framework that defines the class. For example, NSString is defined in Foundation.framework, but categories on NSString defining methods for drawing an NSString to the screen are defined in AppKit.framework.
Another good usage of categories is for dependency hiding; e g if you really need boost for a part of the class, you can have that in a separate header and implementation file, and a user of the class that needs the boost parts can import that header together with the one originally defining the class, and only that file will take ages to compile. This is more useful in the 64-bit runtime, where a category can add instance variables.
A really large implementation over several source files (but a single header) is also a good candidate, as Tom points out :)
I'd just like to add to Tom's original answer: Generally, it's better to use a class extension than a class category when declaring private methods. This way, you can implement the extension in the same #implementation block as the public methods, without getting a warning about "missing category implementation". Example:
// .h file
#interface Foo : NSObject
-(void)publicMethod;
#end
// .m file
#interface Foo ()
// Notice the empty paren; this is how you define
// a class extension, which is not the same as a category
-(void)somePrivateMethod;
#end
#implementation Foo
#pragma mark Public methods
-(void)publicMethod;
{ ... }
#pragma mark Private methods
-(void)privateMethod;
{ ... }
#end
I don't know; those look a lot like informal protocols to me, largely for delegates. See pages 297 - 298 of Cocoa Programming with Mac OS X, 3rd Edition. The protocols are implemented via Categories ... And in all honesty, they appear to be heavily overused in your sample.
Regarding John Rudy's response-- It's true that informal protocols are implemented as categories, but they're generally categories on NSObject. Since the informal protocol might be used by almost any object, it needs to be a category on an class that the adopting object inherits from, and pretty much everything is going to inherit from NSObject. You could make a case for an informal protocol as a category on some other class in specific situations, but it's an unusual approach and definitely not "the Cocoa way"
Ok, I believe Tom's answer is the most useful so far. However, as everyone seems to think this an overboard use of categories I again took a look at NSButton. Below is a bastardized version of the header:
#interface NSButton : NSControl <NSUserInterfaceValidations>
- (NSString *)title;
- (void)setTitle:(NSString *)aString;
...
...
#end
#interface NSButton(NSKeyboardUI)
- (void)setTitleWithMnemonic:(NSString *)stringWithAmpersand;
#end
#interface NSButton(NSButtonAttributedStringMethods)
- (NSAttributedString *)attributedTitle;
- (void)setAttributedTitle:(NSAttributedString *)aString;
- (NSAttributedString *)attributedAlternateTitle;
- (void)setAttributedAlternateTitle:(NSAttributedString *)obj;
#end
#interface NSButton(NSButtonBezelStyles)
- (void) setBezelStyle:(NSBezelStyle)bezelStyle;
- (NSBezelStyle)bezelStyle;
#end
#interface NSButton(NSButtonMixedState)
- (void)setAllowsMixedState:(BOOL)flag;
- (BOOL)allowsMixedState;
- (void)setNextState;
#end
#interface NSButton(NSButtonBorder)
- (void) setShowsBorderOnlyWhileMouseInside:(BOOL)show;
- (BOOL) showsBorderOnlyWhileMouseInside;
#end
#interface NSButton (NSButtonSoundExtensions)
- (void)setSound:(NSSound *)aSound;
- (NSSound *)sound;
#end
So if their using categories to organize NSButton into sections: (NSButtonMixedState) (NSButtonBorder) above, that really only have a couple of operations, why is using this for organizing accessors/mutators bad style? Of course my first example was a silly pedantic interface, but the intent of separating groupings of operations is the same.
First of all, just because something appears in one of Apple's header files doesn't necessarily mean you should take it as an example of a good way to do things. Apple's developers are human too, and subject to the same limitations of skill and time pressures as anyone else.
Using multiple categories in this way suggests that NSButton's implementation is divided into several source files. This might be because the different aspects of NSButton were coded by different people, or at different times, or possibly some other reason. Regardless the division is likely based in part on how the development team and its processes are organized, with the category system providing a way for the work to be divided. In the ideal setup you'd break things up on logical functional boundaries but in practice other factors can come into play.
Related
All my research shows that there's no real usage for the #private directive - so I must be missing something and need you experts to chime in :-)
Assume we have 2 classes: a Car class and a SportsCar class, where SportsCar is a subclass of Car.
Here's the Car class:
#interface Car : NSObject {
NSString *make;
NSString *model;
#private
int numberOfBackSeatPassengers; // I'm making this a private iVar cause I'm just gonna
// say that all Sportscars will be 2-seaters and therefore shouldn't
// be able to set/get the number of back-seat passengers
}
#property (nonatomic, strong) NSString *make, *model;
// Now here's my first issue: if I also make "numberOfBackSeatPassengers" an #property
// then it seems like all subclasses of this Car class *WILL* be able to access it as
// well - even though I declared it as #private - but I'll do this anyway to make my point:
#property int numberOfBackSeatPassengers;
#end
The Implementation looks like this:
#implementation Car
#synthesize make, model, numberOfBackSeatPassengers;
#end
Now here's the Sportscar class:
#import "Car.h"
#interface Sportscar : Car
#property int turboEngineSize;
#end
And its implementation:
#import "Sportscar.h"
#implementation Sportscar
#synthesize turboEngineSize;
#end
In "main" I have this:
Car *car1 = [[Car alloc] init];
[car1 setMake:#"Chevy"];
[car1 setModel:#"Impala"];
[car1 setNumberOfBackSeatPassengers:3];
Sportscar *sports1 = [[Sportscar alloc] init];
[sports1 setMake:#"Audi"];
[sports1 setModel:#"tt"];
[sports1 setNumberOfBackSeatPassengers:3];
Obviously I'm able to set the NumberOfBackSeatPassengers on the Sportscar - even though that iVar was declared as #private - but that's because I made it an #property in "Car.h" which means that the synthesized getter and setter for it are Instance Methods, thereby available to all subclasses of Car.
The other option would have been to NOT declare numberOfBackSeatPassengers as an #property in "Car.h", keep it there as only a simple iVar, and instead manually create a Setter and Getter for it in the #implementation of "Car.m" like this:
-(void) setNumberOfBackSeatPassengers:(int)numPassgeners {
numberOfBackSeatPassengers = numPassgeners;
}
-(int)numberOfBackSeatPassengers {
return numberOfBackSeatPassengers;
}
This would have made the getter and setter for numberOfBackSeatPassengers available only within "Car.m" - which I suppose would make them "private" - but they'd be too private: I could never call them from Main, or from anywhere outside of "Car.m" Moreover, and this is the real point: doing it this way means the #private directive back in "Car.h" doesn't really come into play at all in any of this. I mean I could now go back to "Car.h", take out the "#private" directive there -- and my manual setter and getter for numberOfBackSeatPassengers would still work exactly the same as they are now, being supposedly private - so what's to be gained with "#private"? How does it truly come into play?
Can anyone shed any real light on this?
(And yes, I know I can extend my Car class in the #interface section of the "Car.m" file - through a category, or make numberOfBackSeatPassengers a readonly property first, then change it to readwrite, etc. - but these all seem like workarounds or "hacks" to making "#private" work. I just don't get how #private truly works on its own.)
=====================================================
EDIT - in response to aroth's comments below:
1) aroth's absolutely correct in saying that a subclass could still theoretically call a method that was NOT declared in its parent class's Header -- by using performSelector. I say "theoretically", cause in my case its not quite working correctly: if - in "main" - I call
[sportscar1 performSelector:#selector(setNumberOfBackSeatPassengers:)];
then I get some junk number inserted for numberOfBackSeatPassengers cause I can't explicitly pass-in a number as an argument when calling the method this way.
(Question: is there a way around this?)
2) aroth's also absolutely right in saying that in Sportscar we can simply override the Car class's setter and getter for numberOfBackSeatPassengers, and have these overriding methods reset it to 0, or give an error, etc. But while this is a very practical solution and seems to solve this particular problem, I feel like it doesn't address the larger issue of #private not really seeming to do what it ought to do.
3) Redesigning the logic to have a class for FourDoorCar and another one for TwoDoorCar and then continue building off of that is an interesting option - but that almost feels like now Objective-C's syntax is "forcing" itself on my programming logic and how I'm structuring my very project - and this feels like quite an imposition. Maybe I'm wrong and making too much out of this - but either way this all came about just because the #private isn't doing what it seems to promise...? Doesn't feel right.
At the end of the day I keep coming back to the same question: what good does #private actually do us? What benefits does it have, what does it "buy" me? It seems that if I want to have an iVar be private, I can just declare it in the ".m" file and not ever bother declaring it in the Header file in the first place. I mean am I right about this or not? or is there still some instance where you'd want to declare an iVar in the Header as #private, but not declare a setter and getter for it there in the Header - so those won't be explicitly available to subclasses - and have it all make sense?
Can we think of an actual example for this? Is there some sort of Car property that I'd want to declare as #private in the Header (as opposed to in the ".m") that would somehow benefit me?
I thought numberOfBackSeatPassengers would be a good example, but I'm not seeing how it'd really work in action, in actual code...
=========================================================================
EDIT #2 - Continuing the dialogue with #aroth :-)
#aroth - I absolutely agree that its much better/more organized to declare all iVars in the Header and not split things up so that some are in the Header and some are in the Implementation. That creates a mess and I really dislike that approach. (I noted in my original question that I don't want to use the Implementation and/or Category approach to address my question.)
-Also, yes, properties absolutely don't always have to be backed up by iVars.
-Regarding designing the Class appropriately, I concur that that of course is the key to good programming. The Car/Sportscar example is something I made up on the spot to give my question some context and I didn't invest any time considering its design merits/flaws. I think if we were to take your approach however - which seems quite logical for sure - and go with a Car class, a FourDoorCar subclass, a TwoDoorCar subclass, etc. - we could solve a lot of problems - but its still very likely that sooner or later we'll run into a situation where we'd perhaps want an #private iVar for one of our classes, and not want to create another subclass to deal with it.
I mean lets just assume that this would happen, for the sake of this discussion.
And so, if possible, I'd really like to think of a specific iVar for our Car class that it would make sense to have as #private, show in code how to use it, and discuss its scope and limitations.
I keep trying to think of a real-world example of some property of a Car that we would want only the Car to have - and that none of its subclasses should inherit.
I really thought numBackSeatPassengers would do the trick - and for the purposes of our discussion it still can, but, I'll just make up another one and call it phantomIVar :-)
And so:
#interface Car : NSObject {
#private
//int numberOfBackSeatPassengers;
int phantomIVar;
}
#property (nonatomic, strong) NSString *make, *model;
#end
The Implementation would be:
#implementation Car
#synthesize make, model;
-(void) setPhantomIVar:(int)i {
phantomIVar = i;
}
-(int)phantomIVar {
return phantomIVar;
}
#end
Which pretty much puts us back where we started :-)
At least that's how I feel.
I mean the only thing that the #private declaration seems to buy us is readability. So that now, anyone looking at the Header will be able to see that phantomIVar is an iVar of Car, and understand that its private. That's it.
In terms of functionality however, it didn't seem to do much. Cause its not like putting #private in front of phantomIVar freed us up to still be able write a setter/getter for it in the Header and have those be only accessible to Car class objects and not subclasses of Car. No, #private doesn't get you that. To get privacy you'd have to go in the Implementation file and write your setter and getter there. And ultimately in Objective-C there's no such thing as private methods. In Obj. C. they're all public.
aroth, please let me know if I got this right - and if not, where exactly I went wrong.
Many thanks :-)
This would have made the getter and setter for
numberOfBackSeatPassengers available only within "Car.m"
Not true. Those methods would still exist on every instance of Car and every instance of every object that extends Car, whether or not you declare them in your header file. The compiler wouldn't treat them as publicly visible and would complain if you tried to call them directly, but you'd still be able to call your getter and setter on any subclass of Car simply by using performSelector:.
In any case, if you have a #property there's no point is using #private on the ivar that backs it (and there's also no point in having an explicit ivar backing it, one will be created automatically for you when you use #synthesize; but that's a separate topic). I'd suggest that if SportsCar is meant to extend Car and never allow any backseat passengers to be recorded that the 'standard' way to do that would be to simply override the getter/setter methods in SportsCar to either always set/return 0 or to raise some error if an attempt is made to set a nonzero value.
Another option, since this property does not apply to all Car instances is to take it out of the base class entirely. You could, for example, have Car, and then derived from that have TwoDoorCar and FourDoorCar, and then have SportsCar be derived from TwoDoorCar. In this case you could declare numberOfBackSeatPassengers as a public property of FourDoorCar, as every four-door car should be able to accommodate passengers in the back seat.
To get back to the original question being asked, using #private on an ivar affects only the visibility of that ivar. It does not affect methods which make use of the ivar. So a subclass of Car will not be able to see the numberOfBackSeatPassengers ivar itself. But since you've created a public getter/setter for it, the subclass will of course be able to see those, and use them to modify the value of the ivar.
Edit
To briefly answer the updated question(s):
Yes, you can use NSInvocation to dynamically invoke a method that requires primitive parameters. Or you can use the approach discussed here, which is even more straightforward: Objective-C and use of SEL/IMP. Or you can use a NSNumber instead of an int and then use performSelector:withObject:.
I'm not sure what you're saying #private should be doing in this case. What is it that you think using #private should do?
I think this has less to do with syntax and more to do with principles of object-oriented design. If some cars do not have a back seat, then it is not really good object-oriented design to give the Car superclass a numberOfBackseatPassengers property. Doing that gives the object a field that does not actually apply to every instance of the object type. And when you start doing that you run into exactly the sort of problems you describe in your example. The purpose of a superclass is to contain functionality that is common to all of its derived types. If it has functionality that is common only to some of its derived types, then that is usually a design problem. In any case, it has nothing to do with Objective-C syntax or semantics.
As for what #private gets you, how about simplified organization of your class, for one thing? Yes you can declare an ivar in your implementation file to accomplish a similar effect, but is that really as convenient as having all the ivars declared in the header? On a reasonably complex project, will other developers be able to follow your code as easily if only some ivars are declared in the header and the rest are in the implementation file?
Without #private/#protected every ivar declared in a header would be public, which is definitely not good in an object-oriented environment for all the reasons Jonathan pointed out. So these access modifiers probably exist, first and foremost, to solve this issue.
As for use-cases, properties with getters/setters are probably not the best example. The purpose of getters/setters is virtually always to provide a public interface for modifying/querying the property value, and as noted in Objective-C it's not necessary to explicitly declare an ivar, in any scope, to back a synthesized property.
A better example may be IBOutlet's. You want these declared in your header so that XCode/Interface Builder can find them, but you don't want them exposed outside of your class implementation or (typically) even to subclasses of your class. So you would declare them in your header, and you generally would not add any getter/setter methods for these ivars.
Edit 2
For a specific example of where #private makes sense, what about something like:
#interface Car : NSObject {
#private
DataRecorder* blackBoxRecorder;
}
#property (nonatomic, strong) NSString *make, *model;
#end
We know that proposed regulations may require all cars on the road to include a built-in black-box/data recorder. So every Car must have one, and no subclass of Car should be able to tamper with blackBoxRecorder.
In this case having a setter method defined would not make sense. You might provide a public getter, or instead you might provide a public wrapper API around the DataRecorder that subclasses could use to log data. Something like -(void) logEventWithName:(NSString*)name andValue:(NSNumber*)value;. So subclasses can use the DataRecorder through the API, but they can't mess with the backing ivar itself to disable or modify the behavior of the mandated black-box/data recorder.
But in any case, yes, I'm in general agreement with your analysis. Having #private mostly impacts readability/maintainability of code. It needs to exist for Objective-C to be successful as an object-oriented programming language (if all ivars were public by default and there was no way to modify that, the language would be a complete mess), but what it does from a purely functional standpoint is not much. It's more of a logical/organizational tool. It assists with data hiding and allows you to keep all of your ivars in your header file(s), and that's about it.
You can declare the property as readonly in the Car class itself, or re-declare it as readonly only in the SportsCar class.
Also, #private doesn't have anything to do with properties - it only modifies the scope of the ivar itself.
I would like to know what is the difference when declaring a protocol in the same class and when declaring it in a separate file; example :
#import <UIKit/UIKit.h>
#class MyClassA;
#protocol MyDelegate <NSObject>
#required
- (MyClassA*)myMythod;
#optional
- (void)anOtherMethod:(NSString*)ID;
#end
#interface MyClassB : UIViewController <UITableViewDataSource, UITableViewDelegate>
#property (nonatomic, assign) id <MyDelegate> delegate;
......
here I declare the protocol delagate in the same file with MyClassB, and I can declare it (the protocol delegate) in a separate source file. What is the difference between declaring it in the same file with the class and in a separate file? Thanks!
There definitely are subtle differences.
If the protocol you are talking about is a delegate that is used by one particular class, for example, MySpecialViewController, and MySpecialViewControllerDelegate, then you might very well like to keep the declaration of both of those in the same header. If another class is going to implement that protocol, for example, it's probably going to depend logically on the MySpecialViewController class. So, you're not introducing any additional dependencies.
But, there's another significant reason (at least) to use protocols. You might be trying to decouple a bidirectional dependency between two classes. Of course, the compiler doesn't let two headers #import one another. But, even if you move one class's #import to the .m file, it's often a sign of a poor design to have two classes each fully aware of one another's complete API.
One way to decouple this relationship a little is to make one class aware of the other only through a protocol that the other implements. Perhaps Parent owns and creates the Child class, and thus must #import "Child.h". But, the Child also needs to call the foo:bar: method on the Parent. You could make a FooProtocol:
#protocol FooProtocol
- (void) foo: (int) arg1 bar: (BOOL) arg2;
#end
And then in Parent.h:
#interface Parent : SomeBaseClass<FooProtocol> {
}
which allows Child to do this:
#interface Child {
}
#property (assign) id<FooProtocol> fooHandler;
and use it
[fooHandler foo: 1 bar: YES];
Which leaves the child with no direct dependency on the Parent class (or Parent.h). But, this only works if you keep the declaration of FooProtocol in FooProtocol.h, not in Parent.h. Again, if this FooProtocol was only ever used by Child, then it would make sense to keep it in Child.h, but probably not if this protocol was used by classes other than Child.
So, to summarize, keep your protocols in separate headers if you want to preserve the maximum ability to separate interdependencies between your classes, or to encourage better separation in your design.
No difference. It's just a matter of how you like to organize your headers.
For example, I like to keep everything related to "one functional entity" (whatever that means, the definition varies :-)) in one file. A class that is using delegates that implement a protocol would therefore declare the class and the protocol in the same header, since they are pretty much just different bricks of the same building.
The only difference between having your protocol in a separate header file to your class's header file is it allows for including the protocol to be optional, this could aid in resolving any naming clashes, but prefixing your protocols should be the solution for that.
The convention seems to be to include relevant protocols inside the class's header file, as that way it's more organized and kept together, but if you have extremely large protocols it may make more sense to have them in separate files in order to make your class headers easier to read.
Say we have parent class
ParentViewController.h
#interface ParentViewController
....
#end
ParentViewController.m
#interface ParentViewController()
- (NSArray *)selectedItems;
#end
#implementation ParentViewController
.....
#end
And then we subclass it
ChildViewController.h
#interface ChildViewController : ParentViewController
....
#end
ChildClassViewController.m
#implementation ChildViewController
- (void)doSomething
{
// XCode Warning Flag on this line
NSUInteger count = [self selectedItems];
.....
}
XCode will set Warning flag at the commented line and says that "Instance method '-selectedItems' not found (return type defaults to 'id').
Yes I know that in ObjC there is no such thing as private methods, but using an empty category kind of gives the ability to do so. But somehow it does not get inherited by subclasses.
I usually fix it by moving the method from ParentViewController.m to ParentViewController.h. This feels weird, I loose the ability to make the method private just because I need to subclass it.
Now my question is:
Why does the parent subclass cannot find those methods that is declared in its category at the .m file?
Is there a way to remove the Warning Flag but without losing the ability to keep the method private.
Hopefully someone with more experience will be able to help explain this annoying issue.
First, note that your "empty category" isn't a Category at all, it's a Class Extension. Class Extensions very similar to categories but they're new in Objective C 2.0, and they differ slightly in their use. Primarily, the compiler will warn you if you don't implement a method in a Class Extension, but it won't with a Category. Anyways, on to the issue at hand...
Privacy in Objective-C is all about visibility. If the compiler can't see see the declaration of a method that's being used, you'll get a warning. Note that if you were to implement your subclass in the same file as your Class Extension, the compiler won't warn you because it can see the declaration.
Therefore, If you want to use "private" methods in subclasses, you just need some way of showing the compiler that those methods exist. My favorite pattern is to declare the private methods in a Category in a separate file (like MyClass_private.h). You then only import that interface into the implementation files of the base class and any derived classes that need to see it.
I have a solution, but generally I would advise against it. if you compile the file with -w (suppress all warnings), the warning goes away. I do not know if there is a specific warning flag for this message, if there was, you could use #pragma GCC diagnostic ignored "-Winstance-method-not-found", but I can't find it, sorry.
I'm looking to create a class in Objective-C for an iOS project that is focused on fetching data. I'm familiar with how classes normally work, setter and getter methods and variables. However, for this class since it's only performing a function (returning NSMutableArrays) I don't want to have to create an instance of the class to use the methods inside the class.
Any idea how I can do this neatly and efficiently?
This is a little bit atypical in Objective-C. Since classes in Objective-C can't actually have state beyond what is available to ordinary functions (i.e. there are no class variables), a class that's never instantiated is relatively useless in most cases. The normal design patterns for this kind of functionality are:
A singleton class (if you need lots of state)
A set of functions (if you don't)
You want to make class methods?
#interface Foo : NSObject {}
+(NSMutableArray*)someClassMethod:(id)params;
#end
...
#implementation Foo
+(NSMutableArray*)someClassMethod:(id)params {
// whatever implementation
return nil;
}
#end
...
NSMutableArray* array = [Foo someClassMethod:nil];
If you're only performing functions, and you don't need to support subclassing etc, why not just write them as C functions rather than a class with methods?
If this is just a class that performs some functions, you could write it as a C function.
In your header file --
NSMutableArray *functionThatReturnsMutableArray(NSObject *param1, NSString *param2);
In your implementation file --
NSMutableArray *functionThatReturnsMutableArray(NSObject *param1, NSString *param2)
{
...
return aMutableArray;
}
And that just include the .h file in your class that needs these functions and call them directly.
NSMutableArray *anArray = functionThatReturnsMutableArray(param1, param2);
Depending on what you are doing (the same NSString operations, UIView manipulations, etc), you could implement a category (I answered a question yesterday with the explanation below -- copied for your convenience ;).
Categories extend an existing class with additional methods or with your version of existing methods. For example, let's say you want to add a method that returns the first letter of a string to NSString. To do this you would create a category as follows:
Interface - JULString.h
#import NSString
#interface NSString (JULString)
-(NSString *) firstLetter;
#end
Implementation - The typical convention is that the filename of the category is the name of the class you are extending followed by “+” and the name of the category. In this case the file would be called NSString+JULString.m
#import "NSString+JULString.h"
#implementation NSString ( JULString )
- (NSString *)firstLetter
{
return [NSString stringWithFormat:#"%C", [self characterAtIndex:1]];
}
#end
The neat thing about categories is that now they extend the behavior of ANY instance of the class you are working with. In other words, any NSString in your application will have your new methods (provided that you import the proper header file of course). Beware though, as with great power comes great responsibility. Overwriting class using a category behaviors may lead to undesired effects, so be cautious.
A couple of links you may want to check are:
Apple's guide to Objective-C
Learn Objective-C
Note:
I don't have my Mac with me so I'm writing this code basically off the top of my head (and using some code from the sites above as a reminder). So I apologize in advance for any mistakes ;)
I'm diving into iOS development while trying to grasp Objective-C and I'm still in that phase where, ever where I look, I see things that don't make any sense to a veteran C programmer like myself. In this Game Kit example on Apple's dev site, one of the header files declares a class interface, three different times...
#interface SessionManager : NSObject <GKSessionDelegate> {
NSString *sessionID;
GKSession *myGKSession;
NSString *currentConfPeerID;
NSMutableArray *peerList;
id lobbyDelegate;
id gameDelegate;
ConnectionState sessionState;
}
#property (nonatomic, readonly) NSString *currentConfPeerID;
#property (nonatomic, readonly) NSMutableArray *peerList;
#property (nonatomic, assign) id lobbyDelegate;
#property (nonatomic, assign) id gameDelegate;
- (void) setupSession;
- (void) connect:(NSString *)peerID;
- (BOOL) didAcceptInvitation;
- (void) didDeclineInvitation;
- (void) sendPacket:(NSData*)data ofType:(PacketType)type;
- (void) disconnectCurrentCall;
- (NSString *) displayNameForPeer:(NSString *)peerID;
#end
// Class extension for private methods.
#interface SessionManager ()
- (BOOL) comparePeerID:(NSString*)peerID;
- (BOOL) isReadyToStart;
- (void) voiceChatDidStart;
- (void) destroySession;
- (void) willTerminate:(NSNotification *)notification;
- (void) willResume:(NSNotification *)notification;
#end
#interface SessionManager (VoiceManager) <GKVoiceChatClient>
- (void) setupVoice;
#end
I see that each interface is different, but specify the same class name.
What's the reason for this?
I've also noticed this same behavior in other code examples, only instead of declaring multiple interfaces in the header file, you'll see an additional #interface block declared towards the top of the .m implementation file, typically above the #implementation block. Why?
Thanks so much in advance for your wisdom!
These are called Categories, and you can see them by the parentheses after the class name.
They're used to group methods into chunks instead of having them all in one big bunch. They can also be placed separate from the main class declaration. This is particularly useful inside .m files, where you may need to create utility methods for your class, but you don't want them visible to other objects for any reason (so you don't put them in the .h, which is imported by the other classes). Another common use is to group methods which correspond to a certain logical category, informal protocol, or what have you. Categories can be named (#interface MyClass (MyCategory)) or anonymous (#interface MyClass ()). The latter is usually used for generic private methods in your header.
(The reason you need categories to declare private methods in your .m is so the compiler knows about the methods — otherwise, you'll get a warning when you try to call such a method.)
Also, you can use categories to add methods to existing classes. For example, UIKit contains a category on NSString called NSString(UIStringDrawing). Or if you wanted to make your own:
#interface NSString (MyFoo)
+ (NSString *)fooString;
#end
//... somewhere else...
#implementation NSString (MyFoo)
+ (NSString *)fooString { return #"foo!"; }
#end
Note that you can't add instance variables with a category.
It is not defining the interface 3 times - there is only one interface.
what you are seeing are categories that add methods to the class
There is a base interface that defines the attributes and some methods - there is only one of these ant it defines how the object is stored in memory and is the only one that is needed.
Objective C looks up methods at run time. These methods do not need to be found at compile time and thus do not need to be declared in headers/interfaces etc. If they are not declared and you code calls them then you will get compile time warnings.
In this case one category with an empty name is used for private functions. I usually only put this interface in the .m file of the class so is not visible to other code as not in a header.
The second category is to add the methods to make SessionManager meet the GKVoiceChatClient protocol. The usual reason for doing this is to group code covering a specific behaviour together.
Another reason for using categories is to add methods to an existing class like NSString -you can create your own category adding methods without subclassing the class as you have to do in many other OO languages including Java and C++
This is for code upkeep purposes i belive...its easier to looks through the different labeled interfaces, for example (VoiceManager) which is for voice manager setup and methods related to that, and you have the one interface dealing with the GK delegate methods and whatever interaction with gamekit there will be...as opposed to looking at one huge interface file and having to pick out what you are looking for...They can also divide the implementations in this way too so its easier to look through and navigate.
In order:
The first interface declaration is the actual interface declaration that declares the class as a subclass of NSObject and implementing the GKSessionDelegate protocol. It also declares the instance variables and a selection of methods.
The second interface declaration is a class extension. It can be thought of as a kind of anonymous category. So we'll skip it for now and come back to it.
The third interface is a category declaration. Categories allow you to do two things. They allow you to split the class implementation across multiple source files. In the above, you'll have
#implementation SessionManager
// methods declared in the first #interface
#end
#implementation SessionManager(VoiceManager)
// methods declared in the third #interface
#end
The two #implementations need not be in the same source file.
The other thing a category can do is allow you to extend already existing classes.e.g. #interface NSString(MyStringMethods)...
Coming back to the class extension, this is a bit like an anonymous category. The implementations of the methods declared in it must be in the main #implementation block. The purpose of the class extension is to allow you to declare private API separately from the class's header file. I normally put one in the.m file at the top if I have methods that should only be used from the class. Although, note that this is only a compile time restriction. There is nothing to stop a class extension message from being sent by anybody at run time.