メソッド内から StringValue としてプロパティ名を取得する方法を探しています。
まあ言ってみれば:
私のクラスには、タイプ UILabel からの X サブビューがあります。
@property (strong, nonatomic) UILabel *firstLabel;
@property (strong, nonatomic) UILabel *secondLabel;
[...]
等々。
メソッド foo 内で、ビューは次のように反復されます。
-(void) foo
{
for (UIView *view in self.subviews) {
if( [view isKindOfClass:[UILabel class]] ) {
/*
codeblock that gets the property name.
*/
}
}
}
結果は次のようになります。
THE propertyName(NSString) OF view(UILabel) IS "firstLabel"
class_getInstanceVariable、object_getIvar、およびproperty_getNameを成功せずに試しました。
たとえば、次のコード:
[...]
property_getName((void*)&view)
[...]
戻り値:
<UILabel: 0x6b768c0; frame = (65 375; 219 21); text = 'Something'; clipsToBounds = YES; opaque = NO; autoresize = RM+BM; userInteractionEnabled = NO; layer = <CALayer: 0x6b76930>>
しかし、私はこの種の結果を探しています: " firstLabel " 、 " secondLabel " など。
解決済み
Graver の返信で説明されているように、解決策は次のとおりです。 Ivars の名前を返す class_copyIvarList。
Ivar* ivars = class_copyIvarList(clazz, &count);
NSMutableArray* ivarArray = [NSMutableArray arrayWithCapacity:count];
for (int i = 0; i < count ; i++)
{
const char* ivarName = ivar_getName(ivars[i]);
[ivarArray addObject:[NSString stringWithCString:ivarName encoding:NSUTF8StringEncoding]];
}
free(ivars);
投稿を参照してください: https://stackoverflow.com/a/2302808/1228534 および Objective C Introspection/Reflection