开发者

iOS: issues with a always null NSString

I have a doubt about initializing string with synthesize keyword.

In my Event.h clas开发者_JS百科s 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?


[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"];
}


@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.


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]]];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜