獲取

2013-07-25 40 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);