简体   繁体   中英

Code reuse in iOS applications

i am very new to ios development, rather i have just started work on my first app. Now my app has a home button on almost every page and behind that button the same code snippet is called to move to the home screen. This is a lot of duplicate code in every controller that has a home button. And it is just an example. There are many other scenarios like this and programmer still learning to code, i think its bad practice as any change will have to be made separately on every controller.

So my question, what are the best practices in scenarios like this when coding for ios??

One easy thing to do in this situation is to make a UIViewController subclass ( MyAppMasterVC , for instance) and define your button as so:

- (IBAction)myCommonButtonAction { // code and such }

In all of your view controllers, inherit from this one instead of UIViewController (a la @interface MyNewViewController : MyAppMasterVC ).

首先要做的是了解有关OO编程和类层次结构的更多信息,并了解如何为所有类似控制器创建公共基类。

Software development for iOS in this sense is no different from any other software development. Simply merge your logic into some common class or function, and use that as it deems appropriate. It often turns out that you don't know what part could be common and reusable until you write multiple pieces of code, and only then you realize that it all could be one function. The process of organising existing code, cleaning it up, making it more readable and reusable is called code refactoring . There are a lot of books on refactoring that explain different design patterns , techniques and processes of making your code better. I recommend you read some of them to get a better picture.

This problem is language/platform agnostic. The term many use is 'DRY', an acronym for 'Do not Repeat Yourself'.

Here is a SO search . This should help you with the typical problems and uses, so you can better determine whether you can, when you should, and how to approach this type of problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM