【问题标题】:NSMutableArray with custom objects?NSMutableArray 与自定义对象?
【发布时间】:2010-08-25 19:38:32
【问题描述】:

我有一个自定义类:

 @interface Player : NSObject {
   NSInteger mPlayerNo;
 }

 -(id) initWithNum:(NSInteger) playerNum;

 @implementation Player

 -(id) initWithNum:(NSInteger) playerNum
 {
   if(![super init])
   return nil; 
   ... 
   mPlayerNo=playerNum;
   return self;
 }

 @end

我需要另一个程序类中的 Player 对象数组:

 @interface Spec : NSObject  {
    NSMutableArray * mPlayers;
    ...
  }

所以,我试图在 Spec 类的 init 方法中填充 mPlayers arr,如下所示:

- (id)init {
   if(![super init])
      return nil; 
   NSMutableArray * _array=[[NSMutableArray alloc] init];
   mPlayers=_array;
   [_array release];
   Player * _player=[[[Player alloc] initWithNum:(NSInteger)1]autorelease];
   [mPlayers addObject:_player]; // crashes with EXC_BAD_ACCESS

它不起作用。但是如果我改变了

   NSMutableArray * _array=[[NSMutableArray alloc] init];
   mPlayers=_array;
   [_array release];

   mPlayers=[[NSMutableArray array]retain];

一切正常。 这对我来说很奇怪。请帮助理解 alloc init 的问题。

【问题讨论】:

    标签: objective-c


    【解决方案1】:

    问题是你在使用它之前释放了你的数组。

    NSMutableArray * _array=[[NSMutableArray alloc] init]; //Retain count of 1
    
    mPlayers=_array; //Still 1.
    //Adding a new pointer to the same object doesn't affect the object's retain count.
    
    [_array release]; //Now it's 0. Array is gone!
    

    【讨论】:

      【解决方案2】:
         NSMutableArray * _array=[[NSMutableArray alloc] init];
         mPlayers=_array;
         [_array release];
      

      在这里,您正在创建一个数组,然后立即释放它。 +alloc 意味着保留,您正在通过该版本平衡它。

      分配无关紧要。

      【讨论】:

        【解决方案3】:

        如果您将创建的数组分配给mPlayers,这不会影响保留计数。 如果您随后调用release,则保留计数将达到零并且对象将被释放。

        由于对这种行为的深入了解对于 Objective-C 开发至关重要,您可能需要查看 Apple 提供的 documentation

        【讨论】:

          猜你喜欢
          • 2011-01-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-06-07
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多