将对象添加到NSMutableArray时出错

时间:2021-09-21 18:53:40

I am getting errors when trying to add items to a NSMutableArray which is encapsulated within an object.

我在尝试将项目添加到封装在对象中的NSMutableArray时遇到错误。

Code follows:

代码如下:

#import <Foundation/Foundation.h>


@interface TestObject : NSObject {
    NSMutableArray *myArray;
}

@property (nonatomic, retain) NSMutableArray *myArray;


@end

#import "TestObject.h"


@implementation TestObject

@synthesize myArray;

- (id) init {
    if(self= [super init]){
        // Initialise the Mutable Array
        myArray = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void) dealloc {
    [super dealloc];
    [myArray release];
}
@end

Calling:

呼叫:

TestObject *testObject = [[TestObject alloc] init];
    NSString *someString = @"blah blah blah";
    NSLog(@"%@", someString);
    [testObject.myArray addObject:someString];
    NSLog(@"Test Object Array Count: %@", [testObject.myArray count]);
    [testObject release];

Can anyone tell me why this throws an error when calling count?

任何人都可以告诉我为什么这会在调用count时抛出错误?

I have also tried the copy the Mutable Array to a local variable and get the same result when calling count on the local variable.

我还尝试将Mutable Array复制到局部变量,并在调用局部变量上的count时得到相同的结果。

2 个解决方案

#1


2  

Warning warning warning!!!

警告警告!!!

[super dealloc] is the last thing you should do in your -dealloc method, not the first!

[super dealloc]是你应该在-dealloc方法中做的最后一件事,而不是第一件事!

#2


0  

It's a good thing it just showed a warning, when I have done the same it has crashed.

它只是显示一个警告是一件好事,当我做了同样的事情它已经崩溃了。

The reason is that %@ is an object placeholder. But the count method returns NSInteger which is a primitive datatype and the placeholder for it is %d, as you have correctly noted in the comment.

原因是%@是一个对象占位符。但是count方法返回NSInteger,它是一个原始数据类型,它的占位符是%d,正如您在注释中正确注明的那样。

#1


2  

Warning warning warning!!!

警告警告!!!

[super dealloc] is the last thing you should do in your -dealloc method, not the first!

[super dealloc]是你应该在-dealloc方法中做的最后一件事,而不是第一件事!

#2


0  

It's a good thing it just showed a warning, when I have done the same it has crashed.

它只是显示一个警告是一件好事,当我做了同样的事情它已经崩溃了。

The reason is that %@ is an object placeholder. But the count method returns NSInteger which is a primitive datatype and the placeholder for it is %d, as you have correctly noted in the comment.

原因是%@是一个对象占位符。但是count方法返回NSInteger,它是一个原始数据类型,它的占位符是%d,正如您在注释中正确注明的那样。