我正在尝试将一个Song *对象添加到一个Mutable数组中,我很难过,因为尽管添加了对象,但数组的计数并没有增加。
Song.h
#import <Foundation/Foundation.h>
@interface Song : NSObject
@property(copy, nonatomic) NSString *title, *album, *artist;
@property(copy, nonatomic) NSNumber *playTime;
@end
Song.m
#import "Song.h"
@implementation Song
@end
Playlist.h
#import <Foundation/Foundation.h>
@class Song;
@interface Playlist : NSObject
@property(copy, nonatomic) NSMutableArray *playListArray;
-(void) addSong: (Song *) tempSongToBeAdded;
-(void) removeSong: (Song *) tempSongToBeremoved;
-(void) listOfSongs;
-(NSUInteger) entries;
@end
Playlist.m
#import "Playlist.h"
#import "Song.h"
@implementation Playlist
-(void) addSong: (Song *) tempSongToBeAdded{
NSLog(@"%s song is being added.", [tempSongToBeAdded.title UTF8String]);
[self.playListArray addObject:tempSongToBeAdded];
}
-(void) removeSong: (Song *) tempSongToBeremoved{
[self.playListArray removeObject:tempSongToBeremoved];
}
-(NSUInteger) entries{
return [self.playListArray count];
}
-(void) listOfSongs{
NSLog(@"Hi");
for (Song *tempSong in self.playListArray) {
NSLog(@"title: %s", [tempSong.title UTF8String]);
}
}
@end
的main.m
#import <Foundation/Foundation.h>
#import "Song.h"
#import "Playlist.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
Song *song1 = [[Song alloc] init];
song1.title = @"Manasa";
song1.album = @"Ye Maya Chesava";
song1.artist = @"A. R. Rahman";
song1.playTime = [NSNumber numberWithDouble:4.56];
Playlist *playlist1 = [[Playlist alloc] init];
[playlist1 addSong:song1];
NSLog(@"The total number of songs are %lu",[playlist1 entries]);
[playlist1 listOfSongs];
}
return 0;
}
我将播放列表中的条目设为0,并将歌曲列表设为空。我没有得到任何编译错误,我不知道为什么没有将对象添加到数组中。
答案 0 :(得分:1)
您的变量playListArray
从未初始化,始终为nil
。您需要使用以下命令对其进行初始化:
playListArray = [[NSMutableArray] alloc] init];
您可以在初始化此对象的init
类中添加Playlist
方法。
- (id)init
{
self = [super init];
if (self)
{
playListArray = [[NSMutableArray] alloc] init];
}
return self;
}
编辑:
问题似乎是你如何声明属性
@property(copy, nonatomic) NSMutableArray *playListArray;
它被声明为copy
,这意味着即使您执行playListArray = [[NSMutableArray] alloc] init]
,您的变量playListArray
也会获得初始化数组的副本,但copy
协议是继承自NSArray
,而不是NSMutableArray
,因此您获得了一个不可变数组。您可以在NSMutableArray
文档中查看此内容。您需要为copy
更改retain
(您没有使用ARC,对吧?)。
事实上,我发现你的大部分属性都在使用copy
,如果没有特别的原因,我会将其更改为retain
。