获取 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];
我有 EXC_BAD_ACESS 错误
I have a weird problem.
pictureLink is a global variable declared in .h
NSString *pictureLink;
}
@property(retain,nonatomic) NSString *pictureLink;
i wrote this code
NSString * myPictureUrl=[NSString stringWithFormat:@"http://mywebsite.com/uploads/%@.jpg",hash];
pictureLink=myPictureUrl;
I have a strange result, it must be a pointer
Or
pictureLink=[NSString stringWithFormat:@"http://mywebsite.com/uploads/%@.jpg",hash];
i have EXC_BAD_ACESS error
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是内存管理错误,您没有在代码中保留
myPictureUrl
。[NSString stringWithFormat:@"http://mywebsite.com/uploads/%@.jpg",hash];
返回一个自动释放的值,因此您有两个选择:pictureLink=myPictureUrl;
应该类似于[self setPictureLink:myPictureUrl];
。[myPictureUrl keep];
,并且不要忘记稍后release
它。考虑为您的项目使用 ARC(自动保留计数)。使用 ARC,编译器会处理保留计数,因此您不必这样做,实际上不允许这样做。有一个重构可以转换当前项目。
It's memory management fault, you're not retaining
myPictureUrl
in your code.[NSString stringWithFormat:@"http://mywebsite.com/uploads/%@.jpg",hash];
returns an autoreleased value, so you have two options:pictureLink=myPictureUrl;
should look like[self setPictureLink:myPictureUrl];
.[myPictureUrl retain];
, and don't forget torelease
it later.Consider using ARC (Automatic Retain Counting) for you project. With ARC the compiler takes care of retain counts so you don't have to, in fact aren't allowed to. There is a refactoring that will convert a current project.
您通过直接调用变量来绕过您的
@property
,因此您的@property
设置不会提供任何magic
,例如保留和释放。您需要执行
self.pictureLink
才能使用@property
。为了避免直接访问我的变量的诱惑,我执行了以下操作
,
这样,如果我绕过@property,我真的非常想这样做。
但你需要一个非常非常充分的理由才能这样做,但即使如此,这可能还不是一个足够好的理由。
You are bypassing your
@property
by calling directly the variable, so nomagic
provided by your@property
settings is done, like retain and release.you need to do
self.pictureLink
to use the@property
.To avoid the temptation of accessing directly my variable I do the following
and
That way if I go around the
@property
I really, really wanted to do it.But you need a very, very, very good reason to do so, and event then, it may not be a good enough reason.