1

In super class:

@property (strong, nonatomic) Foo *foo;

In sub class:

- (Foo *) foo
{
     if(!super.foo) super.foo = [[Foo alloc] init];
     return super.foo;
}

Does this make sense? Is it even a good idea to have abstract properties?

Martin G
  • 17,357
  • 9
  • 82
  • 98
izk
  • 1,189
  • 2
  • 8
  • 23

1 Answers1

7

Strictly speaking, there is no "abstract class" or "abstract property" in Objective-C, see for example this thread Creating an abstract class in Objective-C for a good overview.

Your approach is not optimal, because it requires that the superclass implements foo and setFoo:, which contradicts the idea of "abstractness".

A better solution is to define a "dynamic property" in the superclass:

@interface SuperClass : NSObject
@property (strong, nonatomic) Foo *foo;
@end

@implementation SuperClass
@dynamic foo;
@end

and explicitly synthesize it in the subclass:

@interface SubClass : SuperClass
@end

@implementation SubClass
@synthesize foo = _foo;
@end

Now you can access foo on a subclass object, but on a superclass object it will cause a runtime exception.

For lazy initialization, you can use the usual pattern, without any "super-tricks":

- (Foo *) foo
{
    if(!_foo) _foo = [[Foo alloc] init];
    return _foo;
}

An alternative approach (also mentioned in above thread) is to use a "protocol" instead of a common superclass:

@protocol HasFoo <NSObject>
- (Foo *)foo;
@end

@interface MyClass : NSObject<HasFoo>
@property(strong, nonatomic) Foo *foo;
@end

@implementation SubClass
- (Foo *) foo
{
    if(!_foo) _foo = [[Foo alloc] init];
    return _foo;
}
@end
Community
  • 1
  • 1
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Thank you Martin. I am still learning to think in Obj-C. This makes a lot of sense. – izk May 08 '13 at 18:47