获取自定义类的实例数
我在xcode中创build了一个自定义类: PaperPack
并定义了2个即时variables: title
和author
–
然后我分配了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";
那么我如何计算并返回与该类创build的实例的数量?
不,你不能直接得到。 无论何时在实例中创build,添加任何数组,然后使用该数组属性访问它。
例如:
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]);
您可以创build一个工厂单例,用于计算请求的实例数量(然后您必须使用工厂创build所有实例)。 或者你可以在PaperPack
类中添加一个static
variables, PaperPack
增加一个static
variables(在init
方法中,你必须每次都调用init
)。
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;
对不起,如果有什么不对,代码是从内存写入
您也可以执行以下方法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
当你想要创build的对象的数量
[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)当你想要创build的对象的数量
NSLog(@"%d",pack1.count); NSLOg(@"%d",pack2.count);