2013/05/29

Access to properties of an id type object

There are classes named ViewController1 and ViewController2. And their objects are viewController1 and viewController2. Both classes have properties like hoge or foo or something like that.
I wanted to send a message to the one object which is decided by the conditions.
Please take a look of next code :
{
    if (flag) {
        viewController1.hoge = hoge;
        viewController1.foo = foo;
    } else {
        viewController2. hoge = hoge;
        viewController2.foo = foo;
    }
}
↑This is ok, but if there were many properties, I would have to write many repeated code. Therefore I tried to get a reference by condition at first and set properties later as follows :
{
    id targetViewController;
    if (flag) {
        targetViewController = viewController1;
    } else {
        targetViewController = viewController2;
    }

    targetViewController.hoge = hoge;
    targetViewController.foo = foo;

}
↑A type of targetViewController is not decided whether ViewController1 or ViewController2, therefore I used id type. But Xcode showed an error message against this code and never build.

Property not found on object of type 'id'
Property 'hoge' not found on object of type 'id'

Well, you may be right… then what should I do?
I tried some code and found the answer :
{
    [targetViewController setHoge:hoge];
    [targetViewController setFoo:foo];
}
I don't know why but anyway the error message has disappeared when the code access to the properties by using the setter.
Develop | Comments(0) | Trackback(0)
 | HOME | Next »