2012-09-25 80 views
2

我聲明瞭一個類擴展接口,它添加了變量。是否可以訪問該類別中的那些變量?在類別類中使用ObjC類擴展的變量

+0

如果類別是在擴展名相同的編譯單元中聲明的,並且該變量是'public',則應該可以訪問它,但我不確定。你試過了嗎? – dasblinkenlight

+0

...是「公開」一個ObjC關鍵字? – user732274

+2

@ user732274關鍵字'@ public'是,但它實際上只是一個編譯器提示。任何對象都可以隨時從本身獲取任何實例變量,因爲objc是純粹動態的語言。 –

回答

1

當然 - 任何變量是通過運行時可以訪問,即使是不可見的@interface

SomeClass.h

@interface SomeClass : NSObject { 
    int integerIvar; 
} 

// methods 

@end 

SomeClass.m

@interface SomeClass() { 
    id idVar; 
} 

@end 

@implementation SomeClass 

// methods 

@end 

SomeClass + Category.m

@implementation SomeClass(Category) 

-(void) doSomething { 
    // notice that we use KVC here, instead of trying to get the ivar ourselves. 
    // This has the advantage of auto-boxing the result, at the cost of some performance. 
    // If you'd like to be able to use regex for the query, you should check out this answer: 
    // http://stackoverflow.com/a/12047015/427309 
    static NSString *varName = @"idVar"; // change this to the name of the variable you need 

    id theIvar = [self valueForKey:varName]; 

    // if you want to set the ivar, then do this: 
    [self setValue:theIvar forKey:varName]; 
} 

@end 

您也可以使用KVC得到了UIKit框架或類似的高德班,同時更易於比純運行時,黑客使用。

+0

這就是我得到的結果:[ setValue:forUndefinedKey:]:這個類不是密鑰idVar的編碼兼容密鑰值。 – user732274

+0

@ user732274顯然你只能在知道該類有一個名爲'idVar'的變量時才能使用它。在你的情況下,用你需要的變量替換它。 –

+0

我把它命名爲idVar(並且我得到那個錯誤) – user732274