2012-06-14 26 views
1

我有一個Singleton來管理我的應用程序中不同位置所需的一些變量。這是單身,通常稱之爲:使用Singleton時EXC_BAD_ACCESS代碼= 2

#import "General.h" 

static General *sharedMyManager = nil; 

@implementation General 

@synthesize user; 
@synthesize lon; 
@synthesize lat; 
@synthesize car; 
@synthesize firstmess; 
@synthesize firstfrom; 
@synthesize numcels; 

#pragma mark Singleton Methods 

+ (id)sharedManager { 
static dispatch_once_t onceToken; 
dispatch_once(&onceToken, ^{ 
    if (sharedMyManager == nil) { 
     sharedMyManager = [[self alloc] init]; 
    } 
}); 

return sharedMyManager; 
} 

- (id)init { 
if (self = [super init]) { 
    user = [[NSString alloc] initWithString:@"vacio"]; 
    numcels=0; 
} 
return self; 
} 

- (void)dealloc { 
// Should never be called, but just here for clarity really. 
} 

@end 

我用它在一個TableView中,存在於我的應用程序的一部分,這是一個聊天的屏幕信息。 我的意思是,每次應用程序收到或發送消息時,我都會向var「numcels」中添加1,這就是numberOfRowsInSection方法返回的值。

-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
General *general = [General sharedManager]; 
return *(general.numcels); //It freezes here 
} 

的問題是,當我運行該程序,它凍結在註釋行,說EXC_BAD_ACCESS代碼= 2。我想這個問題可能與單身人士有關,但不知道它究竟在哪裏。

任何幫助?先謝謝你。

------- --------編輯

-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
NSLog(@"Hemos entrado en cellForRowAtIndexPath"); 
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"]; 
if(!cell){ 
UITableViewCell *cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"UITableViewCell"]; 
} 
General *general = [General sharedManager]; 
NSString *text=general.firstmess;//it crashes now here 
NSString *remite=general.firstfrom; 
[[cell textLabel]setText:remite]; 
[[cell detailTextLabel] setText:text]; 

return cell; 
} 

而且general.h中,通過要求:

#import <Foundation/Foundation.h> 

@interface General : NSObject { 
NSString *user; 
double lat; 
double lon; 
} 

@property (nonatomic, retain) NSString *user; 
@property (assign, nonatomic) double lat; 
@property (assign, nonatomic) double lon; 
@property (assign, nonatomic) Boolean car; 
@property (assign, nonatomic) NSString *firstmess; 
@property (assign, nonatomic) NSString *firstfrom; 
@property (assign, nonatomic) int numcels; 

+ (id)sharedManager; 

@end 
+0

你爲什麼要做*(general.numcels); ..?我的意思是明星背後的想法是什麼? –

+0

如果我不這樣做,它會顯示一條警告「不兼容的整數轉換指針...」 – Fustigador

+0

你能告訴我你的.h ...嗎? –

回答

0

解決了第一個問題之後(感謝Ankit的幫助),它在我在EDIT下面評論過的行中崩潰了。我只是改變

@property (nonatomc, assign) NSString *firstmess; 

@property (retain, nonatomic) NSString *firstmess; 

而且它不會再崩潰。

謝謝!

2

它應該是這樣的:

return general.numcels;

numcels是一個整數,你不能應用*運營商。

相關問題