Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I declare function prototype for every function?

In Obj-C, what's the best practice for function prototype ? Should I include them for every function in my class or just the one that's needed (i.e a function call happens before a function implementation)

like image 255
Luong Huy Duc Avatar asked Apr 13 '26 06:04

Luong Huy Duc


1 Answers

Best practice is to have exactly one prototype for every function and method you define. Where that prototype should be depends on whether you want to expose the function to the world outside of your class. If you skip a prototype and just include the function body, you'll probably get away with it. (e.g. you could in the example below send your controller a stop from outside the class at runtime.) But it's best to make sure you dot your i's and cross your t's. Notice in my example below that everything is accounted for. Hopefully this helps.

MyAppController.h:

@interface MyAppController : NSObject {
   id thing;
@private
   id noneOfYourBeeswax;
}

@property (nonatomic, readonly) id thing;

-(id)initWithThing:(id)thing;
-(void)start;

@end

MyAppController.m:

@interface MyAppController () // anonymous category

@property (readwrite, retain) id thing;
@property (nonatomic, retain) NSThread *noneOfYourBeeswax;

-(void)start_internal;
-(void)stop;

@end


@implementation MyAppController 

@synthesize thing;
@synthesize noneOfYourBeeswax;

-(id)initWithThing:(id)thing_ {
   if ((self = [super init]) != nil) {
      self.thing = thing_;
   }

   return self;
}


-(void)start {
   // I think I'm doing this wrong but you get the picture
   self.noneOfYourBeeswax = [[[NSThread alloc] initWithTarget:self selector:start_internal object:nil] autorelease];
}

// The real worker
-(void)start_internal {
   while (such and such) {
      // do something useful
   }

   [self stop];
}


-(void)stop {
   // clean up
}

@end
like image 96
QED Avatar answered Apr 15 '26 21:04

QED