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.

4 Answers 4

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]);
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

The count method returns an NSUInteger.

Try this log format instead:

NSLog(@"imageArr size::%u",[imageArr count]);

1 Comment

It's a good idea to put a cast in because NSUInteger is not guaranteed to be an unsigned int
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

1 Comment

NSUInteger is unsigned long on the iPhone so %i is wrong.

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.