Objective-c复制对象错误

时间:2011-09-14 03:19:49

标签: 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 :“数组”变量实际上已正确初始化,但不会被复制。我试图直接初始化“饮料”数组,但无论我尝试什么,“饮料”阵列仍然是空的。

编辑2 :我添加了屏幕截图,希望能够清理一些内容。

2 个答案:

答案 0 :(得分:3)

首先,除了drinks数组之外,你几乎都在泄漏;所有单个饮品对象和array在该代码中被过度保留一次或两次。

其次,如果drinksdrink1为零,则drink5只能为空。当图片为initWithImage:name:caffeine:时,nil可能会返回nil

答案 1 :(得分:0)

饮品对象不符合NSMutableCopying协议? 你应该更容易使用它:

drinks = [NSMutableArray arrayWithArray:array];

要求将数组声明为NSArray,或更简单:

drinks = [array copy];

如果是我,你的代码是:

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