简体   繁体   中英

Can't add object to NSMutableArray from another class

I am trying to add objects to a NSMutableArray from another class and it won't work. It works perfectly for the other attribute.

I looked at similar questions but couldn't find a suitable answer.

The object iPack :

@interface IPack : NSObject

     @property float price;
     @property NSMutableArray *cocktails;

@end

In the class of my collection view :

- (void)viewDidLoad {
    [super viewDidLoad];

    self.iPack = [[IPack alloc] init];
    self.iPack.cocktails = [[NSMutableArray alloc] init];

In the class of my cell :

self.collectionView.iPack.price = self.price //perfectly works

NSArray* cock = [NSArray arrayWithObjects:c1,c2,c3,c4,c5, nil];
[self.collectionView.iPack.cocktails addObjectsFromArray:cock]; //line won't work

You haven't shown the [IPack init] method, but I strongly suspect you are not allocating the cocktails array. Simply defining it as a property does not mean it's automatically allocated:

@implementation IPack

- (instancetype)init
{
    self = [super init];
    if (self) {
        _price = 0.0f;
        _cocktails = [NSMutableArray new];
    }
    return self;
}

@end

EDIT

I've just seen this line in your question:

self.iPack.cocktails = [[NSMutableArray alloc] init];

Which would suggest my answer is wrong (despite it being the better way of doing the same thing). Sorry about that; I cannot see why your code doesn't work. Are you sure you are checking correctly?

try this,

in IPack class add a method

@interface IPack : NSObject

     @property float price;
     @property NSMutableArray *cocktails;
     - (instancetype)initWithPrice:(float)price cocktails:(NSMutableArray *)cocktails;
@end

and in implementation

@implementtion IPack

- (instancetype)initWithPrice:(float)price cocktails:(NSMutableArray *)cocktails {

    self = [super init];
    if (self) {
        self.price = price;
        self.cocktails = cocktails;
    }
}

@end

In the class of my collection view :

remove alloc init in viewDidLoad that is remove the following lines

self.iPack = [[IPack alloc] init];
self.iPack.cocktails = [[NSMutableArray alloc] init];

In the class of my cell :

NSArray* cock = [NSArray arrayWithObjects:c1,c2,c3,c4,c5, nil];
IPack *ipack = [[IPack alloc] initWithPrice:self.price cocktails:[NSMutableArray arrayArray:cock]];
self.collectionView.iPack = ipack;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM