2

varsを追加するクラス拡張インターフェースを宣言します。そのクラスのカテゴリでそれらの変数にアクセスすることは可能ですか?

4

1 に答える 1

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 などのクラスの iVar を取得することもできますが、純粋なランタイム ハッキングよりも簡単に使用できます。

于 2012-09-25T19:36:21.580 に答える