Objective_C擴充機制學習

來源:互聯網
上載者:User

學obj_c已有一年時間了,開發iphone也有一年時間了。首先學習obj_c的時候,是賃著c/c++的基礎,所學的知識是按c/c++的方式去學習,其實obj_c是c的超集當時一點也沒體會到,其精髓也是完全沒有理解到。隨關時間的推移,慢慢瞭解更多。

obj_c比c/c++更強大,因為它包含了一些設計模式在裡面。聽說java裡幾乎包括了所有的設計模式,不過我沒有深入用過java,曾經用過j2me寫過一點點邏輯。用obj_c最靈活的兩 點就是:category與associative.  我把他們歸為obj_c的擴充機制。category可以擴充一個類的方法,associative可以擴充一個類的屬性。 這兩種方法加起來其功能完全等效於c++中的繼承。

下面看一個associative的列子,需要的標頭檔是:


#import <objc/runtime.h>

static char overviewKey = 'a';NSArray *array = [[NSArray alloc] initWithObjects:@ "One", @"Two", @"Three", nil];// For the purposes of illustration, use initWithFormat: to ensure // we get a deallocatable string NSString *overview = [[NSString alloc] initWithFormat:@"%@", @"First three numbers"];objc_setAssociatedObject ( array, &overviewKey, overview, OBJC_ASSOCIATION_RETAIN); [overview release];NSString *associatedObject = (NSString *) objc_getAssociatedObject (array, &overviewKey);NSLog(@"associatedObject: %@", associatedObject);objc_setAssociatedObject ( array, &overviewKey, nil, OBJC_ASSOCIATION_ASSIGN ); [array release];

objc_setAssociatedObject給array增加了一個屬性,我們可以通過key擷取這個屬性,見上面代碼:objc_getAssociatedObject, 第二個objc_setAssociatedObject設為nil,則是刪除這個屬性。這兒還有一個例子:http://oleb.net/blog/2011/05/faking-ivars-in-objc-categories-with-associative-references/

關於category,大家就google一下吧。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.