Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between [object variable] and object.variable in Obj-C?

I was working on a program today and hit this strange bug. I had a UIButton with an action assigned. The action was something like:

-(void) someaction:(id) e
{
    if ([e tag]==SOMETAG)
    {
        //dostuff
    }
}

What confuses me is that when I first wrote it, the if line was

if (e.tag==SOMETAG)

XCode refused to compile it, saying

error: request for member 'tag' in 'e', which is of non-class type 'objc_object*'

but I thought the two were equivalent.

So under what circumstances are they not the same?

like image 741
John Smith Avatar asked Jul 04 '26 12:07

John Smith


1 Answers

Using the dot notation is only possible if the variable has an associated property declared, or if there are Key-Value-Coding compliant accessor methods available. The property syntax allows you to 'synthesise' accessor methods for your variable that are Key-Value-Coding compliant, and really, this is how the dot notation works.

When a property is declared, someObject.variable is equivalent to [someObject variable].

When an object is typed as id, the compiler isn't aware of any properties the object has. id is a pointer to any object, effectively a void*.

You could cast your object to the type that you expect it to be, which would allow you to then use the property syntax.

((MyObject*)e).tag
like image 151
Jasarien Avatar answered Jul 06 '26 02:07

Jasarien



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!