How to create global functions in Objective-C

前端 未结 5 1656
攒了一身酷
攒了一身酷 2020-11-30 02:03

I\'m developing an iphone app and I need to have some functions to use globally in my classes.

But how can I do this?

I just tried to create functions.

5条回答
  •  感动是毒
    2020-11-30 02:37

    Two options here. First is create a class method in a static class:

    Header:

    #import 
    
    @interface GlobalStuff : NSObject {}
    
    + (void)printTest;
    
    @end
    

    Implementation:

    #import "functions.h"
    
    @implementation GlobalStuff
    
    + (void) printTest {
      NSLog(@"test");
    }
    

    Call using:

    #import "functions.h"
    
    ...
    [GlobalStuff printTest];
    

    The other option is to declare a global function instead of class:

    Header:

    void GSPrintTest();
    

    Implementation:

    #import 
    #import "functions.h"
    void GSPrintTest() {
      NSLog(@"test");
    }
    

    Call using:

    #import "functions.h"
    ...
    GSPrintTest();
    

    A third (bad, but possible) option would be adding a category to NSObject for your methods:

    Header:

    #import 
    
    @interface NSObject(GlobalStuff)
    - (void) printTest;
    @end
    

    Implementation:

    #import "functions.h"
    
    @implementation NSObject(GlobalStuff)
    - (void) printTest {
      NSLog(@"test");
    }
    @end
    

    Call using:

    #import "functions.h"
    ...
    [self printTest];
    

提交回复
热议问题