简体   繁体   English

iOS通用应用程序类架构

[英]iOS Universal App Class Architecture

What is the correct way to implement classes in an Universal App? 在Universal App中实现类的正确方法是什么?

I currently have two xib (one for each device), each xib calls the same class and inside that class I have a conditional statement checking what type of device is currently running the app and do the corresponding code for each one. 我目前有两个xib(每个设备一个),每个xib调用相同的类,在该类中,我有一个条件语句,检查当前正在运行该应用程序的设备类型,并为每个设备执行相应的代码。

I'm confused if this is the correct structure, or do I have to create a base class and then extend that class for each of the devices to only overwrite what corresponds to each one? 如果这是正确的结构,我会感到困惑,还是我必须创建一个基类,然后为每个设备扩展该类以仅覆盖与每个设备相对应的内容?

I personally try to reuse code where I can but many developers do like to create separate classes for iPhone and iPad versions to avoid "spaghetti code". 我亲自尝试重用代码,但许多开发人员确实喜欢为iPhone和iPad版本创建单独的类,以避免出现“意大利面条式代码”。 It completely depends on the complexity of the app you are writing. 这完全取决于您正在编写的应用程序的复杂性。 If it's a simple app then I see no reason to just provide logic to test for the device and execute different code based on that vs creating multiple classes for each. 如果它是一个简单的应用程序,那么我认为没有理由只提供逻辑来测试设备并基于该逻辑执行不同的代码,而不是为每个设备创建多个类。 Although, there are many benefits to creating separate code for each such as unit testing or easy updating of iPad specific code and vice versa. 虽然,为每个代码创建单独的代码有很多好处,例如单元测试或iPad特定代码的轻松更新,反之亦然。 I have seen successful developers use both methodologies and both work well if you document and pragma mark your code correctly. 我已经看到成功的开发人员会同时使用这两种方法,并且如果您正确记录文档和编译指示标记您的代码,那么两者都可以很好地工作。

Here is an example of using diff classes 是使用diff类的示例

You can always just create a simple class that returns the device type as well if typing out the full test bothers people. 您总是可以创建一个简单的类来返回设备类型,如果键入完整的测试会让人感到烦恼。 This is handy if you want to test for things like iPod and other device types. 如果您想测试iPod和其他设备类型,这将很方便。 Most times than not this is the approach I use unless the project is very large and the classes begin to feel cluttered. 多数情况下,除非项目非常大且类开始变得混乱,否则我通常会采用这种方法。

// TestDevice.h
@interface TestDevice : NSObject

+ (BOOL)isIpad;

@end

// TestDevice.m
#import "TestDevice.h"

@implementation TestDevice

+ (BOOL)isIpad
{
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
        return YES;

    return NO;
}

@end

Then just add it to your .pch and you can reuse it anywhere in the app by calling... 然后只需将其添加到您的.pch中,即可通过调用...在应用程序中的任何位置重用它。

if ([TestDevice isIpad]) {
    // Something
}
else {
     // Something else
}

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

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