1 8 用乙個Category來擴充套件乙個類

2021-09-02 11:57:15 字數 1602 閱讀 9448

1、問題

你想要給乙個類新增方法和行為,但你不想從頭建立乙個全新的子類。

2、解決方案

在objective-c中,你可以用categories來定義和實現properties和methods,之後它們可以被附到乙個類上。要完成這件事,你需要有2個檔案:乙個標頭檔案列出介面、乙個實現檔案列出實現。當category搞好了,就可以匯入該category標頭檔案;任何將該category賦予其之上的類將會擁有這些properties和methods。

4、原理

你需要的第1個東西就是標頭檔案。就說,你要擴充套件nsstring類,加一些方法幫助你建立html文字。

下面是乙個category標頭檔案,裡面有乙個介面,**如下:

@inte***ce nsstring (htmltags)

上面的nsstring就是你要擴充套件的類。這意味著該category可能只會被運用到nsstring(或nsstring的子類)。在類名後面圓括號中的是給category的名字。

該category的properties和methods都要放在inte***ce的後面,@end的前面。

實現:@implementation nsstring (htmltags)

5、**

listing 1-13. htmltags.h 

#import

@inte***ce nsstring (htmltags) 

-(nsstring *) enclosewithparagraphtags; 

@end

listing 1-14. htmltags.m 

#import "htmltags.h" 

@implementation nsstring (htmltags) 

-(nsstring *) enclosewithparagraphtags{ 

return [nsstring stringwithformat:@"",self]; 

@end

listing 1-15. main.m 

#import "htmltags.h" 

int main (int argc, const char * argv){ 

@autoreleasepool { 

nsstring *webtext = @"this is the first line of my blog post"; 

//print out the string like normal: 

nslog(@"%@", webtext); 

//print out the string using the category function: 

nslog(@"%@", [webtext enclosewithparagraphtags]); 

return 0; 

6、使用

categories通常用在這些情形下:你想避免建立乙個複雜的繼承層次。categories also help your code remain readable.例如,你想要在專案中用乙個category來擴充套件nsstring,你的大多數**對於使用過nsstring的其他人來說都是熟悉的。假如寫乙個nsstring的子類,例如nshtmlstring,就可能會導致困惑。

用兩個棧來實現乙個佇列

用兩個棧來實現乙個佇列,完成佇列的push和pop操作。佇列中的元素為int型別。思路 push入棧1,完成佇列的push操作。棧1pop出到棧2,完成倒序。從棧2pop出,返回,完成佇列的pop操作 這時棧2有兩種狀態,空和不空,空的話再從棧1pop進來即可。class solution int ...

用列舉來實現乙個交通燈

package com.foresee.test 利用列舉來定義紅黃綠燈 author qinyujun public class enumtest catch exception e public enum trafficlamp yellow 2000 red 5000 獲取下乙個燈,在列舉元素...

用乙個 int 來描述位置資訊

一般的,遊戲場景中物件的位置資訊都是用兩個 int 來描述,像這樣 struct pos pos 使用的時候這樣 定義乙個座標 pos pos 獲取x軸座標 int x pos.x 獲取y軸座標 int y pos.y 然後我看到sdlpal中只用了乙個無符號整形來描述,具體 是這樣的 來自palc...