访问NSString时,iPhone应用程序会随机退出

iYa*_*sin 2 memory iphone crash objective-c nsstring

我的应用程序中有一个NSString的问题.
我已经在我的视图控制器的头文件中定义了它.

    NSString *locationCoordinates;
Run Code Online (Sandbox Code Playgroud)

我在一个 - (void)方法中设置它的值.

- (void)locationUpdate:(CLLocation *)location {
    <...>

    NSArray *locArray = [locString componentsSeparatedByString:@", "];

    NSString *xCoordinate = [locArray objectAtIndex:0];
    NSString *yCoordinate = [locArray objectAtIndex:1]; 

    locationCoordinates = [NSString stringWithFormat:@"%@,%@", xCoordinate, yCoordinate];
}
Run Code Online (Sandbox Code Playgroud)

在这种方法中,我可以将其打印到控制台

NSLog(locationCoordinates);
Run Code Online (Sandbox Code Playgroud)

但如果我想在另一种方法中在控制台中查看它,我的应用程序会立即退出.

- (IBAction)saveAndReturnToRootView {
    NSLog(locationCoordinates);
}
Run Code Online (Sandbox Code Playgroud)

控制台告诉我:

2010-02-24 14:45:05.399 MyApp[73365:207] *** -[NSCFSet length]: unrecognized selector sent to instance 0x4c36490
2010-02-24 14:45:05.400 MyApp[73365:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSCFSet length]: unrecognized selector sent to instance 0x4c36490'
2010-02-24 14:45:05.401 MyApp[73365:207] Stack: (
  32887899,
  2434934025,
  33269819,
  32839286,
  32691906,
  32417461,
  32527181,
  32527085,
  32747749,
  356942,
  630491,
  63461,
  2868313,
  4782069,
  2868313,
  3275682,
  3284419,
  3279631,
  2973235,
  2881564,
  2908341,
  40984273,
  32672640,
  32668744,
  40978317,
  40978514,
  2912259,
  9744,
  9598
)
Run Code Online (Sandbox Code Playgroud)

我怎么解决这个问题?

提前致谢 ;-)

Mon*_*ong 7

你没有保留字符串,所以内存正在被清除.当您尝试访问它时,这会导致崩溃.

要保留它,您可以添加以下行

[locationCoordinates retain];
Run Code Online (Sandbox Code Playgroud)

记得在你不再需要它时释放它 - 可能在你的类的析构函数中,否则你会有内存泄漏.


目标C中的标准做法是为此类成员使用属性.在头文件中使用

@property (nonatomic, retain) NSString *locationCoordinates;
Run Code Online (Sandbox Code Playgroud)

然后在实施chuck中

@synthesize locationCoordinates;
Run Code Online (Sandbox Code Playgroud)

当您访问locationCoordinates时,通过self访问它:

self.locationCoordinates = [NSString stringWithFormat:@"%@,%@", xCoordinate, yCoordinate];
Run Code Online (Sandbox Code Playgroud)

Objective C将创建一个getter和setter属性,以最有效的方式为您处理保留.

顺便提一下,属性中的非原子关键字告诉目标c,您不需要它来围绕属性访问创建任何线程同步.如果您要在课程中进行多线程处理,则应考虑删除非原子课程.这将确保属性访问是线程安全的.

没有必要做任何你可以让编译器为你做的工作!


Phi*_*ert 5

将它存储在类的变量中时,应该保留字符串:

locationCoordinates = [NSString stringWithFormat:@"%@,%@", xCoordinate, yCoordinate];
[locationCoordinates retain];
Run Code Online (Sandbox Code Playgroud)

原因是[NSString stringWithFormat:...]返回一个自动释放的实例.函数结束时,字符串将自动释放.

你也可以复制字符串:

locationCoordinates = 
    [[NSString stringWithFormat:@"%@,%@", xCoordinate, yCoordinate] copy];
Run Code Online (Sandbox Code Playgroud)

当然,不要忘记在dealloc中再次发布它:

- (void) dealloc {
    [locationCoordinates release];

    [super dealloc];
}
Run Code Online (Sandbox Code Playgroud)