実行時に object-c にオブジェクトがあり、そこから KVC キーのみを知っており、このプロパティの戻り値の型を検出する必要があります (たとえば、NSArray か NSMutableArray かを知る必要があります)。どうすればそれを行うことができますか? ?
6 に答える
あなたはランタイム プロパティのイントロスペクションについて話しているのですが、これはたまたま、Objective-C が非常に得意とするものです。
あなたが説明した場合、私はあなたが次のようなクラスを持っていると仮定しています:
@interface MyClass
{
NSArray * stuff;
}
@property (retain) NSArray * stuff;
@end
これは、次のような XML でエンコードされます。
<class>
<name>MyClass</name>
<key>stuff</key>
</class>
この情報から、クラスを再作成し、それに適切な値を与えたいと考えていますstuff
。
これは次のようになります。
#import <objc/runtime.h>
// ...
Class objectClass; // read from XML (equal to MyClass)
NSString * accessorKey; // read from XML (equals @"stuff")
objc_property_t theProperty =
class_getProperty(objectClass, accessorKey.UTF8String);
const char * propertyAttrs = property_getAttributes(theProperty);
// at this point, propertyAttrs is equal to: T@"NSArray",&,Vstuff
// thanks to Jason Coco for providing the correct string
// ... code to assign the property based on this information
Apple のドキュメント (上にリンクされています) には、propertyAttrs
.
安い答え:ここで NSObject+Properties ソースを使用してください。
これは、上記と同じ方法論を実装しています。
推奨される方法は、NSObject Protocolで定義されたメソッドを使用することです。
具体的には、何かがクラスのインスタンスであるか、そのクラスのサブクラスのインスタンスであるかを判断するには、 を使用します-isKindOfClass:
。何かが特定のクラスのインスタンスであり、そのクラスのみ (つまり、サブクラスではない) であるかどうかを判断するには、次を使用します。-isMemberOfClass:
したがって、あなたの場合、次のようなことをしたいと思うでしょう:
// Using -isKindOfClass since NSMutableArray subclasses should probably
// be handled by the NSMutableArray code, not the NSArray code
if ([anObject isKindOfClass:NSMutableArray.class]) {
// Stuff for NSMutableArray here
} else if ([anObject isKindOfClass:NSArray.class]) {
// Stuff for NSArray here
// If you know for certain that anObject can only be
// an NSArray or NSMutableArray, you could of course
// just make this an else statement.
}
isKindOfClass メッセージを使用できます
if([something isKindOfClass:NSArray.class])
[somethingElse action];
プロパティが定義されていることがわかっている場合:
id vfk = [object valueForKey:propertyName];
Class vfkClass = vfk.class;
また、isKindOfClass、isSubClass などと比較してください。