Trying to NSLog an NSNumber ivar in an instance method

nickthedude picture nickthedude · Jan 12, 2010 · Viewed 34.1k times · Source

I'm working on a console app that is tracks different songs. I'm working on getting the song class up off the ground first and have run into a snag trying to log an nsnumber which has been allocated for the song duration into an nslog statement:

//
//  Song.h
//  MusicCollection.15.9   
//
//  Created by Nicholas Iannone on 1/11/10.
   //  Copyright 2010 __MyCompanyName__. All rights reserved.
   //

   #import <Foundation/Foundation.h>


@interface Song : NSObject {

NSString *songTitle;
NSString *songArtist;
NSString *songAlbum;
NSNumber *SongDuration; 
}
@property (nonatomic, retain) NSString *songTitle, *songArtist, *songAlbum;
@property (nonatomic, retain) NSNumber *SongDuration;

-(id) init;


-(void) printSong;



@end


//
//  Song.m
//  MusicCollection.15.9    
//
//  Created by Nicholas Iannone on 1/11/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "Song.h"


@implementation Song

@synthesize  songTitle, songArtist, songAlbum;
@synthesize SongDuration;

-(id) init
{

if (self = [super init]) {

    [SongDuration numberWithInteger];
}

-(void) printSong
{



NSLog(@"===============Song Info==================");
NSLog (@"|                                       |");
NSLog (@"| %-31s |", [songTitle UTF8String]);
NSLog (@"| %-31s |", [songArtist UTF8String]);
NSLog (@"| %-31s |", [songAlbum UTF8String]);                                       
NSLog (@"| %31@   |"  [self songDuration]);
NSLog (@"|                                       |");
NSLog (@"|                                       |");
NSLog (@"=========================================");

}
@end

Basically I'm not sure how to incorporate the nsnumber into the nslog statement when the print method gets called, plus im not really sure how to deal with these nsobjects ingeneral they seem kind of in-between an object I would create and a c type. Any clarification on how to handle these would be appreciated.

Thanks,

Nick

Answer

Martin Gordon picture Martin Gordon · Jan 12, 2010

To insert an object's description in a format string, use %@.

You can do this with your title/artist/album NSStrings as well so you don't need to call -UTF8String on them first.

For your song duration, you can either log the NSNumber directly or log a float or integer representation by calling -floatValue or -integerValue and logging those with %f and %d.

Examples:

NSLog(@"%@", songTitle);
NSLog(@"%@", songDuration);
NSLog(@"%f", [songDuration floatValue]);
NSLog(@"%d", [songDuration integerValue]);