测试题7
定义2个新类,分别命名为Song/Playlist。Song对象包含歌曲的信息,歌名、艺术家、专辑、歌曲长度;Playlist对象表示一个播放列表,包含播放列表名称和一个歌曲的集合,还应该提供添加和删除歌曲的方法。(Objective-C)
main.m
- #import <Foundation/Foundation.h>
- #import "PlayList.h"
- #import "Song.h"
- int main(int argc, const char * argv[]) {
- @autoreleasepool {
-
- //创建歌曲对象
- Song *s1 = [[Song alloc]init];
- Song *s2 = [[Song alloc]init];
- Song *s3 = [[Song alloc]init];
- Song *s4 = [[Song alloc]init];
- //为对象属性赋值
- s1.songName = @"歌曲1";
- s1.actor = @"艺术家1";
- s1.zhuanji = @"专辑1";
- s1.songTime = 111;
- s2.songName = @"歌曲2";
- s2.actor = @"艺术家2";
- s2.zhuanji = @"专辑2";
- s2.songTime = 222;
- s3.songName = @"歌曲3";
- s3.actor = @"艺术家3";
- s3.zhuanji = @"专辑3";
- s3.songTime = 333;
- s4.songName = @"歌曲4";
- s4.actor = @"艺术家4";
- s4.zhuanji = @"专辑4";
- s4.songTime = 444;
- //创建播放列表对象
- PlayList *list = [[PlayList alloc]init];
- //为列表对象赋值
- list.listName = @"播放列表";
- list.list = [[NSMutableArray alloc]init];
- //调用添加歌曲方法
- [list addSong:s1];
- [list addSong:s2];
- [list addSong:s3];
- [list addSong:s4];
- NSLog(@"----添加歌曲后列表信息----");
- //遍历列表
- for(Song *s in list.list)
- {
- [s songMessage]; // 输出歌曲信息
- }
- //调用删除歌曲方法
- [list deleteSong:s1];
- [list deleteSong:s3];
- NSLog(@"----删除歌曲后列表信息----");
- //遍历列表
- for(Song *s in list.list)
- {
- [s songMessage]; // 输出歌曲信息
- }
-
- }
- return 0;
- }
复制代码
song.h
- #import <Foundation/Foundation.h>
- @interface Song : NSObject
- @property (nonatomic,strong) NSString *songName; // 歌曲名称
- @property (nonatomic,strong) NSString *actor; // 艺术家
- @property (nonatomic,strong) NSString *zhuanji; // 专辑
- @property (nonatomic,assign) int songTime; // 歌曲时间
- - (void) songMessage; //输出歌曲信息
- @end
复制代码
song.m
- #import "Song.h"
- @implementation Song
- - (void)songMessage //输出歌曲信息
- {
- NSLog(@"歌曲名:%@,艺术家:%@,专辑:%@,歌曲长度:%d",_songName,_actor,_zhuanji,_songTime);
- }
- @end
复制代码
PlayList.h
- #import <Foundation/Foundation.h>
- @class Song;
- @interface PlayList : NSObject
- @property (nonatomic,strong) NSString * listName; // 列表名称
- @property (nonatomic,strong) NSMutableArray * list; // 歌曲集合
- - (void) deleteSong:(Song *)song; // 删除歌曲
- - (void) addSong:(Song *) song; // 添加歌曲
- @end
复制代码
Playlist.m
- #import "PlayList.h"
- @implementation PlayList
- - (void)deleteSong:(Song *)song // 删除歌曲
- {
- if(_list.count==0||_list==nil) // 判断列表数目是否为0,或列表是否存在
- {
- return;
- }
- else
- {
- [_list removeObject:song]; // 删除歌曲
- }
- }
- - (void)addSong:(Song *)song // 添加歌曲
- {
- [_list addObject:song]; // 添加歌曲
-
- }
- @end
复制代码 |
|