开发者

iOS: Adding class method to the application delegate?

开发者 https://www.devze.com 2023-03-31 06:08 出处:网络
Is ok if I add class methods that I need over all my project in the application delegate? and then I i开发者_运维百科mport the delegate in the current UIViewController and I invoke the method: [MyApp

Is ok if I add class methods that I need over all my project in the application delegate?

and then I i开发者_运维百科mport the delegate in the current UIViewController and I invoke the method: [MyAppDelegate classMethod];

Is a good approach ?

thanks


I set up an APP_DELEGATE macro that is defined as:

#define APP_DELEGATE ((AppDelegate *)[[UIApplication sharedApplication] delegate])

... so when I need to use it, I just code:

[APP_DELEGATE someInstanceMethod];

So yes, I use instance methods instead (for simplicity). Just define this macro in your AppDelegate.h and include it wherever you need it.


I think it should be fine, but I would only do it if it a) makes sense, and b) is truly the only place for that method. I'd think long and hard about whether that functionality belongs in the delegate or in some other singleton or shared class.


I would say that it's an acceptable approach but I would not recommend it. It depends on what the methods you are taking about do. For example, if you want to be able to access your data model from everywhere in your app, it's better to use a singleton, so that you separate the model completely from the rest of the app.


it's depending upon ur app needs or context.

if u r going to access class variables then u can choose class methods to create.

but u cannot access the instance variables.

but my choice is instance method which will operate on both class variable and instance variable.

The difference between class methods and instance methods are

Class methods

  • Operate on Class variables (they can not access instance variables)
  • Do not require an object to be instantiated to be applied
  • Sometimes can be a code smell (some people who are new to OOP use as a crutch to do Structured Programming in an OO enviroment)

Instance methods

  • Operate on instances variables and class variables
  • Must have an instanciated object to operate on
0

精彩评论

暂无评论...
验证码 换一张
取 消