简体   繁体   English

iOS应用程序中的代码重用

[英]Code reuse in iOS applications

i am very new to ios development, rather i have just started work on my first app. 我是ios开发的新手,而我刚刚开始研究我的第一个应用程序。 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?? 所以我的问题是,在为ios编码时,这种场景中的最佳实践是什么?

One easy thing to do in this situation is to make a UIViewController subclass ( MyAppMasterVC , for instance) and define your button as so: 在这种情况下,一件容易的事情就是创建一个UIViewController子类(例如MyAppMasterVC )并定义你的按钮:

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

In all of your view controllers, inherit from this one instead of UIViewController (a la @interface MyNewViewController : MyAppMasterVC ). 在所有视图控制器中,从这一个继承而不是UIViewController (一个@interface MyNewViewController : MyAppMasterVC )。

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

Software development for iOS in this sense is no different from any other software development. 在这个意义上, iOS的软件开发与任何其他软件开发没有什么不同。 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'. 许多使用的术语是'DRY','不要重复你自己'的首字母缩写词。

Here is a SO search . 这是SO搜索 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. 这应该可以帮助您解决典型问题和用途,因此您可以更好地确定是否可以,何时应该以及如何处理此类问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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