close
Blogtrottr
海芋小站
提供實用軟體教學,介紹有趣網站及資訊,豐富電腦人生 
Category 是什麼?如何在 Objective-C 中使用 Category?
Dec 11th 2014, 17:28, by 張海芋

在 Java、C++ 等物件化的程式語言中,如果我們要擴充 Class,只需要使用「繼承」的寫法就可以了,在 Objective-C 中,當然也支援了繼承的概念,不過更特別的是他支援了「Category」這種繼承型態。什麼是「Category」呢?簡單來說,就是將現有物件的功能再加以擴充函式,讓現有物件更能符合自己想實做的方式。而使用 Category 只能針對既有元件再新增或者覆寫函式,並不能像繼承一樣新增成員變數。以下是 Category 的實做。

@interface 原Class名稱 (Category Name)
// function 宣告
@end

@implementation 原Class名稱 (Category Name)
// function 實做
@end

舉例來說,如果我要擴充 NSString 這個物件,在裡面新增一個的函式 showMySiteName 來顯示我的網站名稱,那麼我只要在 A.h 檔中這樣寫。

@interface NSString (NSStringCategory)
- (void) showMySiteName;

@end

接下來,我在 A.m 檔案做這個函式,就可以從外面存取了。

@implementation NSString (NSStringCategory)
- (void) showMySiteName{
    NSLog(@"海芋小站真的棒!!");
}
@end

 

要怎麼從其它檔案中存取呢?假設我有一個 ViewController.m,我要存取 ShowMySiteName 這個函式,我必須先 import 我們定義的檔案 A.h,再從檔案中去存取。

#import "A.h"
@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    NSString* ns = [[NSString alloc] init];
    [ns showMySiteName];
}
@end

接下來,你會想說我可以同時針對同個物件來做兩個不同的 Category 擴充嗎?答案是可以的,假設你除了 A.h 外,也有另一個檔案 B.h,定義如下

@interface NSString (NSStringCategory2)
- (void) showMySiteName2;

@end

接下來,我在 B.m 檔案實做這個函式。

@implementation NSString (NSStringCategory2)
- (void) showMySiteName2{
    NSLog(@"海芋小站真的棒2!!");
}
@end

一樣假設我有一個 ViewController.m,我要存取 ShowMySiteName 和ShowMySiteName2 這個函式,我必須先 import 我們定義的檔案 A.h 和 B.h,再從檔案中去存取。

#import "A.h"
#import "B.h"
@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    NSString* ns = [[NSString alloc] init];
    [ns showMySiteName];
    [ns showMySiteName2];
}
@end

那麼你會說, Category Name 是幹麼的,就海芋所理解,那只是方便你辨識用的,如果有錯再請指正囉!

This entry passed through the Full-Text RSS service - if this is your content and you're reading it on someone else's site, please read the FAQ at fivefilters.org/content-only/faq.php#publishers.
Want something else to read? How about 'Grievous Censorship' By The Guardian: Israel, Gaza And The Termination Of Nafeez Ahmed's Blog

You are receiving this email because you subscribed to this feed at blogtrottr.com.

If you no longer wish to receive these emails, you can unsubscribe from this feed, or manage all your subscriptions
arrow
arrow
    全站熱搜

    jmuko90 發表在 痞客邦 留言(0) 人氣()