詳解Objective_C擴展機制學(xué)習(xí)
Objective_C擴展機制學(xué)習(xí)是本文要介紹的內(nèi)容,學(xué)Objective_C已有一年時間了,開發(fā)iphone也有一年時間了。首先學(xué)習(xí)Objective_C的時候,是賃著c/c++的基礎(chǔ),所學(xué)的知識是按c/c++的方式去學(xué)習(xí),其實Objective_C是 C 的超集當(dāng)時一點也沒體會到,其精髓也是完全沒有理解到。隨關(guān)時間的推移,慢慢了解更多。
Objective_C比c/c++更強大,因為它包含了一些設(shè)計模式在里面。聽說java里幾乎包括了所有的設(shè)計模式,不過我沒有深入用過java,曾經(jīng)用過j2me寫過一點點邏輯。用Objective_C最靈活的兩 點就是:category與associative. 我把他們歸為Objective_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];
- 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設(shè)為nil,則是刪除這個屬性。
這兒還有一個例子:http://oleb.net/blog/2011/05/faking-ivars-in-objc-categories-with-associative-references/關(guān)于category,大家就google一下吧。
小結(jié):詳解Objective_C擴展機制學(xué)習(xí)的內(nèi)容介紹完了,希望通過本文的學(xué)習(xí)對你有所幫助!