更改NSString的值,我做得对吗?

时间:2010-09-16 00:42:35

标签: iphone objective-c

我创建了一个类,如下所示

@interface sampleClass: UIViewController
{
    NSString *currentLocation;
}
@property (nonatomic, copy) NSString *currentLocation;

因此,只要当前GPS发生变化,就会按如下方式调用函数:

-(void)newLocationUpdate:(NSString *)text {
  NSString *temp = [[NSString alloc] initWithString:text];
  currentGPS = temp;
  [temp release];
}

我想知道我做得对吗?感谢。

4 个答案:

答案 0 :(得分:2)

忽略currentLocation / currentGPS混淆 - 不,这仍然不太正确。

您没有显示currentLocation的设定者。我假设它是@synthesize d属性。如果您只是写currentLocation = something,那么您不会调用属性设置器;你只是设置实例变量。这意味着在下一行中释放对象后,您的实例变量可能指向一个已释放的对象。

写它的正确方法(再次,假设你有一个合成访问器)将是:

-(void)newLocationUpdate:(NSString *)text {
  self.currentLocation = text;
}

这会调用属性访问器,它会为您复制对象。

如果出于某种原因你需要直接访问实例变量(比如这个 currentLocation的setter方法),你会写:< / p>

-(void)newLocationUpdate:(NSString *)text {
  [currentLocation release];
  currentLocation = [temp copy];
}

答案 1 :(得分:1)

如果您已正确实施currentLocation / currentGPS setter(使用@synthesize或手动实施),那么您的工作量太大了。如果您有一个使用copy标志声明的属性,那么setter方法本身将执行您手动执行的复制。您只需要这一行:

[self setCurrentGPS:text];

或者,如果您更喜欢属性语法:

self.currentGPS = text;

这将自动调用copy方法,这基本上是一种更有效的方法,可以使用[[NSString alloc] initWithString:text]执行您正在做的事情。

答案 2 :(得分:0)

下面:

@interface sampleClass: UIViewController
{
NSString *currentLocation;
}
 -(void)newLocationUpdate:(NSString *)text;

的.m

-(void)newLocationUpdate:(NSString *)text {
  currentLocation = text; 
}

这就是我这样做的方式。这是对的吗?可能不是。它会起作用吗?是。

答案 3 :(得分:-1)

不,你做错了。

您的班级sampleClass有一个名为currentLocation的ivar和一个名为currentLocation的属性。在newLocationUpdate方法中,您将名为currentGPS的变量设置为传递给该方法的字符串值。如上所述,currentGPS与变量currentLocation或属性currentLocation无关。

此外,您在init方法中使用releasenewLocationUpdate似乎可能会对Obj-C中的内存管理工作方式产生根本性的误解。你一定要阅读Apple的内存管理指南。

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html

这是重要的事情!祝你好运。

相关问题