0

上記のコンポーネントのサブクラスを作成せずに、Interface Builderのユーザー定義ランタイム属性セクションに文字列のようなプロパティを設定する方法があるかどうか誰かが知っていますか?たとえば、後で使用するインターフェイスに各コンポーネントのメタデータ値を保存したいとします。メタデータプロパティを追加するためにサブクラスや各コンポーネントを作成する必要はありません。

これは私が思いついたアプローチの1つです。意見?

#import <UIKit/UIKit.h>
#import <objc/runtime.h>


@interface UIControl(MetaData)

@property (nonatomic, retain) id entityProperty;

@end

@implementation  UIControl(MetaData)

static char const * const EntityPropertyKey = "EntityProperty";

@dynamic entityProperty;

- (id)entityProperty {
    return objc_getAssociatedObject(self, EntityPropertyKey);
}

- (void)setEntityProperty:(id)newEntityProperty {
    objc_setAssociatedObject(self, EntityPropertyKey, newEntityProperty,     OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}


@end

..。

if (textField.entityProperty) 
     [managedObject setValue: textField.text forKey:textField.entityProperty];
4

1 に答える 1

1

NSDictionaryをどこかに保持できます。おそらく、オブジェクトの一意のIDを発行し、辞書のidキーによってメタデータを格納するためのメソッドを持つシングルトンオブジェクトに保存できます。UIオブジェクトには、IDが整数の増分である場合に使用できるタグプロパティがあります。その場合、辞書キーはそれらの一意の整数のNSNumbersになります。

このような:

#import <Foundation/Foundation.h>

@interface ACLMetadataManager : NSArray

+(ACLMetadataManager*) sharedMetadataManager;
-(NSUInteger) getUniqueId;
-(void) setObject: (id) object forId:(NSUInteger) theId;
-(id) objectForId:(NSUInteger) theId;

@end

と:

#import "ACLMetadataManager.h"
@implementation ACLMetadataManager { // Private variables
    NSMutableDictionary *_metadata;
    NSUInteger _ids;
}

- (id)init {
    self = [super init];
    if (self) {
        _metadata = [[NSMutableDictionary alloc] init];
    }
    return self;
}

+(ACLMetadataManager*) sharedMetadataManager { // Singleton getter
    static ACLMetadataManager *instance;
    if (instance != nil) {
        return instance;
    }
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
    static dispatch_once_t oneTimeThread;
    dispatch_once(&oneTimeThread, ^(void) {
        instance = [[ACLMetadataManager alloc] init];
    });
#else
    @synchronized(self) {
        instance = [[ACLMetadataManager alloc] init];
    }
#endif
    return instance;
}

-(NSUInteger) getUniqueId { // Increment unique id when getter is called.
    return ++_ids; // Start from 1 because tag is 0 by default.
}

-(void) setObject: (id) object forId:(NSUInteger) theId {
    [_metadata setObject:object forKey:[NSNumber numberWithInteger:theId]];
}

-(id) objectForId:(NSUInteger) theId {
    return [_metadata objectForKey:[NSNumber numberWithInteger:theId]];
}

// Override some methods to ensure singleton stays instantiated.
- (id) retain {
    return self;
}
- (oneway void) release {
    // Does nothing here.
}
- (id) autorelease {
    return self;
}
- (NSUInteger) retainCount {
    return INT32_MAX;
}
@end

使用法:

ACLMetadataManager *metadataManager = [ACLMetadataManager sharedMetadataManager];
myControl.tag = [metadataManager getUniqueId];
[metadataManager setObject:myMetadata forId:myControl.tag];
于 2012-12-15T16:12:59.217 に答える