1

I've got a fixed controller with dynamic views as its view. I want to set value for property of a certain view.

Here's code in the controller as below:

@property (nonatomic, retain) Class viewClass;

- (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view.
        self.view =  _viewClass.new;
        if ([_viewClass resolveInstanceMethod:@selector(lineAdded)]) {
            [_viewClass setValue:@YES forKey:@"lineAdded"];
        }
        self.view.backgroundColor = [UIColor whiteColor];
}

In * the certain* view, I've got a property like this.

@property (nonatomic, assign) BOOL lineAdded;

It reminds me

Undeclared selector 'lineAdded'

When I run, it just skip if condition and go on.

My question is: is it impossible to set property when the class it belongs to isn't specified?

Hope somebody could help me. Thanks in advance.

4

2 回答 2

0

您可以通过让编译器看到lineAdded选择器的声明来消除警告。一个包含该属性声明的头文件,或者#import以另一种方式声明它,例如:

@protocol DummyProtocol
@property (nonatomic, unsafe_unretained) BOOL lineAdded;
@end

其次,设置属性的值不需要lineAdded选择器。它需要setLineAdded:选择器。

第三,检查是否self.view响应的正确方法setLineAdded:是询问它,如下所示:

    if ([self.view respondsToSelector:@selector(setLineAdded:)]) {
        [self.view setValue:@YES forKey:@"lineAdded"];
    }

第四,您询问_viewClass其实例是否响应lineAdded,但随后您询问_viewClass对象本身(而不是self.view它的实例)设置其自己的lineAdded属性。我在上面的代码中修复了这个问题。

第五,您应该分配给self.viewin loadView,而不是 in viewDidLoad

毕竟,如果它不是设置lineAdded,那么您的视图(无论您选择什么类)根本不会响应setLineAdded:.

于 2015-12-19T10:23:50.970 回答
0

当您设置@YES. 您应该声明它NSNumber而不是使用原始数据类型:BOOL. 当你检索时,你应该使用-(BOOL)boolean方法来检索它。至于resolveInstanceMethod,我认为您应该查看此文档以确保您输入的逻辑正确。

https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtDynamicResolution.html

于 2015-12-19T10:22:46.040 回答