2. can not add new instance variable to existing class
3. if the method defined in category is the same as existing class,
it will replace original method of existing class
ex:
add category NumberConvenience to NSString
@interface NSString (NumberConvenience)
- (NSNumber *) lengthAsNumber;
@end // NumberConvenience
@implementation NSString (NumberConvenience)
- (NSNumber *) lengthAsNumber
{
unsigned int length = [self length];
return ([NSNumber numberWithUnsignedInt: length]);
} // lengthAsNumber
@end // NumberConvenience
4. splitting a class's implementation across multiple files or multiple frameworks
ex:
CategoryThing.h
#import
@interface CategoryThing : NSObject {
int thing1;
int thing2;
int thing3;
}
@end // CategoryThing
@interface CategoryThing (Thing1)
- (void) setThing1: (int) thing1;
- (int) thing1;
@end // CategoryThing (Thing1)
@interface CategoryThing (Thing2)
- (void) setThing2: (int) thing2;
- (int) thing2;
@end // CategoryThing (Thing2)
@interface CategoryThing (Thing3)
- (void) setThing3: (int) thing3;
- (int) thing3;
@end // CategoryThing (Thing3)
categoryThing.m
#import "CategoryThing.h"
@implementation CategoryThing
- (NSString *) description
{
NSString *desc;
desc = [NSString stringWithFormat: @"%d %d %d",
thing1, thing2, thing3];
return (desc);
} // description
@end // CategoryThing
thing1.m
#import "CategoryThing.h"
@implementation CategoryThing (Thing1)
- (void) setThing1: (int) t1
{
thing1 = t1;
} // setThing1
- (int) thing1
{
return (thing1);
} // thing1
@end // CategoryThing
thing2.m & thing3.m are like thing1.m
沒有留言:
張貼留言