Jeames Bone
Jeames Bone

Reputation: 564

Objective-C inheritance and type casting

I have a superclass O with a property UIView *view.

@interface O : NSObject
{
    UIView *view;
}

@property (nonatomic, weak) UIView *view;

@end

UIView sublass:

@interface myView : UIView

@property (nonatomic, weak) UIColor color;

I then have a sublass of O which has the following in its init:

view = [[myView alloc] init];
view.color = [UIColor redColor];

color is a property of myView used in some custom drawing code.

This causes the compiler to crash because UIView does not have a property color. I would be able to set the value using the setColor method, but it would be nice to be able to access the property via dot syntax.

Is there a way to do this?

Upvotes: 0

Views: 262

Answers (4)

Pavel Reznikov
Pavel Reznikov

Reputation: 3208

You could declare your O using myView:

O.h:

@class myView;

@interface O: NSObject {
    myView *view;
}
....
@end

O.m:

#import "myView.h"

....

In this case by declaring @class myView you don't need to import myView.h in O.h which is good. You just telling to compiler that there is a myView somewhere else. Now you could use your custom properties of myView instance.

The other thing if you're sure that O.view is always of type myView you could call setter like so:

[view setColor:theColor];

but I don't recommend this because if view will be an instance of some other UIView class you will get error, that there is no selector setColor.

I strongly recommend you to declare view property with proper class.

Upvotes: 0

Saurabh Passolia
Saurabh Passolia

Reputation: 8109

edited:

in your specific case you need to declare view as myView *view instead of UIView in your .h file. then you will have access of custom color property.

Upvotes: 1

coverback
coverback

Reputation: 4413

How would you be able to use setColor:? I don't see such a method for UIView. You can use backgroundColor property, and access it both with dot and method notation.

As for the dot vs. method notation, for all properties assigning to a .propertyName would be same as calling setPropertyName:. You wouldn't be able to call dot notation only if setSomething isn't a @property, just an explicitly declared method, but in Apple's framework I don't think it's possible.

Upvotes: 0

V-Xtreme
V-Xtreme

Reputation: 7333

Try this:

self.view.backgroundColor=[UIColor redColor];

Upvotes: 0

Related Questions