superclass - What is the proper way to lazy initialize an abstract property in Objective-C -
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 make sense? idea have abstract properties?
strictly speaking, there no "abstract class" or "abstract property" in objective-c, see example thread creating abstract class in objective-c overview.
your approach not optimal, because requires superclass implements foo
, setfoo:
, contradicts idea of "abstractness".
a better solution define "dynamic property" in superclass:
@interface superclass : nsobject @property (strong, nonatomic) foo *foo; @end @implementation superclass @dynamic foo; @end
and explicitly synthesize in subclass:
@interface subclass : superclass @end @implementation subclass @synthesize foo = _foo; @end
now can access foo
on subclass object, on superclass object cause runtime exception.
for lazy initialization, can use usual pattern, without "super-tricks":
- (foo *) foo { if(!_foo) _foo = [[foo alloc] init]; return _foo; }
an alternative approach (also mentioned in above thread) use "protocol" instead of 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
Comments
Post a Comment