0

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

3
  • Fixed my own issue. NSLog(@"Test Object Array Count: %d", [testObject.myArray count]); Commented Jul 26, 2010 at 22:04
  • 1
    Not trying to answer your question but I strongly suggest moving that [myArray release] call in your -dealloc to before you do the super call. Commented Jul 26, 2010 at 22:05
  • Thanks Benjamin, little oversight on my part. I typed that code out by hand in Safari as I do not have xcode on this machine. Commented Jul 26, 2010 at 22:17

2 Answers 2

2

Warning warning warning!!!

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.