简体   繁体   English

iOS:始终存在 null NSString 的问题

[英]iOS: issues with a always null NSString

I have a doubt about initializing string with synthesize keyword.我对使用 synthesize 关键字初始化字符串有疑问。

In my Event.h class I have在我的 Event.h class 我有

@interface Event : NSObject {

    NSString *title;
}

@property (nonatomic, retain) NSString *title;

and in Event.h I have在 Event.h 我有

@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:但是,当我想从我的主 class 设置标题并在控制台中显示内容时,我得到 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?是因为我没有正确初始化 Event 中的 title 变量吗? 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.您在 null object 上调用stringByAppendingString: (因为它从未初始化),所以它什么也不做。 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 @synthesize 为您创建 setter 和 getter 方法,但不会初始化

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.了解这些东西的最快方法是观看 Paul Hegarty / 斯坦福大学的“Developing Apps for iOS”,可在 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.我还建议使用这种方法,因为它更简洁一些,因为您不需要 if 语句。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM