aneuryzm
aneuryzm

Reputation: 64834

iOS: issues with a always null NSString

I have a doubt about initializing string with synthesize keyword.

In my Event.h class I have

@interface Event : NSObject {

    NSString *title;
}

@property (nonatomic, retain) NSString *title;

and in Event.h I have

@synthesize title;

However when I want to set the title from my main class and I display the content in the console, I get null:

 [self.currentEvent.title stringByAppendingString:@"hello"];  
 NSLog(@"%@", self.currentEvent.title); //this is null

Is because I don't properly initialize the title variable in Event? Isn't synthesize initializing it for me?

Upvotes: 1

Views: 1398

Answers (3)

adimitri
adimitri

Reputation: 1296

You are not storing the result of your call into a variable. I also suggest using this method since it's a little bit cleaner because you do not need to have an if statement.

 [self setTitle:[NSString stringWithFormat:@"hello %@", [self title]]];

Upvotes: 0

alex-i
alex-i

Reputation: 5454

[self.currentEvent.title stringByAppendingString:@"hello"];

You call stringByAppendingString: on a null object (since it was never initialized), so it doesn't do anything. Plus, even if it were to return something, you're not storing the return value anywhere.

if(self.currentEvent.title==nil){
    self.currentEvent.title = @"hello";
}
else{
    self.currentEvent.title = [self.currentEvent.title stringByAppendingString:@"hello"];
}

Upvotes: 3

Bemmu
Bemmu

Reputation: 18217

@synthesize creates the setter and getter methods for you, but does not initialize

Fastest way to get up to speed with this stuff is to watch "Developing Apps for iOS" by Paul Hegarty / Stanford University, available free on iTunes.

Upvotes: 0

Related Questions