Re: Help Mixing Objective-C & Objective-C++
Re: Help Mixing Objective-C & Objective-C++
- Subject: Re: Help Mixing Objective-C & Objective-C++
- From: Gwynne Raskind <email@hidden>
- Date: Thu, 24 Feb 2011 04:43:18 -0500
On Feb 24, 2011, at 3:58 AM, Andreas Grosam wrote:
>> You can't, but you can declare protocols for your ObjC++ classes in separate headers then have the ObjC classes interact with "NSObject<Foo>" instead of Foo objects directly.
>>
>> FooProtocol.h
>>
>> @protocol Foo
>> // methods the pure ObjC classes need to see
>> @end
>>
>> Foo.h
>>
>> #import "FooProtocol.h"
>> @interface Foo : NSObject <Foo>
>> ...
>>
>> Foo.mm
>> #import "Foo.h"
>> // do C++ things here
>>
>> Bar.m
>>
>> #import "FooProtocol.h"
>> // do things with NSObject<Foo>
> This would be an excellent approach, since protocols are the real and pure interfaces -- like "formal" duck-typing :)
>
> However, with protocols alone you cannot create objects - you need some sort of factory method, declared in some other class:
>
> id<Foo> myFooObject = [someObject newFoo];
>
> Note: someObject can be a class object or an instance object. It just needs to implement the factory methods. The resulting object can be an instance of any class, it doesn't need to be class Foo.
You can use protocols alone to do object creation with a little runtime trickery. I'm quite fond of this small set of language "extensions":
<http://code.google.com/p/libextobjc/>
For this situation, I was thinking of the "concrete protocol" implementation provided by the library, which I've used several times to plug functionality into classes when I couldn't change the inheritance. Other languages call these traits.
(And while on the subject of language extensions, I also shamelessly plug for Michael Ash's MAGenerator class. +1 to get both that and libextobjc constructs into Objective-C 3.)
-- Gwynne
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden