Tigran Iskandaryan
Tigran Iskandaryan

Reputation: 1451

addObject: doesn't add objects to NSMutableArray

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 Songs 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.

Upvotes: 0

Views: 576

Answers (2)

Shehata Gamal
Shehata Gamal

Reputation: 100549

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

    self = [super init];

    if(self)
    {
        _name = playlistName

        _mySongs = [NSMutableArray new];

    }

   return self;

}

Upvotes: 1

dvp.petrov
dvp.petrov

Reputation: 1120

This is how you can lazy init your mutable array. What this does is: alloc initing your array the first time you need it. It is a pretty common practice for static arrays with predefined values, that do not need to be loaded in the memory prior some event.

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

What is more: The check you are making in addSong method is fine, but I would recommend overriding the isEqual method of Song class.

Upvotes: 2

Related Questions