What is a method template template in cocoa with a C object? (Thinking language comparison)

Here, Java and C ++ can easily implement it using a virtual function. What about Object C to implement this pattern? Any example in cocoa touch (iOS)?

+3
source share
3 answers

As jer already noted , all Objective-C methods are essentially virtual. This is a feature of the language that does not quite match other C-like languages. However, the basics of a template template can still be achieved in Objective-C, by manually forcing subclasses to implement certain functions. For example (using the convention in your related Wikipedia article):

@interface Game
{
    int playersCount;
}
- (void)playOneGame:(int)numPlayers;
// "virtual" methods: 
- (void)initializeGame;
- (void)makePlay:(int)player;
- (BOOL)endOfGame;
- (void)printWinner;
@end

@implementation Game
- (void)initializeGame         { NSAssert(FALSE); }
- (void)makePlay:(int player)  { NSAssert(FALSE); }
- (BOOL)endOfGame              { NSAssert(FALSE); return 0; }
- (void)printWinner            { NSAssert(FALSE); }
- (void)playOneGame:(int)numPlayers
{
    //..
}
@end

Game "" , . , ( ++ Java) ( Objective-C).

, playOneGame:, (*) init:

@implementation Game
...
- (void)init
{
    if ((self = [super init]) == nil) { return nil; }

    IMP my_imp = [Game instanceMethodForSelector:@selector(playOneGame:)];
    IMP imp = [[self class] instanceMethodForSelector:@selector(playOneGame:)];
    NSAssert(imp == my_imp);

    return self;
}
...
@end

(*) , 100% - , playOneGame:, Objective-C instanceMethodForSelector: .

+4

Objective-C ++ virtual.

0

Objective-C , -. , .

,

enter image description here

 @interface Worker : NSObject

- (void) doDailyRoutine;
- (void) doWork; // Abstract
- (void) comeBackHome; 
- (void) getsomeSleep;
@end

@implementation Worker

- (void) doDailyRoutine {
  [self doWork];
  [self comeBackHome];
  [self getsomeSleep];
  }

 - (void) doWork { [self doesNotRecognizeSelector:_cmd]; }
 - (void) comeBackHome { [self doesNotRecognizeSelector:_cmd]; }
 - (void) getsomeSleep { [self doesNotRecognizeSelector:_cmd]; }
 // [self doesNotRecognizeSelector:_cmd] it will force to call the subclass          Implementation
@end

@interface Plumber : Worker
@end

@implementation Plumber

- (void) doWork { NSLog(@"Plumber Work"); }

@end
@interface Electrician : Worker

@end

@implementation Electrician

- (void) doWork { NSLog(@"Electrician Work"); }

@end
@interface Cleaner : Worker

@end

@implementation Cleaner

- (void) doWork { NSLog(@"Cleaner Work"); }

@end

dowork() , , Cocoa Frameworks.

, " ".

0

Source: https://habr.com/ru/post/1782532/


All Articles