你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> iOS 類增加成員變量

iOS 類增加成員變量

編輯:IOS開發綜合

RT

// 增加成員變量
#import 

@interface NSObject (AddProperty)
@property (nonatomic,strong) NSString *stringProperty;
@property (nonatomic,assign) NSInteger integerProperty;
@end
#import NSObject+AddProperty.h
#import 

//objc_getAssociatedObject和objc_setAssociatedObject都需要指定一個固定的地址,這個固定的地址值用來表示屬性的key,起到一個常量的作用。
static const void *StringProperty = &StringProperty;
static const void *IntegerProperty = &IntegerProperty;
//static char IntegerProperty;
@implementation NSObject (AddProperty)

@dynamic stringProperty;

//set
-(void)setStringProperty:(NSString *)stringProperty{
    //use that a static const as the key
    objc_setAssociatedObject(self, StringProperty, stringProperty, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    //use that property's selector as the key:
    //objc_setAssociatedObject(self, @selector(stringProperty), stringProperty, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
//get
-(NSString *)stringProperty{
    return objc_getAssociatedObject(self, StringProperty);
}
//set
-(void)setIntegerProperty:(NSInteger)integerProperty{
    NSNumber *number = [[NSNumber alloc]initWithInteger:integerProperty];
    objc_setAssociatedObject(self, IntegerProperty, number, OBJC_ASSOCIATION_ASSIGN);
}
//get
-(NSInteger)integerProperty{
    return [objc_getAssociatedObject(self, IntegerProperty) integerValue];
}

@end

// 獲取成員變量列表

@interface NSObject (Property)
-(NSDictionary *)propertyDictionary;

+ (NSArray *)classPropertyList;
@end
#import NSObject+Property.h
#import 
#import 

@implementation NSObject (Property)
-(NSDictionary *)propertyDictionary
{
    //創建可變字典
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    unsigned int outCount;
    objc_property_t *props = class_copyPropertyList([self class], &outCount);
    for(int i=0;i

 

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved