【问题标题】:Must i release object at here? [closed]我必须在这里释放物体吗? [关闭]
【发布时间】:2012-07-06 00:28:56
【问题描述】:

我对 Objective-C 的内存管理感到困惑。 示例:

.h file
@property(nonatomic,retain) NSString *myString;

.m file
@synthesize myString
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [arrayString count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

  //in this case,i have to check 
  if(self.myString != nil)
        [myString release],self.myString = nil;
  //and assign 
  self.myString = [arrayString objectAtIndex:indexPath.row];
  //or i need only assign 
  self.myString = [arrayString objectAtIndex:indexPath.row];
}

谁能给我解释一下? 非常感谢。

【问题讨论】:

    标签: iphone ios memory


    【解决方案1】:

    您只需分配字符串 .. 并在 deallocviewDidUnload 方法中将其释放/分配给 nil

    【讨论】:

    • 你甚至不需要调用release。由于它是一个带有retain 限定符的属性,您只需将该属性分配为 nil:self.myString = nil;
    • 为什么?我有一个带有保留的属性,我从来没有将它分配给其他属性,但是当我在 dealloc 或 didUnload 调用 [myProperty release] 时没有崩溃。在这里,retainCount 为 0,但我可以释放它。我不知道为什么
    【解决方案2】:
     if(self.myString != nil){
            [myString release],self.myString = nil;
     }
    

    这就够了:

      if(self.myString != nil){
                self.myString = nil;
         }
    

    至于你的问题,你只需要这个:

      self.myString = [arrayString objectAtIndex:indexPath.row];
    

    【讨论】:

    • 还有self.myString = nil;就够了
    【解决方案3】:

    你不需要释放,因为该属性被定义为“保留”,这意味着它释放前一个对象后,它保留了传递的对象。

    如果您直接使用变量而不是访问属性,那么您需要手动管理释放/保留..

    顺便说一句:您可以向 nil 对象发送消息...(所以不检查它是 nil 来释放它)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-02
      • 1970-01-01
      • 2011-09-17
      • 1970-01-01
      相关资源
      最近更新 更多