我正在尝试将一个数组复制到另一个数组,但它不起作用。我要复制的原始数组包含五个对象;结果数组为空。
数组被设置为这样的属性:
@property (nonatomic, retain) NSMutableArray *drinks;
我的 viewDidLoad
方法如下所示:
- (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];
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects: drink1, drink2, drink3, drink4, drink5, nil];
drinks = [array mutableCopy];
}
有谁知道为什么它不起作用?我也尝试过使用常规的 copy
方法并简单地分配它,但它不起作用。
编辑 1:“array”变量实际上得到了正确的初始化,但是它没有被复制。我尝试直接初始化“drinks”数组,但无论我尝试什么,“drinks”数组仍然是空的。
编辑 2:我已经添加了屏幕截图,希望能澄清一些问题。
最佳答案
首先,除了 drinks
数组外,您几乎泄露了所有内容;所有单独的饮料对象和 array
在该代码中都被过度保留了一两次。
其次,只有当 drink1
到 drink5
为 nil 时,drinks
才能为空。也许 initWithImage:name:caffeine:
在图像为 nil
时返回 nil
?
关于Objective-c 复制对象错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7410889/