我正在读一本书来学习Objective-C。我被其中一个练习卡住了。你必须制作一个有班级歌曲、播放列表和音乐集合的程序。如果你创建了一首歌曲,它必须自动添加到音乐收藏中,谁有一个收集歌曲的NSMutableArray。如果您从音乐集合中删除一个对象,则必须从包含该歌曲的每个播放列表中删除该歌曲。
歌曲界面
#import <Foundation/Foundation.h>
@interface Song : NSObject{
NSString *title;
NSString *artist;
NSString *album;
}
@property (copy) NSString *title;
@property (copy) NSString *artist;
@property (copy) NSString *album;
-(Song *) initWithNames:(NSString*) title1 and: (NSString*) artist1 and: (NSString*) album1;
@end播放列表界面
#import <Foundation/Foundation.h>
@interface Playlist : NSObject{
NSString * title;
NSMutableArray *collecsongs;
}
@property (strong) NSString *title;
@property (strong) NSMutableArray *collecsongs;
-(Playlist *) initWithName: (NSString *) name;
@end音乐采集接口
#import <Foundation/Foundation.h>
#import "Playlist.h"
@interface MusicCollection : NSObject{
NSMutableArray *collecplist;
Playlist *library;
}
@property (strong) NSMutableArray *collecplist;
@property (strong) Playlist *library;
@end因此,如果我创建一首歌曲,例如song1,有没有一种方法,如果我将它添加到播放列表中,自动将它添加到mastercoleection变量“库”中,而不是这样做
Song *song1 = [[Song alloc] initWithNames:@"Somebody That I Used To Know" and: @"Gotye" and: @"First Album"];
Playlist *Misrolas = [[Playlist alloc] initWithName: @"Misrolas"];
MusicCollection *music = [[MusicCollection alloc] init];
[Misrolas.collecsongs addObject: song1];//adds song1 to the playlist named "Misrolas"
[music.library.collecsongs addObject: song1];//adds song1 to the music collection所以我不知道该怎么做,我想重写可能是addObject:,但这似乎不是正确和容易的,谢谢你的帮助=)
我是这样做的,有没有更有效或者更好的添加方式?
-(void) addsong: (Song *)song addtocollection: (Playlist *) library{
NSAssert([song isKindOfClass: [Song class]], @"Not the same class");
[self.collecsongs addObject:song];
[library.collecsongs addObject: song];
}发布于 2012-08-10 04:13:20
-(Song *) initWithNames:(NSString*) title1 and: (NSString*) artist1 and: (NSString*) album1;这是一个非常糟糕的名字。您的选择器缩写为initWithNames:and:and:(这并不是真正的描述性的)。考虑使用
- (id)initWithTitle:(NSString *)title artist:(NSString *)artist album:(NSString *)album;注意这里我是如何使用(id)的返回类型的。它允许更容易的子类化,因为任何子类都可以使用init...“构造函数”,没有任何类型不匹配警告。
说到您的问题,我建议您只公开NSArray *属性访问器(这样您就不能修改数组内容),并在Playlist类上创建一个方法:
- (void)addSong:(Song *)song
{
NSAssert([song isKindOfClass:[Song class]]);
[self.collecplist addObject:song];
}这就是OOP的封装。你没有公开私有接口(数组),你提供了添加歌曲的接口(你不能添加其他类型的对象),最后,你做一个验证,你添加的是真正的歌曲。您还可以在此处将歌曲添加到您的音乐收藏中。
发布于 2012-08-10 04:07:17
如果调用Playlist对象上的方法来添加歌曲,而不是访问其collecsongs属性,您可能会发现这更容易。在该方法中,它可以将歌曲添加到数组中,然后将其添加到库中。(然后,您可以让collecsongs属性返回一个NSArray,而不是NSMutableArray,这在我看来要清晰得多。
https://stackoverflow.com/questions/11891114
复制相似问题