I'm learning Objective-C and have some trouble with adding objects to an NSMutableArray
. I have a class called Song
and a class called Playlist
. I need to add Song
s to a Playlist
. Here is the Playlist.h
file (the array is called 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
In Playlist.m
file I have a method, which checks that the playlist doesn't contain the song, and if so, adds it to the array. It looks like this:
-(void)addSong:(Song *)theSong {
for(Song * song in mySongs){
range = [song.title rangeOfString:theSong.title];
if(range.location != NSNotFound)
return;
}
[mySongs addObjects:theSong];
}
I also have a method, which prints all the songs inside a particular playlist. Here how it looks like:
-(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");
}
The problem is, this method always prints "No songs", which means, the count
of the array is 0. This happens even if in main.m
file I call the method for adding a song to the playlist first.
I know there is some simple mistake but I can't figure out what it is. I've also checked other answers to similar questions here, but they didn't help me.
If you could help me understand why I can't add an object to the array, I would appreciate it.