获取NSString变量的值

use*_*567 2 iphone objective-c nsstring

我有一个奇怪的问题.pictureLink是以.h声明的全局变量

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

我写了这段代码

NSString * myPictureUrl=[NSString stringWithFormat:@"http://mywebsite.com/uploads/%@.jpg",hash];
pictureLink=myPictureUrl;
Run Code Online (Sandbox Code Playgroud)

我有一个奇怪的结果,它必须是一个指针或

pictureLink=[NSString stringWithFormat:@"http://mywebsite.com/uploads/%@.jpg",hash];
Run Code Online (Sandbox Code Playgroud)

我有EXC_BAD_ACESS错误

And*_*rev 6

这是内存管理故障,您不会保留myPictureUrl在代码中.

[NSString stringWithFormat:@"http://mywebsite.com/uploads/%@.jpg",hash]; 返回一个自动释放的值,因此您有两个选择:

  1. pictureLink=myPictureUrl;应该是这样的[self setPictureLink:myPictureUrl];.
  2. 做一个[myPictureUrl retain];,不要忘记release以后再做.

考虑为您的项目使用ARC(自动保留计数).使用ARC,编译器会处理保留计数,因此实际上不允许这样做.有一个重构将转换当前项目.