Objective-c 复制对象错误

标签 objective-c ios cocoa-touch nsmutablearray

我正在尝试将一个数组复制到另一个数组,但它不起作用。我要复制的原始数组包含五个对象;结果数组为空。

数组被设置为这样的属性:

@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];
}

The first array fills up fine The second array is empty

有谁知道为什么它不起作用?我也尝试过使用常规的 copy 方法并简单地分配它,但它不起作用。

编辑 1:“array”变量实际上得到了正确的初始化,但是它没有被复制。我尝试直接初始化“drinks”数组,但无论我尝试什么,“drinks”数组仍然是空的。

编辑 2:我已经添加了屏幕截图,希望能澄清一些问题。

最佳答案

首先,除了 drinks 数组外,您几乎泄露了所有内容;所有单独的饮料对象和 array 在该代码中都被过度保留了一两次。

其次,只有当 drink1drink5 为 nil 时,drinks 才能为空。也许 initWithImage:name:caffeine: 在图像为 nil 时返回 nil

关于Objective-c 复制对象错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7410889/

相关文章:

objective-c - 如何使用自动布局以编程方式创建 UITableView?

iphone - 如何检测 iPhone 屏幕是否锁定(关闭)

objective-c - 保存和恢复自定义对象数组

iphone 开发 : how to create an animation by using NSTimer

iphone - Ios应用程序图标类

iphone - 在 1 个单元格内绘制 6 个 ImageView

ios - 从 SWRevealViewController 中存在的 tableview 单元格展开 segue

ios - 转换时变量为空

ios - 使用 RxSwift 重新加载 Tableview

iphone - 如何创建自定义中心选项卡按钮?