问题
I have created a custom class in xcode: PaperPack
and defined 2 instant variables: title
and author
-
Then I alloc 2 instances of the class as below:
PaperPack *pack1 = [[PaperPack alloc] init];
pack1.title = @"Title 1";
pack1.author = @"Author";
PaperPack *pack2 = [[PaperPack alloc] init];
pack1.title = @"Title 2";
pack1.author = @"Author";
Then how do I count and return number of instances I have created with that class?
回答1:
No you can not get directly. Whenever you create in instance add it any Array and then access it using that array properties.
Ex :
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];
Then get count as :
NSLog(@"TOTAL INSTANCES : %d",[allInstancesArray count]);
回答2:
You could create a factory singleton which you use to count the number of instances requested (then you must create all instances using the factory). Or you could add a static
variable into the PaperPack
class and increment it each time (in the init
method, then you must call init
each time).
回答3:
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;
}
To use it:
Just call class method which will increase "createdCount" value
PaperPack *firstPaperPack = [PaperPack paperPack];
PaperPack *secondPaperPack = [PaperPack paperPack];
and to count:
NSInteger count = [PaperPack sharedPaperPack].createdCount;
Sorry if something is incorrect, code is written from memory
回答4:
You can also do the following Method 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
when you want the number of objects created
[PaperPack count];
Method 2
1)add a property to your class PaperPack.h
@property (nonatomic,assign) NSInteger count ;
2)synthesize it in PaperPack.m
@synthesize count ;
3) modify init
method
-(id)init
{
if([super init])
{
self = [super init] ;
self.count = self.count + 1 ;
}
return self ;
}
4)when you want the number of objects created
NSLog(@"%d",pack1.count);
NSLOg(@"%d",pack2.count);
来源:https://stackoverflow.com/questions/17850883/get-number-of-instances-of-custom-class