0

我正在读一本书来学习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

因此,如果我创建一首歌曲,例如歌曲 1,是否有办法将其添加到播放列表中,自动将其添加到 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];

}
4

2 回答 2

0

如果您在Playlist对象上调用方法来添加歌曲,而不是访问其collecsongs属性,您可能会发现这更容易。在该方法中,它可以将歌曲添加到数组中,然后将其添加到库中。(然后你可以让collecsongs属性返回一个 NSArray,而不是一个NSMutableArray,这对我来说似乎更干净。

于 2012-08-09T20:07:16.837 回答
0
-(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-09T20:13:19.613 回答