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

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

            [[Album alloc] initWithTitle:@"Staring at the Sun" artist:@"U2" coverUrl:@"http://www.easck.com/static/thumbs/album/album_u2_staring%20at%20the%20sun.png" year:@"2000"],
                [[Album alloc] initWithTitle:@"American Pie" artist:@"Madonna" coverUrl:@"http://www.easck.com/static/thumbs/album/album_madonna_american%20pie.png" year:@"2000"]]];
    }
    return self;
}
在 init 里你在数组中加入了 5 张专辑。如果上面的专辑你不喜欢,你可以随意替换成你喜欢的。:]

 

现存在 PersistencyManager.m 添加下面三个方法:

复制代码
- (NSArray*)getAlbums
{
        return albums;
}

 

- (void)addAlbum:(Album*)album atIndex:(int)index
{
        if (albums.count >= index)
            [albums insertObject:album atIndex:index];
        else
        [albums addObject:album];
}

- (void)deleteAlbumAtIndex:(int)index
{
        [albums removeObjectAtIndex:index];
}


这些方法是获取,添加,删除专辑。

 

Build 你的项目,确保所有的代码都能正确编译。


单例模式的使用场合

类只能有一个实例,并且必须从一个为人数值的访问点对其访问。
这个唯一的实例只能通过子类化进行拓展,并且拓展的对象不会破坏客户端代码。

在Objective-C中方法都是公有的,而且OC的语言本身是动态类型的,因此所有类都可以相互发送对方的消息。,并且Cocoa框架使用计数的内存管理方式来维护对象的内存中的生存期。