获取

2013-07-25 35 views
3

我已经在Xcode中创建一个自定义类的自定义类的实例的数量:PaperPack和定义2个即时变量:titleauthor -获取

然后我的Alloc如下类的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"; 

那么我如何计算并返回使用该类创建的实例的数量?

+0

你为什么要? – Wain

+0

@我需要将该号码传递给另一个班级。 – fahrulazmi

回答

0

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

例:

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]); 
+1

在他的情况下(如果他只需要实例数量)保留一个int实例可能会更好,例如,而不是NSMutableArray。像@Wain解决方案。 –

+0

谢谢@ nishant-tyagi它的工作原理! – fahrulazmi

+0

嗯。欢迎花花公子:-) –

5

你可以创建你用它来计算要求的实例数出厂单(那么你必须创建所有实例使用工厂)。或者,您可以将static变量添加到PaperPack类中并每次递增(在init方法中,则必须每次调用init)。

+2

+1,如果你只需要一个号码...数......你不应该有一组instanses – Injectios

+0

单身...最好的做法在最好的 – madLokesh

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; 

很抱歉,如果事情是不正确,代码是从内存中写入的

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);