Monday, August 15, 2011

Objective C : NSConstantString(instance) does not recognize

In my attempt to understand Objective C, I have been doing a lot of testing and code writing.
Among many error I encountered, I would like to mention this one in particular since I was unable find much information about this in the internet.

ds@mypc ~/bsp/Cocoa/obj
$ TestAppPhotographer.exe
: Uncaught exception NSInvalidArgumentException, reason: NSConstantString(instance) does not recognize setCaption:

The reson I was getting this error message was due to the fact that when I created an init method to set initial values for our instance variables, I missed a like to "return self;".

Before:

-(id) init
{
if( self = [super init])
{
[self setCaption:@"Default Caption"];
[self setPhotographer:@"Default Photographer"];
}
}

After :

- (id) init
{ if ( self = [super init] )
{ [self setCaption:@"Default Caption"];
[self setPhotographer:@"Default Photographer"];
}
return self;
}

Once I added the above piece of code, it ran okay.

Photographer.h


#import

@interface Photographer : NSObject
{
NSString* caption;
NSString* photographer;
}

-(NSString*) caption;
-(NSString*) photographer;


-(void) setCaption: (NSString*)input;
-(void) setPhotographer: (NSString*) input;
@end


Photographer.m


#import
#import "Photographer.h"


@implementation Photographer

-(NSString*) caption
{
return caption;
}

-(NSString*) photographer
{
return photographer;
}

-(void) setCaption: (NSString*) input
{
//not using garbage collection, we need to release the old object, and retain the new one.
[caption autorelease];
caption = [input retain];
}

-(void) setPhotographer: (NSString*) input
{
[photographer autorelease];
photographer = [input retain];
}


- (id) init
{ if ( self = [super init] )
{ [self setCaption:@"Default Caption"];
[self setPhotographer:@"Default Photographer"];
}
return self;
}

@end


Main.m

#import
#import "Photographer.h"


int main (int argc, char *argv[])
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];

Photographer *me = [[Photographer alloc] init];

[me setCaption: @"hello"];
NSLog(@"The caption is %@", [me caption]);

[pool drain];
return 0;
}

GNUmakefile

# Set a path variable to gnustep library directory
export GNUSTEP_MAKEFILES=/c/GNUstep/gnustep/System/Library/Makefiles

# Common Makefile Variables
include $(GNUSTEP_MAKEFILES)/common.make

# Console Project
include $(GNUSTEP_MAKEFILES)/tool.make

# Output Name
TOOL_NAME = TestAppPhotographer

# Source Files
TestAppPhotographer_OBJC_FILES = Main.m Photographer.m

# Class Header (Interface) files
TestAppPhotographer_HEADER_FILES = Photographer.h

# Additional Rules
-include GNUmakefile.preamble

# Objective C Rules
include $(GNUSTEP_MAKEFILES)/tool.make

# Additional Rules
-include GNUmakefile.postamble

No comments:

Post a Comment