Re: Error in learning Cocoa book?
Re: Error in learning Cocoa book?
- Subject: Re: Error in learning Cocoa book?
- From: Ondra Cada <email@hidden>
- Date: Sat, 13 Oct 2001 19:09:42 +0100
Ricky,
>
>>>>> Ricky Sharp (RS) wrote at Sat, 13 Oct 2001 10:45:54 -0500:
RS> NSMutableArray* expenses;
RS>
RS> and then an appropriate accessor. The book has the method declaration as:
RS>
RS> - (NSMutableArray*) expenses;
RS>
RS> but the implementation as:
RS>
RS> - (NSArray*) expenses
RS> {
RS> return expenses;
RS> }
RS>
RS> Now, this does compile, link and run, but are there any side effects of
RS> this?
Well, the declared types (anywhere) serve just the compiler. Should you
replace "AnyClass*" anywhere by "id", it would work as well (so far as just
id-compatible arguments and return types are used). Therefore, in a sense it
is unimportant which class names are used in declarations: the program would
always work properly (or improperly ;)), regardless the right or wrong class
names are used in declarations.
OTOH, the proper declaration (plus compiler warnings) help you to keep code
bugfree -- and from _this_ point of view the example is faulty.
Presume you'll go next year to improve the code, and for some reason or
another you would change
- (NSArray*) expenses {
return expenses;
}
to
- (NSArray*) expenses {
return [NSArray arrayWithArray:expenses];
}
So far as _this_ declaration goes, the change is legal (it brings some
slight behaviour change, which might be desired or not, regarding the actual
usage). Of course, you are in for a nasty surprise as soon as the returned
value is somewhere used the way the _header_ declaration (NSMutableArray)
suggested.
Incidentally, there are two ways how to correct this:
@interface ... { NSMutableArray *exp; }
-(NSMutableArray*)exp;
...
@implementation
-(NSMutableArray*)exp { return exp; }
...
is the obvious solution. But, the following is proper as well:
@interface ... { NSMutableArray *exp; }
-(NSArray*)exp;
...
@implementation
-(NSArray*)exp { return exp; }
...
provided you want give out the array read-only for users of the API.
---
Ondra Cada
OCSoftware: email@hidden
http://www.ocs.cz
2K Development: email@hidden
http://www.2kdevelopment.cz
private email@hidden
http://www.ocs.cz/oc