gpt4 book ai didi

ios - 添加对象 : doesn't add objects to NSMutableArray

转载 作者:行者123 更新时间:2023-11-28 19:28:53 24 4
gpt4 key购买 nike

我正在学习 Objective-C,但在向 NSMutableArray 添加对象时遇到了一些问题。我有一个名为 Song 的类和一个名为 Playlist 的类。我需要将 Song 添加到 Playlist。这是 Playlist.h 文件(数组名为 mySongs:

#import <Foundation/Foundation.h>

@interface Playlist : NSObject

@property(nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSMutableArray *mySongs;

-(instancetype)initPlaylistWithName: (NSString *)playlistName;
-(instancetype)init;

-(void)addSong: (Song *)theSong;
-(void)removeSong: (Song *)theSong;
-(void)printSongsInPlaylist;

@end

Playlist.m 文件中,我有一个方法,它检查播放列表是否不包含歌曲,如果是,则将其添加到数组中。它看起来像这样:

-(void)addSong:(Song *)theSong {
for(Song * song in mySongs){
range = [song.title rangeOfString:theSong.title];
if(range.location != NSNotFound)
return;

}

[mySongs addObjects:theSong];
}

我还有一个方法,可以打印特定播放列表中的所有歌曲。这是它的样子:

 -(void)printSongsInPlaylist {
if ([mySongs count] != 0) {
for (Song *song in mySongs) {
NSLog(@"Title: %@, Artist: %@, Album: %@, PlayingTime: %@", song.title, song.artist, song.album, song.playingTime);
}
} else {
NSLog(@"No songs");
}

问题是,此方法总是打印“No songs”,这意味着数组的 count 为 0。即使在 main.m 文件中也会发生这种情况我首先调用了将歌曲添加到播放列表的方法。

我知道有一些简单的错误,但我不知道是什么。我也在这里检查了类似问题的其他答案,但它们对我没有帮助。

如果您能帮助我理解为什么我不能向数组添加对象,我将不胜感激。

最佳答案

这就是您可以延迟初始化可变数组的方法。它的作用是:在您第一次需要时分配初始化您的数组。对于具有预定义值的静态数组来说,这是一种非常常见的做法,不需要在某些事件之前加载到内存中。

- (NSMutableArray*)mySongs
{
if (!_mySongs) {
_mySongs = [[NSMutableArray alloc] init];
}
return _mySongs;
}

更重要的是:您在 addSong 方法中进行的检查很好,但我建议重写 Song 类的 isEqual 方法。

关于ios - 添加对象 : doesn't add objects to NSMutableArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48405001/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com