0

this is a noob question but I cannot for the life of me figure out why my MSMutableArray class variable is not being set. Below is my code:

@interface MyClass : NSObject {
   NSMutableArray *imageArr;
}

@implementation MyClass
-(id)init
{
   self = [super init];
   if (self) {
      imageArr = [[NSMutableArray alloc] init]; 
   }
   return self;
}

- (void) checkImageArr {
   NSLog(@"imageArr size::%@",[imageArr count]);
}

When this code runs, the following is set to the log:

imageArr size::(null)

Why is that variable not being set? I looked at the following question and don't see anything different between my code and the accepted answer.

Thanks.

Community
  • 1
  • 1
thiesdiggity
  • 1,897
  • 2
  • 18
  • 27

4 Answers4

1

Change %@ to %lu and you'll see.

Extra Savoir-Faire
  • 6,026
  • 4
  • 29
  • 47
1

The count method returns an NSUInteger.

Try this log format instead:

NSLog(@"imageArr size::%u",[imageArr count]);
Felix Lamouroux
  • 7,414
  • 29
  • 46
1

The %@ specifier expects the argument to be an id (or pointer to an object). -count returns an NSUInteger which is not an object. Since your array is empty, the count is zero and so the argument is being interpreted as a nil object, which comes out as (null) when used with the %@ specifier.

If the argument was not nil, -description would be sent to it to get a string to insert in the log message. So, if you add an object to your array, NSLog will try to interpret 1 as an object pointer and send -description to it. This will cause an EXC_BAD_ACCESS exception (try it!).

You need a format specifier that interprets the argument as a number. NSUinteger has the following definition

#if __LP64__ || TARGET_OS_EMBEDDED || TARGET_OS_IPHONE || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64
typedef unsigned long NSUInteger;
#else
typedef unsigned int NSUInteger;
#endif 

so it's probably an unsigned long. For safety, I always cast it to make sure, so you need this:

NSLog(@"imageArr size::%lu", (unsigned long)[imageArr count]);
JeremyP
  • 84,577
  • 15
  • 123
  • 161
0
NSLog(@"imageArr size::%@",[imageArr count]);

You should use %@ when you want to "write an object" AFAIK, it is like write [object description]. [imageArr count] is a int, right? It is not a pointer to an object.

You should use %i instead of %@. And size will be 0.

Try NSLog(@"imageArr size::%@",imageArr); if you want to write a address

Nikita Ilyasov
  • 500
  • 2
  • 14