开发者

Error When adding Object to NSMutableArray

开发者 https://www.devze.com 2023-01-08 18:48 出处:网络
I am getting errors when trying to add items to a NSMutableArray which is encapsulated within an object.

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

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];
   开发者_Go百科 }
    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?

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.


Warning warning warning!!!

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消