iphone - Requiring the presence of a method in an id -


the situation

my custom controller class has following method:

- (void)requestviewcontrollerwithidentifier:(nsstring *)identifier fromobject:(id)object; 

this causes object receive message:

- (uiviewcontroller *)viewcontrollerwithidentifier:(nsstring *)identifier; 

the problem

right now, object id there's no guarantee implements method, , compiler warning when send message.


the solution

i came 2 solutions myself:

  1. use protocol.
  2. make id nsobject , create category nsobject.

they both fine solutions , don't mind choosing 1 of them, but...


the question

...i noticed apple doing odd in gamekit api. gksession has following method:

- (void)setdatareceivehandler:(id)handler withcontext:(void *)context 

handler id, apple requires implement method:

- (void) receivedata:(nsdata *)data frompeer:(nsstring *)peer insession: (gksession *)session context:(void *)context; 

without making use of protocol or category! i'm wondering how , why this? why don't use protocol? enforce method in other way? if this, how can suppress compiler warning?

you can assign variable of type id object type. if know must implement given protocol can assign variable of type within method , invoke method on variable.

as design point, better make protocol explicit , externalise caller compiler can type checking properly. parts of apple's code better others @ this: gamekit @ unhelpful end of things.

defining category not want do, because tells compiler add method every nsobject.

if have protocol:

@protocol yourprotocol <nsobject> - (uiviewcontroller *)viewcontrollerwithidentifier:(nsstring *)identifier; @end 

and define method as:

- (void)requestviewcontrollerwithidentifier:(nsstring *)identifier fromobject:(id <yourprotocol>)object; 

it want. may not strictly necessary in case it's idea have protocol extend nsobject protocol (as above) can call useful stuff -retain, -release, -autorelease, , -respondstoselector. alternative of declaring method follows prevents user using nsproxy-rooted object object parameter.

- (void)requestviewcontrollerwithidentifier:(nsstring *)identifier fromobject:(nsobject <yourprotocol> *)object; 

if it's own use , aren't using proxy objects can quite convenient, should avoid in public apis.


Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

android - layout with fragment and framelayout replaced by another fragment and framelayout -