gpt4 book ai didi

objective-c - 在 iOS 类扩展中定义属性

转载 作者:太空狗 更新时间:2023-10-30 03:21:33 25 4
gpt4 key购买 nike

我想在类扩展中向 UITableView 添加一个属性:

@interface UITableViewController ()

@property NSString *entityString;

@end

然后我导入扩展,然后在 UITableViewController 的子类中使用 entityString 属性:

@implementation CustomerTableViewController

- (void)viewDidLoad {
self.entityString = @"Customer";
...
[super viewDidLoad];
}
...

Apple documentation说:

the compiler will automatically synthesize the relevant accessor methods (...) inside the primary class implementation.

但是当我尝试执行它时,出现了这个错误:

-[CustomerTableViewController setEntityString:]: unrecognized selector sent to instance 0x737b670

我做错了什么?也许该属性不能被子类访问?

最佳答案

尝试使用具有关联引用的类别。它更简洁并且适用于 UIButton 的所有实例。

UIButton+Property.h

#import <Foundation/Foundation.h>

@interface UIButton(Property)

@property (nonatomic, retain) NSObject *property;

@end


UIButton+Property.m

#import "UIButton+Property.h"
#import <objc/runtime.h>

@implementation UIButton(Property)

static char UIB_PROPERTY_KEY;

@dynamic property;

-(void)setProperty:(NSObject *)property
{
objc_setAssociatedObject(self, &UIB_PROPERTY_KEY, property, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(NSObject*)property
{
return (NSObject*)objc_getAssociatedObject(self, &UIB_PROPERTY_KEY);
}

@end

//示例用法

#import "UIButton+Property.h"


UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button1.property = @"HELLO";
NSLog(@"Property %@", button1.property);
button1.property = nil;
NSLog(@"Property %@", button1.property);

关于objective-c - 在 iOS 类扩展中定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12252725/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com