NSMutableArray Crashing App

In one class, I define an NSMutableArray with getters and setters:

@interface ArrayClass : NSObject {
    NSMutableArray *array;
@property (nonatomic, strong) NSMutableArray *array;


Then within the implementation file, I alloc init the mutable array:

#import "ImageUploader.h"

@implementation ArrayClass
@synthesize array;

- (id)init {
    self = [super init];
    if (self != nil) {
        NSLog(@"ArrayClass inited");
        array = [[NSMutableArray alloc] init];
    return self;


Then I initialize an instance of this class from another class:

ArrayClass *arrayClass = [[ArrayClass alloc] init];
                [arrayClass.array addObject:image];
                NSUInteger count = [arrayClass.array count];
                NSLog(@"%@", count);

But when I try to add an object to the mutable array, the app crashes and Xcode 4.3 shows:

Removing the addObject call makes the app run fine. What am I doing wrong that would cause the app to crash?


This is wrong:

NSUInteger count = [arrayClass.array count];
NSLog(@"%@", count);

You want:

NSLog(@"%u", count);

%@ is used to specify that the argument is an object. However, an NSUInteger is a primitive value, not an object. You use %u for unsigned ints.


NSLog(@"%i", count);

NSUInteger return an INT not an object address

NSLog(@"%@", count); 

is wrong, use:

NSLog(@"%i", count); 

%@ in the format statement expects and must be an object, NSUInteger is in int, not an object.

You are using an %@ format specifier, which is for Cocoa objects only, for an NSUInteger, which is a typedef on an ordinary unsigned int. Use %d, %i or %u instead.

It looks to me like it's crashing when trying to print description, which makes sense because you're using %@ where an integer is expected in your NSLog().

Separately, using a mutable property is almost always a bad idea. If it's really a property, you probably want to use an immutable array, and set the whole array when you want to change it.

Agree that the logging of count is wrong, but I think the other answers miss a move obvious point: the crash happens on the addObject. This implies that image is nil. NSLog that before the add.

Need Your Help

How to call VieModel function on custom binding Knockout Js

javascript jquery knockout.js jquery-validate

How can I call a ViewModel function inside of a custom binding? I have a custom binding to apply jQuery Validate to a form and I need to call a function in the submitHandler, but nothing I've tried...

How do I replace multiple spaces with a single space in C#?

c# regex string

How can I replace multiple spaces in a string with only one space in C#?