Accessing Method from other Classes Objective-C

前端 未结 8 1528
挽巷
挽巷 2020-11-29 05:57

Looked for an answer for this question, but I haven\'t found a suitable one yet. I\'m hoping you guys (and gals) can help me out! (This is for an iPhone app)

Alrig

8条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 06:47

    Option 1:

    @implementation commonClass
    + (void)CommonMethod:(id)sender  /* note the + sign */
    {
    //So some awesome generic stuff...
        }
    @end
    
    @implementation ViewController2
    
    - (void)do_something... {
        [commonClass CommonMethod];
    }
    
    
    @end
    

    Option 2:

    @implementation commonClass
    - (void)CommonMethod:(id)sender
    {
    //So some awesome generic stuff...
        }
    @end
    
    @implementation ViewController2
    
    - (void)do_something... {
        commonClass *c=[[commonClass alloc] init];
        [c CommonMethod];
        [c release];
    }
    
    @end
    

    Option 3: use inheritance (see Mr. Totland's description in this thread)

    @implementation commonClass
    - (void)CommonMethod:(id)sender
    {
    //So some awesome generic stuff...
        }
    @end
    
    /* in your .h file */
    @interface ViewController2: commonClass
    
    @end
    

    naturally you always need to #import commonClass.h in your view controllers..

提交回复
热议问题