2013-03-05 79 views
0

我的問題是,我有一個要求,以創建3個班的練習:如何讓數組存儲在Objective C中的數組內?

歌(創建和設置歌曲) 播放列表(創建並添加歌曲到它) MusicCollection(有播放列表的集合)現在這個類是棘手的,我需要在播放列表集合中有一個主播library播放列表,它將包含集合中的每首歌...

所以,從我看到有些人在MusicCollection屬性中定義了Playlist類型稱爲庫,並在初始化時執行:

-(id) initWithName: (NSString *) theName 
{ 
    self = [super init]; 

    if (self) { 
     musicCollection = [[NSMutableArray alloc] init]; 
     library = [[Playlist alloc] initWithName: @"library"]; 
     [musicCollection addObject: library]; 
    } 
    return self; 
} 

從我從此明白,每次用戶初始化的集合,所以播放列表對象將被添加到集合陣列...

而問題是,在addPlaylist方法的集合,他們沒有將此播放列表歌曲添加到庫中...像這樣:

-(void) addPlaylist: (Playlist *) thePlaylist 
{ 
    if ([musicCollection containsObject: thePlaylist] == NO) 
     [musicCollection addObject: thePlaylist]; 
} 

有什麼想法?我真的堅持了這一點:/

我雖然有可能通過收集陣列內的陣列圖書館和迭代來看看,如果歌曲是在圖書館,如果不將它們添加..

現在,在Playlist.m的addsong方法是:

-(void) addSong:(Song *)theSong 
{ 
    [playList addObject:theSong]; 
} 

,但我看到,在MusicCollection.m他們補充添加,添加歌曲到庫中的歌曲的方法:

-(void) addSong: (Song *) theSong toPlaylist: (PlayList *) thePlaylist 
{ 
    if([thePlaylist.playList containsObject:theSong]==NO) 
     [thePlaylist addSong:theSong]; 

    if([library.playList containsObject:theSong]==NO) 
     [library addSong:theSong]; 

} 

但是,如果我創建播放列表並將其添加到MusicCllection中,該怎麼辦?不通過MusicCollection方法添加的歌曲添加歌曲..

+0

您是否有一些代碼將歌曲添加到播放列表中? – 2013-03-05 23:32:36

+0

是的,請查看我添加到問題中的代碼。謝謝@ SteveO'Connor – MNY 2013-03-05 23:40:53

回答

0

爲對象比較工作

-(void) addPlaylist: (Playlist *) thePlaylist 
{ 
    if ([musicCollection containsObject: thePlaylist] == NO) 
     [musicCollection addObject: thePlaylist]; 
} 

必須重寫isEqual:方法PlayList

- (BOOL)isEqual:(id)other { 

    if (other == self) 
     return YES; 

    if (!other || ![other isKindOfClass:[self class]]) 
     return NO; 

    return [self isEqualToPlayList:other]; 

} 

//Assuming playListId is an unique identifier in `PlayList` 
- (BOOL)isEqualToPlayList:(PlayList*)playList{ 

    if (self == playList) 
     return YES; 

    if (self.playListId != playList.playListId) 
     return NO; 
    //If you you a combinational uniqueness, check for them as well 

    return YES; 

} 

欲瞭解更多信息請遵循對象比較以下link