获取NSString变量的值



我有一个奇怪的问题。pictureLink是在.h

中声明的全局变量。
 NSString *pictureLink;
}
@property(retain,nonatomic) NSString *pictureLink;

我写了这个代码

NSString * myPictureUrl=[NSString stringWithFormat:@"http://mywebsite.com/uploads/%@.jpg",hash];
pictureLink=myPictureUrl;

我有一个奇怪的结果,它一定是一个指针或者

pictureLink=[NSString stringWithFormat:@"http://mywebsite.com/uploads/%@.jpg",hash];

i have exc_bad_access error

这是内存管理错误,您没有在代码中保留myPictureUrl

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

  1. pictureLink=myPictureUrl;应该像[self setPictureLink:myPictureUrl];
  2. 做一个[myPictureUrl retain];,以后别忘了release

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

您通过直接调用变量绕过了@property,因此@property设置提供的magic没有完成,如保留和释放。
您需要执行self.pictureLink才能使用@property
为了避免直接访问我的变量,我做了以下操作

NSString *theProperty
}
@property (nonatomic, retain) NSString *property;

@synthesise property = theProperty;

这样,如果我绕过@property,我真的,真的很想这样做。
但是你需要一个非常、非常、非常好的理由来这么做,而在这种情况下,它可能不是一个足够好的理由。

最新更新