2011-12-14 62 views
2

我有一个奇怪的问题。 链接PictureLink是.H得到一个NSString变量的值

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错误

+0

如果可能的话使用ARC,那么编译器将处理幕后的所有保留计数。 – zaph 2011-12-14 14:34:39

回答

6

这是内存管理故障,y你不会在你的代码中保留myPictureUrl

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

  1. pictureLink=myPictureUrl;应该像[self setPictureLink:myPictureUrl];
  2. 做一个[myPictureUrl retain];,不要忘记release它以后。

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

+1

如果有一个属性不在其周围编码,请使用属性设置器/获取器。直接指定到`pictureLink`将会创建一个由`pictureLink`指向的对象的内存泄漏。 – zaph 2011-12-14 14:26:35

+0

@Andrey谢谢你的完美工作。这是我的第一个应用程序,我从来没有释放对象:D它会导致我的问题? – user567 2011-12-14 14:28:43

2

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

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

@synthesise property = theProperty; 

这样,如果我走了@property我真的身边,真的想做到这一点。
但是,你需要一个非常非常好的理由来做到这一点,然后事件可能不是一个很好的理由。