Objective-c copying objects error
I'm trying to copy an array to another but it's not working. The original array I want to copy contains five objects; the resulting array is empty.
The array is set up as a property like this:
@property (nonatomic, retain) NSMutableArray *drinks;
My viewDidLoad
method looks like this:
- (void)viewDidLoad
{
[super viewDidLoad];
checkCounter = 0;
Drink *drink1 = [[[Drink alloc] initWithImage:nil name:@"Test1" caffeine:11] autor开发者_运维知识库elease];
Drink *drink2 = [[[Drink alloc] initWithImage:nil name:@"Test2" caffeine:22] autorelease];
Drink *drink3 = [[[Drink alloc] initWithImage:nil name:@"Test3" caffeine:33] autorelease];
Drink *drink4 = [[[Drink alloc] initWithImage:nil name:@"Test4" caffeine:44] autorelease];
Drink *drink5 = [[[Drink alloc] initWithImage:nil name:@"Test5" caffeine:55] autorelease];
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects: drink1, drink2, drink3, drink4, drink5, nil];
drinks = [array mutableCopy];
}
Does anyone have any idea why it doesn't work? I've tried using the regular copy
method as well and simply assigning it but it doesn't work.
EDIT 1: The "array" variable actually gets initialised properly, however it does not get copied over. I have tried to directly initialise the "drinks" array but no matter what I try the "drinks" array remains empty.
EDIT 2: I have added screenshots to hopefully clear up some things.
First, you are leaking pretty much everything but the drinks
array; all of the individual drink objects and the array
are over-retained once or twice in that code.
Secondly, drinks
could only be empty if drink1
through drink5
are nil. maybe initWithImage:name:caffeine:
is returning nil
when the image is nil
?
Drink object doesn't conform to the NSMutableCopying Protocol? You should use this easier:
drinks = [NSMutableArray arrayWithArray:array];
require declare array as NSArray, or simpler:
drinks = [array copy];
if was me, your code is:
- (void)viewDidLoad
{
[super viewDidLoad];
checkCounter = 0;
Drink *drink1 = [[[Drink alloc] initWithImage:nil name:@"Test1" caffeine:11] autorelease];
Drink *drink2 = [[[Drink alloc] initWithImage:nil name:@"Test2" caffeine:22] autorelease];
Drink *drink3 = [[[Drink alloc] initWithImage:nil name:@"Test3" caffeine:33] autorelease];
Drink *drink4 = [[[Drink alloc] initWithImage:nil name:@"Test4" caffeine:44] autorelease];
Drink *drink5 = [[[Drink alloc] initWithImage:nil name:@"Test5" caffeine:55] autorelease];
drinks = [[NSMutableArray alloc] initWithObjects: drink1, drink2, drink3, drink4, drink5, nil];
}
精彩评论