iOS Design Patterns

iOS Design Patterns – you’ve probably heard the term, but do you know what it means? While most developers probably agree that design patterns are very important, there aren’t many articles on the subject and we developers sometimes don’t pay too much attention to design patterns while writing code.

Design patterns are reusable solutions to common problems in software design. They’re templates designed to help you write code that’s easy to understand and reuse. They also help you create loosely coupled code so that you can change or replace components in your code without too much of a hassle.

If you’re new to design patterns, then I have good news for you! First, you’re already using tons of iOS design patterns thanks to the way Cocoa is built and the best practices you’re encouraged to use. Second, this tutorial will bring you up to speed on all the major (and not so major) iOS design patterns that are commonly used in Cocoa.

The tutorial is divided into sections, one section per design pattern. In each section, you’ll read an explanation of the following:

  • What the design pattern is.
  • Why you should use it.
  • How to use it and, where appropriate, common pitfalls to watch for when using the pattern.

In this tutorial, you will create a Music Library app that will display your albums and their relevant information.

In the process of developing this app, you’ll become acquainted with the most common Cocoa design patterns:

  • Creational: Singleton and Abstract Factory.
  • Structural: MVC, Decorator, Adapter, Facade and Composite.
  • Behavioral: Observer, Memento, Chain of Responsibility and Command.

本文被分为了许多部分,每个部分将讲述一个设计模式。在每个部分中你将会了解到如下内容:

  • 什么是设计模式?
  • 为什么要用设计模式?
  • 如何使用设计模式,以及在使用的时候,哪里是合适的,以及需要注意的问题。
  • 在本文中,你将创建一个音乐库应用,这个应用将显示你的专辑以及它们相关联的信息。
  • 在开发本应用的过程中,你将逐渐熟悉被大量使用的Cocoa设计模式:
  • 创建型:单例(单态)和抽象工厂
  • 结构型:模型-视图-控制器,装饰器,适配器,外观(门面)和组合模式
  • 行为型:观察者,备忘录,责任链和命令模式


Don’t be misled into thinking that this is an article about theory; you’ll get to use most of these design patterns in your music app. Your app will look like this by the end of the tutorial:

finalapp

Getting Started

Download the starter project, extract the contents of the ZIP file, and open BlueLibrary.xcodeproj in Xcode.

There’s not a lot there, just the default ViewController and a simple HTTP Client with empty implementations.

Note: Did you know that as soon as you create a new Xcode project your code is already filled with design patterns? MVC, Delegate, Protocol, Singleton – You get them all for free! :]

Before you dive into the first design pattern, you must create two classes to hold and display the album data.

Navigate to “File\New\File…” (or simply press Command+N). Select iOS > Cocoa Touch and thenObjective-C class and click Next. Set the class name to Album and the subclass to NSObject. Click Nextand then Create.

Open Album.h and add the following properties and method prototype between @interface and @end:

@property (nonatomic, copy, readonly) NSString *title, *artist, *genre, *coverUrl, *year;
 
- (id)initWithTitle:(NSString*)title artist:(NSString*)artist coverUrl:(NSString*)coverUrl year:(NSString*)year;

Note that all the properties are readonly, since there’s no need to change them after the Album object is created.
The method is the object initializer. When you create a new album, you’ll pass in the album name, the artist, the album cover URL, and the year.

Now open Album.m and add the following code between @implementation and @end:

- (id)initWithTitle:(NSString*)title artist:(NSString*)artist coverUrl:(NSString*)coverUrl year:(NSString*)year
{
    self = [super init];
    if (self)
    {
        _title = title;
        _artist = artist;
        _coverUrl = coverUrl;
        _year = year;
        _genre = @"Pop";
    }
    return self;
}

There’s nothing fancy here; just a simple init method to create new Album instances.

Again, navigate to File\New\File…. Select Cocoa Touch and then Objective-C class and click Next. Set the class name to AlbumView, but this time set the subclass to UIView. Click Next and then Create.

Note: If you find keyboard shortcuts easier to use then, Command+N will create a new file,Command+Option+N will create a new group, Command+B will build your project, and Command+Rwill run it.

Open AlbumView.h and add the following method prototype between @interface and @end

- (id)initWithFrame:(CGRect)frame albumCover:(NSString*)albumCover;

Now open AlbumView.m and replace all the code after @implementation with the following code:

@implementation AlbumView
{
    UIImageView *coverImage;
    UIActivityIndicatorView *indicator;
}
 
- (id)initWithFrame:(CGRect)frame albumCover:(NSString*)albumCover
{
    self = [super initWithFrame:frame];
    if (self)
    {
 
        self.backgroundColor = [UIColor blackColor];
        // the coverImage has a 5 pixels margin from its frame
        coverImage = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, frame.size.width-10, frame.size.height-10)];
        [self addSubview:coverImage];
 
        indicator = [[UIActivityIndicatorView alloc] init];
        indicator.center = self.center;
        indicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
        [indicator startAnimating];
        [self addSubview:indicator];
    }
    return self;
}
 
@end

The first thing you notice here is that there’s an instance variable named coverImage. This variable represents the album cover image. The second variable is an indicator that spins to indicate activity while the cover is being downloaded.

In the implementation of the initializer you set the background to black, create the image view with a small margin of 5 pixels and create and add the activity indicator.

Note: Wondering why the private variables were defined in the implementation file and not in the interface file? This is because no class outside the AlbumView class needs to know of the existence of these variables since they are used only in the implementation of the class’s internal functionality. This convention is extremely important if you’re creating a library or framework for other developers to use.

Build your project (Command+B) just to make sure everything is in order. All good? Then get ready for your first design pattern! :]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值