获取自定义类的实例数

时间:2013-07-25 06:46:10

标签: ios objective-c instance counter multiple-instances

我在xcode中创建了一个自定义类:PaperPack并定义了两个即时变量:titleauthor -

然后我分配2个类的实例,如下所示:

PaperPack *pack1 = [[PaperPack alloc] init];
pack1.title = @"Title 1";
pack1.author = @"Author";

PaperPack *pack2 = [[PaperPack alloc] init];
pack1.title = @"Title 2";
pack1.author = @"Author";

然后我如何计算并返回我用该类创建的实例数?

4 个答案:

答案 0 :(得分:5)

您可以创建一个工厂单例,用于计算所请求的实例数(然后您必须使用工厂创建所有实例)。或者您可以在static类中添加PaperPack变量并每次递增(在init方法中,然后每次都必须调用init。)

答案 1 :(得分:0)

不,你不能直接得到。无论何时在实例中创建,都要添加任何Array,然后使用该数组属性访问它。

例如:

NSMutableArray *allInstancesArray = [NSMutableArray new];
PaperPack *pack1 = [[PaperPack alloc] init];
pack1.title = @"Title 1";
pack1.author = @"Author";
    [allInstancesArray addObject:pack1];

PaperPack *pack2 = [[PaperPack alloc] init];
pack1.title = @"Title 2";
pack1.author = @"Author";
    [allInstancesArray addObject:pack2];

然后算作:

NSLog(@"TOTAL INSTANCES : %d",[allInstancesArray count]);

答案 2 :(得分:0)

static PaperPack *_paperPack;

@interface PaperPack ()

@property (nonatomic, assign) NSInteger createdCount;

- (PaperPack *)sharedPaperPack;

@end

@implementation PaperPack

+ (PaperPack *)sharedPaperPack
{
    @synchronized(self)
    {       
        if(!_sharedPaperPack)
        {

             _sharedPaperPack = [[[self class] alloc] init];

        }
    }
    return _sharedPaperPack;
}

+ (PaperPack*)paperPack {
    self = [super init];
    if (self) {
        [PaperPack sharedPaperPack].createdCount ++;
    }
    return self;
}

使用它:

只需调用类方法即可增加“createdCount”值

PaperPack *firstPaperPack = [PaperPack paperPack];
PaperPack *secondPaperPack = [PaperPack paperPack];

并计算:

NSInteger count = [PaperPack sharedPaperPack].createdCount;

如果出现问题,请注意,代码是从内存中写入的

答案 3 :(得分:0)

您还可以执行以下操作 方法1

// PaperPack.h
@interface PaperPack : NSObject
+ (int)count;
@end

// PaperPack.m
static int theCount = 0;

@implementation PaperPack
-(id)init
{
  if([super init])
   {
     count = count + 1 ; 
   }
  return self ;
}
+ (int) count
 { 
   return theCount; 
  }
@end

当您想要创建的对象数量时

[PaperPack count];

方法2

1)为您的班级PaperPack.h

添加一个属性
@property (nonatomic,assign) NSInteger count ;

2)在PaperPack.m

中合成它
@synthesize count ;

3)修改init方法

-(id)init
{
  if([super init])
   {
     self = [super init] ;
     self.count = self.count + 1 ; 
   }
   return self ;
}

4)当你想要创建的对象数量时

  NSLog(@"%d",pack1.count);
   NSLOg(@"%d",pack2.count);