Nat! bio photo

Nat!

Senior Mull

Twitter Github Twitch

mulle_objc: the trouble with @property

Continued from mulle_objc: present and absent language features.


@property in MulleObjC

The mulle-objc-runtime is what the compiler considers a “fragile” runtime, that means the relative location of an instance variable (ivar) is known at compile time.

The problem with @dynamic

Classes.h:

@interface Foo
@property long   value;
@end

@interface Bar : Foo
@property long   anotherValue;
@end

Foo.m:

@implementation Foo
@dynamic value;
@end

Bar.m:

@implementation Bar
@synthesize value;
@end

The property synthesizer in Bar.m can’t know, that Foo is using @dynamic and that it therefore did not implement the instance variable _value. Therefore the offset to _anotherValue will be wrong.

Solution #1

  • Emit an instance variable regardless of @dynamic or not.

Solution #2

  • @property must specify a new keyword dynamic. @property(dynamic) long value;

Solution #3

  • Do not allow @dynamic

The problem with @synthesize

As above, but with the following modifications in

Classes.h:

@interface Foo
{
   long   _storage;
}
@property long   value;
@end


@interface Bar : Foo
@property long   anotherValue;
@end

Foo.m:

@implementation Foo
@synthesize value = _storage;
@end

Bar will not know that value is actually using _storage and will have to assume, that Foo has two instance variables _storage and _value.

Solution #1

Do not allow @synthesize with a different instance variable name, than the one the auto-synthesizer would generate.

Solution #2

@property must specify the required variable with a new keyword synthesize @property(synthesize=_storage) long value;

Solution #3

  • Do not allow @synthesize. (Always auto-synthesize)

The problem with @protocol

Classes.h:

@protocol Baz
@property long   value;
@end

@interface Foo < Baz>
@end

Foo.m:

@implementation Foo
@end

Solution #1

Do nothing. The compiler will warn about the missing property.

Solution #2

Value will get auto-synthesized into Foo.


What to do ?

In the future it may be nice to implement the second solution. For now the first solutions look the best.

What happens with a readonly @property ?

A readonly property also autosynthesizes an ivar with above rules. But it does not generate a setter. If you store a retained value in this ivar you have to release it during -finalize or -dealloc.


Continue to mulle_objc: ivar layout with @property.


Post a comment

All comments are held for moderation; basic HTML formatting accepted.

Name:
E-mail: (not published)
Website: