Why is the protocol defined twice in Apple's sample code? - objective-c

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.

Related

Mutual include breaks types

I have two classes, Entity, and EntityHandler.
EntityHandler has a method, AddEntity. This method adds the Entity to an NSMutableArray.
Entity has a method called subscribe. It assigns a reference to EntityHandler to a variable for later usage.
Upon the inclusion of both header files in each other the project breaks. For example,
-(void) addEntity: (Entity *) mob;
returns the error
Expected a type
How can I fix this?
You're looking to employ forward declarations for your ObjC types, in order to break the cyclic header dependency.
It would look something like:
// EntityHandler.h
#class Entity; // << the forward declaration. not #import.
#interface EntityHandler : NSObject
-(void) addEntity:(Entity *) mob;
#end
This tells the compiler that there is an ObjC class named Entity.
Then you #import when you need more than a typename (likely in EntityHandler.m).

Naming conventions for parameters in Objective-C

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.

Method parameter wihout type?

What did I do here? Can method parameters be typeless?
In a recent project which works fine, the App is in the store already - no issues so far, I did the following in a .h file:
#property (strong, nonatomic) NSManagedObject *myPerson;
- (HKPersonPicker*) initWithPerson:person;
- (HKPersonPicker*) initWithPerson:person delegate:(id <HKPersonPickerDelegate>)delegate;
I meant to do it this way but did not:
- (HKPersonPicker*) initWithPerson:(NSManagedObject*)person;
- (HKPersonPicker*) initWithPerson:(NSManagedObject*)person delegate:(id <HKPersonPickerDelegate>)delegate;
The corresponding part of the .m file:
- (HKPersonPicker*) initWithPerson:person
{
self = [super init];
if(self){
self.myPerson = person;
}
return (self);
}
- (HKPersonPicker*) initWithPerson:person delegate:(id <HKPersonPickerDelegate>)delegate
{
self = [self initWithPerson:person];
if(self){
self.delegate = delegate;
}
return (self);
}
As you can see I did not do anything special with this person object, just assigned it to the property myPerson. As I did not call any of the object's methods or accessed its data, the compiler did not need to know anything about that object. But what is it from the compiler's point of ivew? Type id? Just something? Is there any default type?
As you see, I do not have any real problem. I am just curious. Hope this question does not break any SO rule.
With C the default type is int, but with Objective-C it's id.
Missing type declarations in methods default to id. IIRC, you can see a fair number of methods without return types in Apple's runtime library.
There is no definitive problem with what you are doing, but its not really kosher at the same time. You should still have a type declaration for the sake of clarity, and maintaining good and consistent Cocoa-like code styling.
So it should really be like:
- (GSPersonPicker*) initWithPerson:(id)person;
And you should really change the property declaration:
#property (strong, nonatomic) id *myPerson;
If that is not changed, then your code is confusing. You KNOW the type that will be coming in. So let the compiler help you with meaningful warnings/errors by using types. You should also probably be using the type 'HKPerson' or whatever you have named your entity, so the compiler doesn't think its ok for you to pass in an 'HKPlace' (they will both be of type 'id' and 'NSManagedObject', which does you no favors)
More importantly, you should not be using the dynamic type (id) unless you have a reason. The compiler is there to help you. Errors and warnings are your friend, they tell you that you messed up, not the computer. When you use 'id', the compiler just goes, Oh, anything can go in here!!! And it will not detect an error where you sent that method a type that will break everything.
Now lets say that you are going to use polymorphism. IE, Lets declare a generic protocol for multiple classes to adhere to, which defines our person:
#protocol GSPerson
-(NSUInteger)age;
#end
So now lets define a couple classes, and have them subscribe to the protocol (the GSPerson thats between carrots markdown is killing me atm lol):
#import "GSPerson.h"
#interface GSSpecialPerson <GSPerson>
// code
#end
#import "GSPerson.h"
#interface GSWeirdPerson <GSPerson>
// code
#end
Then lets redefine our method signature to adhere to the protocol:
- (GSPersonPicker*) initWithPerson:(id<GSPerson>)person;
And our property declaration:
#property (strong, nonatomic) id <GSPerson> *myPerson;
Now the compiler knows that anything i pass into that method should conform to the GSPerson protocol I defined above (ie they need a method that returns the persons age). If i try to pass anything else in, it will throw compiler warnings, WHICH IS GOOD.
Even better, it will throw warnings on your polymorphic classes if they are missing their required methods.

multiple custom objects with same properies

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.

Do Objective-C Category names do anything?

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 ...