ios developer tiny share-20160919

来源:互联网 发布:淘宝bt种子 编辑:程序博客网 时间:2024/06/05 03:28

本节讲Objective-C中使用category,来给现有类增加新的方法。


Categories Add Methods to Existing Classes

If you need to add a method to an existing class, perhaps to add functionality to make it easier to do something in your own application, the easiest way is to use a category.

The syntax to declare a category uses the @interface keyword, just like a standard Objective-C class description, but does not indicate any inheritance from a subclass. Instead, it specifies the name of the category in parentheses, like this:

@interface ClassName (CategoryName) @end

A category can be declared for any class, even if you don’t have the original implementation source code (such as for standard Cocoa or Cocoa Touch classes). Any methods that you declare in a category will be available to all instances of the original class, as well as any subclasses of the original class. At runtime, there’s no difference between a method added by a category and one that is implemented by the original class.

Consider the XYZPerson class from the previous chapters, which has properties for a person’s first and last name. If you’re writing a record-keeping application, you may find that you frequently need to display a list of people by last name, like this:

Appleseed, JohnDoe, JaneSmith, BobWarwick, Kate

Rather than having to write code to generate a suitable lastName, firstName string each time you wanted to display it, you could add a category to the XYZPerson class, like this:

#import "XYZPerson.h" @interface XYZPerson (XYZPersonNameDisplayAdditions)- (NSString *)lastNameFirstNameString;@end

In this example, the XYZPersonNameDisplayAdditions category declares one additional method to return the necessary string.

A category is usually declared in a separate header file and implemented in a separate source code file. In the case of XYZPerson, you might declare the category in a header file called XYZPerson+XYZPersonNameDisplayAdditions.h.

Even though any methods added by a category are available to all instances of the class and its subclasses, you’ll need to import the category header file in any source code file where you wish to use the additional methods, otherwise you’ll run into compiler warnings and errors.

The category implementation might look like this:

#import "XYZPerson+XYZPersonNameDisplayAdditions.h" @implementation XYZPerson (XYZPersonNameDisplayAdditions)- (NSString *)lastNameFirstNameString {    return [NSString stringWithFormat:@"%@, %@", self.lastName, self.firstName];}@end

Once you’ve declared a category and implemented the methods, you can use those methods from any instance of the class, as if they were part of the original class interface:

#import "XYZPerson+XYZPersonNameDisplayAdditions.h"@implementation SomeObject- (void)someMethod {    XYZPerson *person = [[XYZPerson alloc] initWithFirstName:@"John"                                                    lastName:@"Doe"];    XYZShoutingPerson *shoutingPerson =                        [[XYZShoutingPerson alloc] initWithFirstName:@"Monica"                                                            lastName:@"Robinson"];     NSLog(@"The two people are %@ and %@",         [person lastNameFirstNameString], [shoutingPerson lastNameFirstNameString]);}@end

As well as just adding methods to existing classes, you can also use categories to split the implementation of a complex class across multiple source code files. You might, for example, put the drawing code for a custom user interface element in a separate file to the rest of the implementation if the geometrical calculations, colors, and gradients, etc, are particularly complicated. Alternatively, you could provide different implementations for the category methods, depending on whether you were writing an app for OS X or iOS.

Categories can be used to declare either instance methods or class methods but are not usually suitable for declaring additional properties. It’s valid syntax to include a property declaration in a category interface, but it’s not possible to declare an additional instance variable in a category. This means the compiler won’t synthesize any instance variable, nor will it synthesize any property accessor methods. You can write your own accessor methods in the category implementation, but you won’t be able to keep track of a value for that property unless it’s already stored by the original class.

The only way to add a traditional property—backed by a new instance variable—to an existing class is to use a class extension, as described inClass Extensions Extend the Internal Implementation.

Note: Cocoa and Cocoa Touch include a variety of categories for some of the primary framework classes.
The string-drawing functionality mentioned in the introduction to this chapter is in fact already provided for NSString by the NSStringDrawing category for OS X, which includes the drawAtPoint:withAttributes: and drawInRect:withAttributes: methods. For iOS, the UIStringDrawing category includes methods such as drawAtPoint:withFont: and drawInRect:withFont:.

0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 手机玩游戏闪屏怎么办 满身起小疙瘩很痒怎么办 出门在外忘记带备用胸罩怎么办 去泰国浮潜近视怎么办 gta5线上马丁任务卡了怎么办 双肩背包黑色的皮子褪色怎么办 lspdfr在游戏里崩溃怎么办 gta5钱超过21亿怎么办 假警察要带走我怎么办 遇到假警察拦车怎么办 大连船员体检眼力不合格怎么办 禁行如果通过了怎么办 钻戒的戒圈磨损怎么办 多肉的肉掉了怎么办 电脑自带鼠标动不了怎么办 笔记本电脑自带鼠标动不了怎么办 包包弹簧扣松了怎么办 耳钉氧化成黑色怎么办 想买点小股票玩玩要怎么办 玩具子弹打到眼睛怎么办 玩具汽车遥控器码乱了怎么办 索尼A7屏幕花了怎么办? 汽车冷冻器坏了怎么办 sim卡损坏怎么办 补卡 异或门一个输入怎么办 迷你世界加不了好友怎么办 电脑软件显示无效应用程序怎么办 美的滚筒洗衣机打不开门怎么办 手机存储卡坏了怎么办 回南天地板潮湿怎么办 lg滚筒洗衣机门打不开怎么办 西门子滚桶洗衣机门打不开怎么办 洗衣机离合器螺丝卸不动怎么办 门锁保险栓坏了怎么办 小车电瓶没电了怎么办 重装机兵战车底盘坏了怎么办 父亲沉迷安利十年该怎么办 脚的大脚骨痛怎么办 自考准考证号忘记了怎么办 有桌子老师不出马怎么办 电商遇到职业打假人怎么办