When naming parameters in Objective-C, does it matter -that is, it is advisable for documentation / legibility - if I use the same name for similar methods? For example:
#interface Zookeeper : Employee
-(void) washAnimal:(Animal *)someAnimal;
-(void) feedAnimal:(Animal *)someAnimal;
-(void) trainAnimal:(Animal *)someAnimal;
...
Or, should it be like so:
#interface Zookeeper : Employee
-(void) washAnimal:(Animal *)animalToBeWashed;
-(void) feedAnimal:(Animal *)animalToBeFed;
-(void) trainAnimal:(Animal *)animalToBeTrained;
...
Thanks!
In the example you gave, I'd just use animal as the name for all 3. Look at UITableViewDelegate and UITableViewDataSource methods - all arguments for the table view in question are named tableView.
Related
Say I have a class Parent and the child is Child1 and Child2.
I declare Parent+ParentCategory and then I declare a method:
-(void) Redraw;
Later I want the Redraw function of Child1 to be different than the Redraw function of Child2.
Can I declare Child1+Child1Category and then override the
-(void) Redraw
Can -(void)Redraw of Child1 call the function in the parent category?
Can that be done?
What would be good approach?
I know classes can inherit each other. I know protocol can extend each other. I wonder why category doesn't?
I do not agree with the given answers:
A.: It is not true, that category's methods win against class' method. This is an implementation detail, but the behavior is not defined.
If the name of a method declared in a category is the same as a method
in the original class, or a method in another category on the same
class (or even a superclass), the behavior is undefined as to which
method implementation is used at runtime.
B.
But this does not matter. You neither define a method in a category that is defined in the class nor define a method in two clashing categories. The cit. simply does not apply to your case. It applies to something like this:
#interface A : NSObject
- (void)doSomething;
#end
#implementation A
- (void)doSomething {}
#end
#interface A (Addition)
- (void)doSomething;
#end
#implementation A (Addition)
- (void)doSomething {}
#end
If I understand you correct, you do not want to do this. You want something like that:
Base level:
#interface A : NSObject
#end
#implementation A
#end
#interface A (Addition)
- (void)doSomething;
#end
#implementation A (Addition)
- (void)doSomething {}
#end
This does not break the rule, because there is no method in the category, which is in the class.
Subclass level:
#interface B : A
#end
#implementation B
#end
#interface B (Addition)
- (void)doSomething;
#end
#implementation B (Addition)
- (void)doSomething {}
#end
There is no clash on the level of B for the same reason as there is no clash on the level of A.
Somebody might say, that there is a clash, because B inherits -doSomething from A. But this is no clash, because in this case a priority rule applies: Subclasses overwrite methods.
You can do that.
Edit:
You can check the problem simply by adding the method to the class. Would that compile? In the clashing case, it wouldn't. In your case, it would.
I will replay with a cit. from this answer:
Lets just put it this way. Don't override methods using categories, period, ever, end of answer.
The reason of this is that while it is exactly known that a category's method always win against a class method (that is, if you implement a method in a category that's already declared in the class you are extending with the category the method of the category will be called.) when you have multiple category implementing the same method which implementation takes precedence is undefined
It is not wise to use category to do this. Categories add methods to the current class. If there are multiple methods with the same name, it will replace the old one (it is NOT an override). But unfortunately it is hard to say which one is replaced. Don't do it or you may get in trouble.
And you probably can not call the method in Parent from the child category. The most proper design here is a protocol.
Objective-c class can be extended by categories.
But with multi category extensions on a same class by over define a same method, the result is not defined -- As following case:
#implementation someClass (category1)
- (void)foo {}
#end
#implementation someClass (category2)
- (void)foo {}
#end
In that case, compiler even won't show any warning message. In some big project and with different people for maintenance, this kind of case is quite difficult to be addressed.
So my question is: is there any sophisticated pattern or resolution for avoiding this scenario?
For big projects, a good practice is to also add a prefix to your method names like :
- (void)nd_foo;
- (void)sp_foo;
i have 7 custom objects with the same properties, createDate and modifiedDate. can i create a method that accepts Object1 but actually takes all 7 objects?
right now, this works:
[self setCreateAndModifiedTimeWithEvent:((Object1 *) object2
WithCreateDate:[[eventsArray objectAtIndex:i] objectForKey:#"create_date"]
AndModifiedDate:[[eventsArray objectAtIndex:i] objectForKey:#"modified_date"]];
.h file
-(void) setCreateAndModifiedTimeWithEvent:(Object1 *)object
WithCreateDate:(NSString *)createStamp
AndModifiedDate:(NSString *)modifiedStamp;
.m file
-(void) setCreateAndModifiedTimeWithEvent:(Object1 *)object
WithCreateDate:(NSString *)createStamp
AndModifiedDate:(NSString *)modifiedStamp
{
object.A = #"Hello,";
object.B = #"World";
}
this would cut back on good chuck of lines of code.
i know you can do this sort of thing with UIView and its subclasses. say i have a
UITextField myTextField.
i can do
((UIScrollView *)myTextField).tag = 2;
is there anything inherently bad about typecasting my objects like this or is it acceptable?
Like Joe said, you'd be better off with something like this:
#interface DatedObject : NSObject
#property NSDate *createDate;
#property NSDate *modifiedDate;
#end
#implementation DatedObject
#synthesize createDate;
#synthesize modifiedDate;
#end
Then have each of the 7 classes inherit from the DatedObject base class. Inheritance is a fundamental part of Object Oriented Programming, and you should learn to use it (wisely).
Then your method can be:
-(void) setCreateAndModifiedTimeWithEvent:(DatedObject *)object
WithCreateDate:(NSString *)createStamp
AndModifiedDate:(NSString *)modifiedStamp;
You could also do this with a protocol, but the nice thing about using a base class that the other classes inherit from is that you only have to implement this functionality in one place. If the 7 classes don't all currently inherit from the same base class (which would end up being the superclass of DatedObject), a protocol is probably the way to go. In that case, you can declare your method like this:
-(void) setCreateAndModifiedTimeWithEvent:(id<DatedObjectProtocol>)object
WithCreateDate:(NSString *)createStamp
AndModifiedDate:(NSString *)modifiedStamp;
One of the big advantages to these two approaches over what you've posted in your question is that you get more help from the compiler in catching places where your code sends a message to an object that doesn't respond to it.
Andrew's answer is correct.
But, if for some reason you don't want to create a common base class or a protocol, you could always set the type of the method parameter to id, like this:
-(void) setCreateAndModifiedTimeWithEvent:(id)object
WithCreateDate:(NSString *)createStamp
AndModifiedDate:(NSString *)modifiedStamp;
Parameters of type id don't do any type checking at compile time (like the values in an NSArray) so you can call any method you want on them without generating compiler warnings (this is obviously quite dangerous if you aren't careful).
You can't use dot notation on id variable without casting, but it's better to cast from an id to a concrete type than to cast from a different unrelated type.
It doesn't actually make any difference except to your code readability though.
I am looking at Apple's sample code for lazy table image loading. I see that they have two lines starting with #protocol ParseOperationDelegate. Why do they do this twice? All the documentation on Objective C protocols I've looked at do not tell you to do it twice.
#class AppRecord;
#protocol ParseOperationDelegate;
//#interface ParseOperation : NSOperation <NSXMLParserDelegate>
#interface ParseOperation : NSOperation
{
#private
id <ParseOperationDelegate> delegate;
NSData *dataToParse;
NSMutableArray *workingArray;
//AppRecord *workingEntry;
//NSMutableString *workingPropertyString;
//NSArray *elementsToParse;
//BOOL storingCharacterData;
}
- (id)initWithData:(NSData *)data delegate:(id <ParseOperationDelegate>)theDelegate;
#end
#protocol ParseOperationDelegate
- (void)didFinishParsing:(NSArray *)appList;
- (void)parseErrorOccurred:(NSError *)error;
#end
The #protocol ParseOperationDelegate; line is not defining the protocol. It's a forward declaration. Basically it's saying that "a protocol called ParseOperationDelegate exists and is defined somewhere else in the code".
They do this so that the compiler will not die with an error on the line that goes id <ParseOperationDelegate> delegate;. The alternative would be to have the entire protocol definition placed before the interface definition (which personally I think would be a better solution in this case).
In such a simple case as this one I think there is little point in having the forward declaration. But you can easily imagine a more complex case where perhaps the protocol definition lives in its own header file (or in the header file for some other class). In a case like that, using a forward declaration allows you to avoid having to #import the protocol's header file into your class's header. It's a small difference, really, but it can be useful.
A class can be extended in Objective C using a category such as:
#interface NSString (CategoryName)
-(NSString *)myFabulousAddition; // a fabulous additional method
#end
/////////////////////////////
#implementation NSString (CategoryName)
-(NSString *)myFabulousAddition {
// do something fabulous...
}
#end
In this small example, I would be adding the method myFabulousAddition to NSString. I could then call it by [anNSString myFabulousAddition] just as if it were part of the NSString set of methods. Great and useful.
In the Apple documents regarding Categories, the docs state:
There’s no limit to the number of
categories that you can add to a
class, but each category name must be
different, and each should declare and
define a different set of methods.
What if you have something like this:
#interface NSString (CategoryName)
-(NSString *)myFabulousAddition; // a fabulous additional method
#end
#interface NSString (ANOTHERCategoryName)
-(NSString *)myFabulousAddition; // a DIFFERENT fabulous additional method
// BUT with same name as the other category
#end
/////////////////////////////
#implementation NSString (CategoryName)
-(NSString *)myFabulousAddition {
// do something fabulous...
}
#end
#implementation NSString (ANOTHERCategoryName)
-(NSString *)myFabulousAddition {
// do something equally fabulous, but DIFFERENT...
}
#end
The lack of a name in the parenthesis indicates that the form is an extension to the class, like so:
#interface MyObject () // No name -- an extension vs category to MyObject
- (void)setNumber:(NSNumber *)newNumber;
#end
Does the category name have any meaning to the compiler or linker? Is the category name part of the method signature in anyway or is it part of a primitive namespace? If the category name is meaningless, how do you know if you are about to stomp on another method and get undefined behavior?
The way to avoid stomping on methods is to prefix your category method names, like this:
#interface NSString (MyCompanyCategoryName)
- (NSString *)MYCO_fabulousAddition;
#end
If you get a collision of method names from different categories, then which one 'wins' at run time is completely undefined.
The name of a category is almost entirely useless, with the exception being that the nameless category (i.e. ()) is reserved for class extensions. Methods from class extensions are supposed to be implemented in the class' main #implementation.
The category name doesn't mean anything special, it's just an identifier. Unless the linker (or runtime loader) decides to give you a warning, there is no way to tell that multiple categories are defining the same method.
The behavior is (largely) unpredictable - one of the categories will win out, but you can't tell which one. Also, I think it's well possible you will start out with one implementation and end up with another one (if the second category is loaded after the first).
It certainly acts as an identifier, from the programmer's point of view. In the compiler point of view category methods are simply added as an extension of the class ( from which it is extending), regardless of the name.
And yes you can add categories of the same class with the same identifiers, even with same functions. But you definitely can't override any function because categories are just part of the class once you define them ( Just like you can't override a function of a class from within that class ).
As they are being added at runtime, they don't raise any error and only at runtime compiler selects the function, which is totally unpredictable.
i believe that they don't have any meaning. You don't really use them in your code ... Since they are categories and ... the semantic of a category ... is just to categorize something, i think this is somewhat logical ...
I would say they just simply gather the methods ...
On the other hand your question is very valid ... You DON'T KNOW if you override a method. If you are in the same project then the compiler issues a warning (or an error ? i don't remember), however if you are overriding a method from a library, then .. you are out of luck ...