使用设计模式中的Singleton单例模式来开发iOS应用程序

2020-01-14 22:07:45于海丽

用 iOSCocoa TouchObject-C class 在 API 文件夹下创建一个新的类,名字叫 PersistencyManager,子类选择 NSObject。

打开 PersistencyManager.h,在顶部引入面文件:

#import "Album.h"
然后在 @interface 后面加入下面代码:

复制代码
- (NSArray *)getAlbums;
- (void)addAlbums:(Album*)album atIndex:(int)index;
- (void)deleteAlbumAtIndex:(int)index;
上面的三个方法都需要跟专辑的数据相结合。

 

打开 PersistencyManager.m,在 @implementation 上面添加如下代码:

复制代码
@interface PersistencyManager () {
    NSMutableArray *albums;
}
上面的代码是给类添加了一个扩展,这是另一种给类添加私有方法和私有属性的方法,类外面的成员是看不到这些的。这里,你声明了一个 NSMutableArray 来保存专辑的数据。这是一个可变数组,你可以很容易的添加和删除专辑。

 

现在在 @implementation 下面添加实现代码:

复制代码
- (id)init {
    self = [super init];
    if (self) {
        albums = [NSMutableArray arrayWithArray:@[[[Album alloc] initWithTitle:@"Best of Bowie" artist:@"David Bowie" coverUrl:@"http://www.easck.com/static/thumbs/album/album_david%20bowie_best%20of%20bowie.png" year:@"1992"],
        [[Album alloc] initWithTitle:@"It's My Life" artist:@"No Doubt" coverUrl:@"http://www.easck.com/static/thumbs/album/album_no%20doubt_its%20my%20life%20%20bathwater.png" year:@"2003"],
                [[Album alloc] initWithTitle:@"Nothing Like The Sun" artist:@"Sting" coverUrl:@"http://www.easck.com/static/thumbs/album/album_sting_nothing%20like%20the%20sun.png" year:@"1999"],