例如,NSString*defaultCellIndedentifier=@"HelloWorld";
我什么时候应该解除分配?字符串是objective-c中唯一可以是静态的变量吗?
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
[BNUtilitiesQuick UtilitiesQuick].currentBusiness=[[BNUtilitiesQuick getBizs] objectAtIndex:[indexPath row]];
//Business * theBiz=[[BNUtilitiesQuick getBizs] objectAtIndex:[indexPath row]];
static NSString * defaultCellIndentifier = @"HelloWorld";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier: defaultCellIndentifier];
//UITableViewCell*cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Hello"] autorelease];;
...
return cell;
}
在这种情况下,您无法真正解除分配对象,因为它是一个静态字符串,位于映射到内存的程序的只读部分。执行[@"foo" release]
没有任何效果。您只能将nil
分配给您的变量,但这不会使字符串消失。
一般来说,静态变量的目的是保持不变,这样你就不想释放它。只要它不是一个只会增长并占用大量内存的可变数组,这就不是问题。
编辑以澄清:
通常,您使用一个静态变量来分配一次应该或多或少是静态的东西。静态变量与所有实例共享,因此如果您更改它,则类的所有实例都将看到此更改。特别是对于多个线程,这可能是一个问题,但这样做通常是安全的:
- (void)foo
{
// It's important to initialize this to nil. This initialization
// is only done ONCE on application start ! It will NOT overwrite
// any values you've set later on.
static NSDate *someImportantDate = nil;
if (!someImportantDate) {
// Allocate the static object. We will only get here once.
// You need to make sure that the object here is not autoreleased !
someImportantDate = [[NSDate alloc] init];
// or:
someImportantDate = [[NSDate date] retain];
}
// Do stuff.
}
但是一旦创建,就不应该再次接触静态变量。如果您发现需要更改它,则应该在类中使用实例变量,而不是使用静态变量。
还有一个关于多线程的警告:如果你有多个线程,你应该确保在多个线程访问静态变量之前完成静态变量的初始化。因为如果两个线程都看到未初始化的(nil)变量,他们都会尝试设置新值(竞争条件),理论上这甚至可能导致崩溃。一旦变量被初始化,并且您只读取变量(并且它不是可变对象),就可以安全地从不同的线程访问该值。
对于您的情况,永远不要释放任何用@""
语法创建的字符串。它们是内存中的常量,在应用程序进程结束之前永远不应该解除分配。