2

メソッド内から 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_getInstanceVariableobject_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

4

2 に答える 2

0

Objective-C でのオブジェクトのプロパティの配列の取得からのテストされていないコード

id currentClass = [self class];
NSString *propertyName;
unsigned int outCount, i;
objc_property_t *properties = class_copyPropertyList(currentClass, &outCount);
for (i = 0; i < outCount; i++) {
    objc_property_t property = properties[i];
    propertyName = [NSString stringWithCString:property_getName(property)];
    NSLog@("The propertyName is %@",propertyName);
}
于 2012-06-06T11:19:14.263 に答える
0

ループを実行せずに特定のプロパティ名を取得する簡単な方法

カスタムオブジェクトが以下のようなものだとしましょう

@interface StoreLocation : NSObject
@property (nonatomic, strong) NSString *city;
@property (nonatomic, strong) NSNumber *lat;
@property (nonatomic, strong) NSNumber *lon;
@property (nonatomic, strong) NSString *street;
@property (nonatomic, strong) NSString *state;
@property (nonatomic, strong) NSString *code;
@end


@interface AppleStore : NSObject

@property (nonatomic, strong) StoreLocation *storeLocation;

@end

目的のマクロの下では、望ましい結果が得られます

#define propertyKeyPath(property) (@""#property)
#define propertyKeyPathLastComponent(property) [[(@""#property)componentsSeparatedByString:@"."] lastObject]

以下のコードを使用してプロパティ名を取得します

NSLog(@"%@", propertyKeyPath(appleStore.storeLocation)); //appleStore.storeLocation
NSLog(@"%@", propertyKeyPath(appleStore.storeLocation.street)); //appleStore.storeLocation.street
NSLog(@"%@", propertyKeyPathLastComponent(appleStore.storeLocation)); //storeLocation
NSLog(@"%@", propertyKeyPathLastComponent(appleStore.storeLocation.street)); //street

ソース: http://www.g8production.com/post/78429904103/get-property-name-as-string-without-using-the-runtime

于 2014-07-25T04:28:33.507 に答える