获取 NSString 变量的值

发布于 2024-12-21 07:44:32 字数 482 浏览 2 评论 0原文

我有一个奇怪的问题。 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

只有一腔孤勇 2024-12-28 07:44:32

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

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

  1. pictureLink=myPictureUrl; 应该类似于 [self setPictureLink:myPictureUrl];
  2. 执行[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:

  1. pictureLink=myPictureUrl; should look like [self setPictureLink:myPictureUrl];.
  2. do a [myPictureUrl retain];, and don't forget to release 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.

自由如风 2024-12-28 07:44:32

您通过直接调用变量来绕过您的 @property,因此您的 @property 设置不会提供任何 magic,例如保留和释放。
您需要执行 self.pictureLink 才能使用 @property
为了避免直接访问我的变量的诱惑,我执行了以下操作

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

@synthesise property = theProperty;

这样,如果我绕过@property,我真的非常想这样做。
但你需要一个非常非常充分的理由才能这样做,但即使如此,这可能还不是一个足够好的理由。

You are bypassing your @property by calling directly the variable, so no magic 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

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

and

@synthesise property = theProperty;

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文