开发者

Return the object of which something is a property?

Lets say I have an object with a nu开发者_运维问答mber of properties, one of them being a CALayer.

Throughout my view, I have to hitTest layers. After I've got the layer, I then need to get at the object of which the layer is a property, or 'to which it belongs'. Is there anyway to return the owner of a property?

Thanks!


We have three different things here:

  1. The property
  2. The instance variable behind the property
  3. The CALayer

These are three distinct things. The property belongs to the object's class, and tells the compiler how to go about accessing the instance variable (if I can be a little bit hand-wavy). The instance variable belongs to the object, and points to the CALayer. And the CALayer just does its own little CALayer thing.

Several different instance variables used by any number of properties either from the same object or many different objects can all point to that same CALayer object.

So the question becomes: Does an object keep a list of all the variables that are pointing to it?

And the answer is: Unfortunately, no.


One approach is to iterate through your objects, comparing the layer property to the CALayer retrieved by hit-testing:

MyObject *theObject = nil;
for ( MyObject *obj in self.objects ) {
    if ( obj.layer == theLayer ) {
        theObject = obj;
        break;
    }
}

Another approach is to subclass CALayer and add ivar/property pointing to the object it represents. To avoid retain cycles it should be @property(assign) MyObject* representedObject. It makes getting the object trivial, but requires subclassing CALayer.


I wold suggest you pass around the parents of the CALayers instead of the actual layers when you do the hit-testing, so that you never need to back up to the parent.

You ca not find the parent of a property object, unless you implemented a both-ways relation. Both-ways relations are generally bad, since it can easily introduce retain cycles.

The general solution to this in Cocoa is to use delegates, turns out that the delegate for a CALayer is the UIView it is backing. So in the case of most CALayer instances you can back up to it's parent through the delegate. Do notice I say most, not all, so it is not a silver bullet.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜