如何为以下(目标 C)重构类似的方法?
- (void)insertNewSong:(Song *)newSong forArtist:(Artist *)artist {
NSMutableArray *newSongList = [[artist songs] mutableCopy];
BOOL hasInserted = NO;
for (int i = 0; i < [[artist songs] count]; i++) {
Song *existingSong = [[artist songs] objectAtIndex:i];
if ([[newSong title] caseInsensitiveCompare:[existingSong title]] == NSOrderedAscending) {
[newSongList insertObject:newSong atIndex:i];
hasInserted = YES;
break;
}
}
if (hasInserted == NO) {
[newSongList addObject:newSong];
}
artist.songs = newSongList;
}
- (void)insertNewArtistToSongList:(Artist *)newArtist {
BOOL hasInserted = NO;
for (int i = 0; i < [_artists count]; i++) {
Artist *existingArtist = [_artists objectAtIndex:i];
if ([[newArtist name] caseInsensitiveCompare:[existingArtist name]] == NSOrderedAscending) {
[_artists insertObject:newArtist atIndex:i];
hasInserted = YES;
break;
}
}
if (hasInserted == NO) {
[_artists addObject:newArtist];
}
}
对于 insertNewSong 方法,使用包含每个 Song 对象的 NSMutableArray [艺术家歌曲]。对于 insertNewArtist 方法,使用了包含每个 Artist 对象的 NSMutableArray 实例变量 _artists。
这两种方法都通过将输入对象的文本属性与数组中的文本属性进行比较,将对象插入到 NSMutableArray 中。
目前上述方法包含一些重复但很容易理解(在我的例子中)。我在想是否有办法将其简化为更通用的方法,并且不会损害可读性?