Search code examples
objective-ccocoacocoa-touchmemory-managementnslog

%d doesn't show integer properly


As I try to write

NSLog(@"%d", myObject.myId);

where myId is int, console gives some hight number like 70614496. And when I use @"%@", I get exception -[CFNumber respondsToSelector:]: message sent to deallocated instance 0x466c910. Why is it so?

Here's definition of myObject:

@interface myObject : NSObject {
int myId;
NSString *title;
}

@property(nonatomic) int myId;
@property(nonatomic, retain) NSString *title;

@end

@implementation myObject

@synthesize myId, title;

- (void)dealloc {
[title release];

[super dealloc];
}

@end

Solution

  • It looks like your instance of myObject was autoreleased at some time and is no longer actually valid. That is why you see the strange NSNumber issue when you try to dereference it as an object. When you just ask for an integer, you won't get any kind of error, it will just display the pointer's address coerced into an integer.

    To see when your myObject gets dealloced, try adding something like this to the dealloc method in your class:

    - (void)dealloc
    {
        NSLog(@"dealloc called on %@", self);
        [title release];
        [super dealloc];
    }
    

    I bet you will find this logging a dealloc before you see the log for your myObject.myID.