在方法中添加多个Object

时间:2016-04-12 19:27:14

标签: objective-c

有没有办法通过自定义方法将多个对象添加到NSMutableArray中?这是我的代码。

@property NSMutableArray *MusicCollectionArray;

    -(void) addPlaylist: (Playlist *) thePlaylist;

-(void) addPlaylist: (Playlist *) thePlaylist {
    [MusicCollectionArray addObject:thePlaylist];
}

现在让我说我调用方法但不是添加一个对象,是否有办法将多个添加到一个而不是分别调用每个方法。 (对象数量未知)

例如。 [mycollection addPlaylist:first,second,third];

3 个答案:

答案 0 :(得分:0)

你可以添加另一个这样的数组:

NSMutableArray *sourceArray = [NSMutableArray arrayWithObject:@"FirstObject"];

NSString *secondObject = @"SecondObject";
NSString *thirdObject = @"ThirdObject";

NSArray *objectsToAdd = @[secondObject, thirdObject];

[sourceArray addObjectsFromArray:objectsToAdd];

答案 1 :(得分:0)

有可能,请看一下Apple文档和这个主题:
https://developer.apple.com/library/mac/qa/qa1405/_index.html

#import <Cocoa/Cocoa.h>

@interface NSMutableArray (variadicMethodExample)

- (void) appendObjects:(id) firstObject, ...; // This method takes a nil-terminated list of objects.

@end

@implementation NSMutableArray (variadicMethodExample)

- (void) appendObjects:(id) firstObject, ...
{
id eachObject;
va_list argumentList;
if (firstObject) // The first argument isn't part of the varargs list,
  {                                   // so we'll handle it separately.
  [self addObject: firstObject];
  va_start(argumentList, firstObject); // Start scanning for arguments after firstObject.
  while (eachObject = va_arg(argumentList, id)) // As many times as we can get an argument of type "id"
      [self addObject: eachObject]; // that isn't nil, add it to self's contents.
  va_end(argumentList);
  }
}

@end

我猜你会抓住一个主意。

答案 2 :(得分:0)

最好使用for循环来完成:

- (void) addPlaylistFromPlayLists:(NSArray <Playlist*>*)playlists {
    for (Playlist *playlist in playlists) {
        [musicCollectionArray addObject:playlist];  
    }  
}  

这样,您确保只添加阵列内的播放列表。 for循环只会添加给它的内容,你不必告诉它有多少是for / in。